Exemplo n.º 1
0
        /// <summary>
        /// Updates a Rock location to match an Ideal Postcodes ResultAddress
        /// </summary>
        /// <param name="location">The Rock location to be modified</param>
        /// <param name="address">The IdeaL Postcodes ResultAddress to copy the data from</param>
        /// <returns>Whether the Location was succesfully geocoded</returns>
        public bool UpdateLocation(Rock.Model.Location location, ResultAddress address)
        {
            location.Street1 = address.line_1;
            location.Street2 = address.line_2;
            if (!string.IsNullOrWhiteSpace(address.dependant_locality) && address.dependant_locality != address.line_2)
            {
                location.City = address.dependant_locality;
            }
            else
            {
                string city = address.post_town;
                city          = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(city.ToLower());
                location.City = city;
            }

            location.State                = address.county;
            location.PostalCode           = address.postcode;
            location.StandardizedDateTime = RockDateTime.Now;

            // If ResultAddress has geocoding data set it on Location
            if (address.latitude.HasValue && address.longitude.HasValue)
            {
                bool setLocationResult = location.SetLocationPointFromLatLong(address.latitude.Value, address.longitude.Value);
                if (setLocationResult)
                {
                    location.GeocodedDateTime = RockDateTime.Now;
                }
                return(setLocationResult);
            }
            return(false);
        }
Exemplo n.º 2
0
        /// <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);
        }
Exemplo n.º 3
0
 /// <summary>
 /// Gets the values.
 /// </summary>
 /// <param name="location">The location.</param>
 public void GetValues(Rock.Model.Location location)
 {
     if (location != null)
     {
         if (!string.IsNullOrWhiteSpace(this.Street1) ||
             !string.IsNullOrWhiteSpace(this.Street2) ||
             !string.IsNullOrWhiteSpace(this.City))
         {
             location.Country    = Country;
             location.Street1    = Street1;
             location.Street2    = Street2;
             location.City       = City;
             location.County     = County;
             location.State      = State;
             location.PostalCode = PostalCode;
         }
         else
         {
             location.Country    = null;
             location.Street1    = null;
             location.Street2    = null;
             location.City       = null;
             location.County     = null;
             location.State      = null;
             location.PostalCode = null;
         }
     }
 }
Exemplo n.º 4
0
        /// <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);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Verifies a given location.
        /// </summary>
        /// <param name="location">The location.</param>
        /// <param name="resultMsg">The result message.</param>
        /// <returns>Result of the verification.</returns>
        public override VerificationResult Verify(Rock.Model.Location location, out string resultMsg)
        {
            if (location.Country != "SG" || string.IsNullOrEmpty(location.PostalCode))
            {
                resultMsg = "No match";
                return(VerificationResult.None);
            }

            var query = String.Format("{0} {1} Singapore {2}", location.Street1, location.Street2, location.PostalCode);

            // Remove unit number from the query since OneMap does return results with it.
            query = Regex.Replace(query, UnitNumberRegex, "");

            // Remove "blk" from query since OneMap does not return results with it.
            query = Regex.Replace(query, @"\bblk\b", "", RegexOptions.IgnoreCase);

            var client  = new RestClient("https://developers.onemap.sg");
            var request = new RestRequest("commonapi/search")
                          .AddParameter("returnGeom", "Y")
                          .AddParameter("getAddrDetails", "Y")
                          .AddParameter("searchVal", query);
            var restResponse = client.Get(request);

            if (restResponse.StatusCode != System.Net.HttpStatusCode.OK)
            {
                resultMsg = restResponse.StatusDescription;
                return(VerificationResult.ConnectionError);
            }

            var result = JObject.Parse(restResponse.Content)["results"]
                         .Children()
                         .Select(r => r.ToObject <OneMapSearchResult>())
                         .Where(r => r.Postal.Equals(location.PostalCode.Trim()))
                         .FirstOrDefault();

            if (result == null)
            {
                resultMsg = "No match";
                return(VerificationResult.None);
            }

            var textInfo = CultureInfo.CurrentCulture.TextInfo;

            // Extract unit number and add it to Street2.
            var matches = new Regex(UnitNumberRegex).Matches(String.Format("{0} {1}", location.Street1, location.Street2));

            location.Street2 = matches.Count == 1 ? matches[0].Value : null;

            location.PostalCode = result.Postal;
            location.Street1    = String.Format("{0} {1}", result.BlockNumber.ToUpper(), textInfo.ToTitleCase(result.RoadName.ToLower()));
            location.County     = null;
            location.City       = null;
            location.State      = null;
            location.SetLocationPointFromLatLong(result.Latitude, result.Longitude);

            resultMsg = "Match";
            return(VerificationResult.Standardized | VerificationResult.Geocoded);
        }
Exemplo n.º 6
0
        public void SetUnmaskedValues(Rock.Model.Location location)
        {
            base.SetValues(location);

            if (location != null)
            {
                UnmaskedStreet1 = location.Street1;
            }
        }
Exemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImpactLocation"/> class.
 /// </summary>
 /// <param name="location">The location.</param>
 public ImpactLocation(Rock.Model.Location location)
 {
     Street1    = location.Street1;
     Street2    = location.Street2;
     City       = location.City;
     State      = location.State;
     PostalCode = location.PostalCode;
     Country    = location.Country;
 }
Exemplo n.º 8
0
        public void GetUnmaskedValues(Rock.Model.Location location)
        {
            base.GetValues(location);

            if (location != null && !string.IsNullOrWhiteSpace(this.UnmaskedStreet1))
            {
                location.Street1 = this.UnmaskedStreet1;
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Standardizes the address
        /// </summary>
        /// <param name="location">The location.</param>
        /// <param name="result">The AddressCheck result code</param>
        /// <returns>
        /// True/False value of whether the address was standardized succesfully
        /// </returns>
        public override bool Standardize(Rock.Model.Location location, out string result)
        {
            if (location != null)
            {
                var requestArray = new RequestArray();
                requestArray.CustomerID       = GetAttributeValue("CustomerId");
                requestArray.OptAddressParsed = "True";

                RequestArrayRecord requestAddress = new RequestArrayRecord();
                requestAddress.AddressLine1 = location.Street1;
                requestAddress.AddressLine2 = location.Street2;
                requestAddress.City         = location.City;
                requestAddress.State        = location.State;
                requestAddress.Zip          = location.Zip;
                requestAddress.RecordID     = "1";

                requestArray.Record    = new RequestArrayRecord[1];
                requestArray.Record[0] = requestAddress;

                ServiceClient serviceClient = new ServiceClient();
                var           responseArray = serviceClient.doAddressCheck(requestArray);

                if (responseArray.TotalRecords == "1" && responseArray.Record[0].RecordID == "1")
                {
                    result = responseArray.Record[0].Results;

                    if (responseArray.Record[0].Results.Contains("AS01"))
                    {
                        ResponseArrayRecordAddress responseAddress = responseArray.Record[0].Address;
                        location.Street1 = responseAddress.Address1;
                        location.Street2 = responseAddress.Address2;
                        location.City    = responseAddress.City.Name;
                        location.State   = responseAddress.State.Abbreviation;
                        location.Zip     = responseAddress.Zip + '-' + responseAddress.Plus4;
                        if (location.Street2.Trim() == string.Empty &&
                            responseAddress.Suite.Trim() != string.Empty)
                        {
                            location.Street2 = responseAddress.Suite;
                        }

                        return(true);
                    }
                }
                else
                {
                    result = "No Records Returned";
                }
            }
            else
            {
                result = "Null Address";
            }

            return(false);
        }
Exemplo n.º 10
0
        /// <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);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Standardizes and Geocodes an address using the Ideal Postcodes service
        /// </summary>
        /// <param name="location">The location.</param>
        /// <param name="resultMsg">The result</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)
        {
            resultMsg = string.Empty;
            var result = VerificationResult.None;


            string inputKey = GetAttributeValue("APIKey");
            string tags     = CreateTags();

            //Create address that encodes correctly
            string inputAddress;

            CreateInputAddress(location, out inputAddress);

            //restsharp API request
            var client   = new RestClient("https://api.ideal-postcodes.co.uk/");
            var request  = BuildRequest(inputKey, inputAddress, tags);
            var response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.OK)
            //Deserialize response into object
            {
                var settings = new JsonSerializerSettings
                {
                    NullValueHandling     = NullValueHandling.Ignore,
                    MissingMemberHandling = MissingMemberHandling.Ignore
                };
                var idealResponse = JsonConvert.DeserializeObject <RootObject>(response.Content, settings);
                var idealAddress  = idealResponse.result.hits;
                if (idealAddress.Any())
                {
                    var address = idealAddress.FirstOrDefault();
                    resultMsg = string.Format("Verified by Ideal Postcodes UDPRN: {0}", address?.udprn);
                    bool updateResult = UpdateLocation(location, address);
                    result = updateResult ? VerificationResult.Geocoded : VerificationResult.Standardized;
                }
                else
                {
                    resultMsg = "No match.";
                }
            }
            else
            {
                result = VerificationResult.ConnectionError;
            }

            location.StandardizeAttemptedServiceType = "IdealPostcodes";
            location.StandardizeAttemptedDateTime    = RockDateTime.Now;

            location.GeocodeAttemptedServiceType = "IdealPostcodes";
            location.GeocodeAttemptedDateTime    = RockDateTime.Now;
            return(result);
        }
        /// <summary>
        /// Updates a Rock location to match a mappify.io StreetAddressRecord
        /// </summary>
        /// <param name="location">The Rock location to be modified</param>
        /// <param name="address">The mappify.io StreetAddressRecord to copy the data from</param>
        /// <returns>Whether the Location was succesfully geocoded</returns>
        public bool UpdateLocation(Rock.Model.Location location, StreetAddressRecord address)
        {
            string addressStreet = address.streetAddress;

            string[] separatingStrings = { ", " };
            string[] addressComponents = addressStreet.Split(separatingStrings, StringSplitOptions.RemoveEmptyEntries);

            if (addressComponents.Length >= 2)
            {
                if (addressComponents.Length == 2)
                {
                    location.Street1 = addressComponents[0];
                    location.Street2 = "";
                }
                else if (addressComponents.Length == 3)
                {
                    location.Street1 = addressComponents[0];
                    location.Street2 = addressComponents[1];
                }
                else
                {
                    List <string> parts = new List <string>();
                    for (int i = 0; i < (addressComponents.Length - 2); i++)
                    {
                        parts.Add(addressComponents[i]);
                    }
                    location.Street1 = String.Join(" ", parts);
                    location.Street2 = addressComponents[addressComponents.Length - 2];
                }
            }

            string city = address.suburb;

            city                          = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(city.ToLower());
            location.City                 = city;
            location.State                = address.state;
            location.PostalCode           = address.postCode;
            location.StandardizedDateTime = RockDateTime.Now;

            // If StreetAddressRecord has geocoding data set it on Location
            if (address.location.lat.HasValue && address.location.lon.HasValue)
            {
                bool setLocationResult = location.SetLocationPointFromLatLong(address.location.lat.Value, address.location.lon.Value);
                if (setLocationResult)
                {
                    location.GeocodedDateTime = RockDateTime.Now;
                }
                return(setLocationResult);
            }

            return(false);
        }
Exemplo n.º 13
0
        /// <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 successfully verified</param>
        /// <param name="result">The result code unique to the service.</param>
        /// <returns>
        /// True/False value of whether the address was geocoded successfully
        /// </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);
        }
Exemplo n.º 14
0
 /// <summary>
 /// Sets the values.
 /// </summary>
 /// <param name="location">The location.</param>
 public void SetValues(Rock.Model.Location location)
 {
     if (location != null)
     {
         Country    = location.Country;
         Street1    = location.Street1;
         Street2    = location.Street2;
         City       = location.City;
         State      = location.State;
         PostalCode = location.PostalCode;
     }
     else
     {
         Country    = GetDefaultCountry();
         Street1    = string.Empty;
         Street2    = string.Empty;
         City       = string.Empty;
         State      = GetDefaultState();
         PostalCode = string.Empty;
     }
 }
Exemplo n.º 15
0
        /// <summary>
        /// Gets the values.
        /// </summary>
        /// <param name="location">The location.</param>
        public void GetValues(Rock.Model.Location location)
        {
            if (location == null)
            {
                return;
            }

            if (IsEmpty())
            {
                // No non-default values have been entered, so return an empty location.
                location.Country    = null;
                location.Street1    = null;
                location.Street2    = null;
                location.City       = null;
                location.County     = null;
                location.State      = null;
                location.PostalCode = null;
            }
            else
            {
                // Get field values, nullifying any fields that are not available for the selected country.
                var street1    = GetLocationFieldValue(this.Street1, _AddressLine1Requirement);
                var street2    = GetLocationFieldValue(this.Street2, _AddressLine2Requirement);
                var city       = GetLocationFieldValue(this.City, _CityRequirement);
                var county     = GetLocationFieldValue(this.County, _LocalityRequirement);
                var state      = GetLocationFieldValue(this.State, _StateRequirement);
                var postalCode = GetLocationFieldValue(this.PostalCode, _PostalCodeRequirement);

                location.Country = this.Country;

                // Get field values masked by requirements.
                // If the Country field has been modified for this Location, nullify fields that are no longer available.
                location.Street1    = street1;
                location.Street2    = street2;
                location.City       = city;
                location.County     = county;
                location.State      = state;
                location.PostalCode = postalCode;
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Updates a Rock location to match a Addy AddressDetail
        /// </summary>
        /// <param name="location">The Rock location to be modified</param>
        /// <param name="address">The Addy AddressDetail to copy the data from</param>
        /// <returns>Whether the Location was succesfully geocoded</returns>
        public bool UpdateLocation(Rock.Model.Location location, AddressDetail address)
        {
            location.Street1              = address.address1;
            location.Street2              = address.address2;
            location.City                 = address.city;
            location.State                = String.Empty;
            location.PostalCode           = address.postcode;
            location.StandardizedDateTime = RockDateTime.Now;

            // If AddressDetail has geocoding data set it on Location
            if (address.x.IsNotNullOrWhiteSpace() && address.y.IsNotNullOrWhiteSpace())
            {
                bool setLocationResult = location.SetLocationPointFromLatLong(Convert.ToDouble(address.y), Convert.ToDouble(address.x));
                if (setLocationResult)
                {
                    location.GeocodedDateTime = RockDateTime.Now;
                }
                return(setLocationResult);
            }

            return(false);
        }
 /// <summary>
 /// Abstract method for verifying a location.  Derived classes should implement
 /// this method to perform an verification action on an address (i.e. standardize, geocode, etc.).
 /// </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 abstract bool VerifyLocation(Rock.Model.Location location, bool reVerify, out string result);
Exemplo n.º 18
0
        /// <summary>
        /// Standardizes the 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 standardized succesfully
        /// </returns>
        public override bool VerifyLocation(Rock.Model.Location location, bool reVerify, out string result)
        {
            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.StandardizedDateTime.HasValue ||
                    location.StandardizedDateTime.Value.CompareTo(RockDateTime.Now.AddSeconds(-30)) > 0 ||
                    reVerify
                ))
            {
                var requestArray = new RequestArray();
                requestArray.CustomerID       = GetAttributeValue("CustomerId");
                requestArray.OptAddressParsed = "True";

                RequestArrayRecord requestAddress = new RequestArrayRecord();
                requestAddress.AddressLine1 = location.Street1;
                requestAddress.AddressLine2 = location.Street2;
                requestAddress.City         = location.City;
                requestAddress.State        = location.State;
                requestAddress.Zip          = location.PostalCode;
                requestAddress.Country      = location.Country;
                requestAddress.RecordID     = "1";

                requestArray.Record    = new RequestArrayRecord[1];
                requestArray.Record[0] = requestAddress;

                ServiceClient serviceClient = new ServiceClient();
                var           responseArray = serviceClient.doAddressCheck(requestArray);

                if (responseArray.TotalRecords == "1" && responseArray.Record[0].RecordID == "1")
                {
                    result = responseArray.Record[0].Results;
                    if (string.IsNullOrWhiteSpace(result))
                    {
                        result = responseArray.Results;
                    }

                    string[] validResultCodes = new string[] {
                        "AS01", // Address Fully Verified
                        "AS09"  // Foreign Address
                    };

                    if (validResultCodes.Any(a => responseArray.Record[0].Results.Contains(a)))
                    {
                        bool foreignAddress = responseArray.Record[0].Results.Contains("AS09");
                        ResponseArrayRecordAddress responseAddress = responseArray.Record[0].Address;
                        location.Street1 = responseAddress.Address1;
                        location.Street2 = responseAddress.Address2;
                        location.City    = responseAddress.City.Name;
                        if (!foreignAddress || !string.IsNullOrWhiteSpace(responseAddress.State.Abbreviation))
                        {
                            // only set the State if we got a AS01 or a State back
                            location.State = responseAddress.State.Abbreviation;
                        }

                        if (!foreignAddress || !string.IsNullOrWhiteSpace(responseAddress.Zip))
                        {
                            // only set the PostalCode if we got a AS01 or a Zip back
                            location.PostalCode = responseAddress.Zip;
                            if (!string.IsNullOrWhiteSpace(requestAddress.Plus4))
                            {
                                location.PostalCode = responseAddress.Zip + '-' + responseAddress.Plus4;
                            }
                            else
                            {
                                location.PostalCode = responseAddress.Zip;
                            }
                        }

                        if (location.Street2.Trim() == string.Empty &&
                            responseAddress.Suite.Trim() != string.Empty)
                        {
                            location.Street2 = responseAddress.Suite;
                        }

                        location.StandardizedDateTime = RockDateTime.Now;
                    }
                }
                else
                {
                    result = "No Records Returned";
                }

                location.StandardizeAttemptedServiceType = "MelissaData";
                location.StandardizeAttemptedDateTime    = RockDateTime.Now;
                location.StandardizeAttemptedResult      = result;
            }

            // MelissaData only standardizes addresses, it does not geocode, therefore
            // always return false so that next verifcation service will run
            return(false);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Standardizes and Geocodes an address using the Addy service
        /// </summary>
        /// <param name="location">The location</param>
        /// <param name="resultMsg">The result</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)
        {
            resultMsg = string.Empty;
            VerificationResult result = VerificationResult.None;

            string apiKey    = GetAttributeValue("APIKey");
            string apiSecret = GetAttributeValue("APISecret");

            //Create input streetAddress string to send to Addy
            var    addressParts  = new[] { location.Street1, location.Street2, location.City, location.State, location.PostalCode };
            string streetAddress = string.Join(" ", addressParts.Where(s => !string.IsNullOrEmpty(s)));

            //Restsharp API request
            var client   = new RestClient("https://api.addy.co.nz/");
            var request  = BuildRequest(streetAddress, apiKey, apiSecret);
            var response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.OK)
            //Deserialize response into object
            {
                var settings = new JsonSerializerSettings
                {
                    NullValueHandling     = NullValueHandling.Ignore,
                    MissingMemberHandling = MissingMemberHandling.Ignore
                };
                var addyResponse            = JsonConvert.DeserializeObject <AddressVerificationResult>(response.Content, settings);
                var addyAddress             = addyResponse.address;
                var addyAddressAlternatives = addyResponse.alternatives;
                if (addyAddress.IsNotNull())
                {
                    location.StandardizeAttemptedResult = addyAddress.linzid.ToString();

                    if (addyAddressAlternatives.IsNull() || addyAddressAlternatives.Count() == 0)
                    {
                        bool updateResult    = UpdateLocation(location, addyAddress);
                        var  generalMsg      = string.Format("Verified with Addy to match LINZ: {0}. Input address: {1}. ", addyAddress.linzid.ToString(), streetAddress);
                        var  standardisedMsg = "Coordinates NOT updated.";
                        var  geocodedMsg     = "Coordinates updated.";

                        if (updateResult)
                        {
                            //result = VerificationResult.Geocoded;
                            resultMsg = generalMsg + geocodedMsg;
                        }
                        else
                        {
                            //result = VerificationResult.Standardized;
                            resultMsg = generalMsg + standardisedMsg;
                        }
                        result |= VerificationResult.Standardized;
                    }
                    else
                    {
                        resultMsg = string.Format("Not verified: {0}", addyResponse.reason);
                        if (addyAddressAlternatives.Count() > 0)
                        {
                            var tooManyMsg = "Too many to display...";
                            foreach (AddressReference alternate in addyAddressAlternatives)
                            {
                                if (resultMsg.Length + alternate.a.Length >= 195)
                                {
                                    if (resultMsg.Length + tooManyMsg.Length <= 200)
                                    {
                                        resultMsg += tooManyMsg;
                                    }
                                    else
                                    {
                                        resultMsg += "...";
                                    }

                                    break;
                                }
                                else
                                {
                                    resultMsg += alternate.a + "; ";
                                }
                            }
                        }
                    }
                }
                else
                {
                    resultMsg = addyResponse.reason;
                }
            }
            else
            {
                result    = VerificationResult.ConnectionError;
                resultMsg = response.StatusDescription;
            }

            location.StandardizeAttemptedServiceType = "Addy";
            location.StandardizeAttemptedDateTime    = RockDateTime.Now;

            location.GeocodeAttemptedServiceType = "Addy";
            location.GeocodeAttemptedDateTime    = RockDateTime.Now;
            return(result);
        }
Exemplo n.º 20
0
        public void CreateInputAddress(Rock.Model.Location location, out string inputAddress)
        {
            var addressParts = new[] { location.Street1, location.Street2, location.City, location.PostalCode };

            inputAddress = string.Join(" ", addressParts.Where(s => !string.IsNullOrEmpty(s)));
        }
Exemplo n.º 21
0
        /// <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);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Creates the document.
        /// </summary>
        /// <param name="financialTransactionQry">The financial transaction qry.</param>
        /// <returns></returns>
        public Document RunReport()
        {
            UpdateProgress( "Connecting..." );

            // Login and setup options for REST calls
            RockConfig rockConfig = RockConfig.Load();

            _rockRestClient = new RockRestClient( rockConfig.RockBaseUrl );
            _rockRestClient.Login( rockConfig.Username, rockConfig.Password );

            _contributionStatementOptionsREST = new Rock.Net.RestParameters.ContributionStatementOptions
            {
                StartDate = Options.StartDate,
                EndDate = Options.EndDate,
                AccountIds = Options.AccountIds,
                PersonId = Options.PersonId,
                OrderByPostalCode = true
            };

            var organizationAddressAttribute = _rockRestClient.GetData<List<Rock.Model.Attribute>>( "api/attributes", "Key eq 'OrganizationAddress'" ).FirstOrDefault();
            if ( organizationAddressAttribute != null )
            {
                Guid locationGuid = Guid.Empty;
                if ( Guid.TryParse( organizationAddressAttribute.DefaultValue, out locationGuid ) )
                {
                    _organizationAddressLocation = _rockRestClient.GetDataByGuid<Rock.Model.Location>( "api/locations", locationGuid );
                }
            }

            // If we don't have a _organizationAddressLocation, just create an empty location
            _organizationAddressLocation = _organizationAddressLocation ?? new Rock.Model.Location();

            // setup report layout and events
            DocumentLayout report = new DocumentLayout( this.Options.LayoutFile );

            //// if there is an imgLogo and the path is "logo.jpg", use the logo specified in rockconfig.  
            //// We have to read the layout as Xml first to figure out what the Path of the imgLogo
            XmlDocument layoutXmlDoc = new XmlDocument();
            layoutXmlDoc.Load( this.Options.LayoutFile );
            var imageNodes = layoutXmlDoc.GetElementsByTagName( "image" );
            foreach ( var imageNode in imageNodes.OfType<XmlNode>() )
            {
                string imagePath = imageNode.Attributes["path"].Value;
                string imageId =imageNode.Attributes["id"].Value;
                if (imageId.Equals("imgLogo" ) &&  imagePath.Equals( RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase )  )
                {
                    Image imgLogo = report.GetReportElementById( "imgLogo" ) as Image;
                    if ( imgLogo != null )
                    {
                        try
                        {
                            if ( !rockConfig.LogoFile.Equals( RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase ) )
                            {
                                imgLogo.ImageData = ceTe.DynamicPDF.Imaging.ImageData.GetImage( rockConfig.LogoFile );
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception( "Error loading Logo Image: " + rockConfig.LogoFile + "\n\n" + ex.Message);
                        }
                    }
                }
            }


            Query query = report.GetQueryById( "OuterQuery" );
            if ( query == null )
            {
                throw new MissingReportElementException( "Report requires a QueryElement named 'OuterQuery'" );
            }

            query.OpeningRecordSet += mainQuery_OpeningRecordSet;

            Query orgInfoQuery = report.GetQueryById( "OrgInfoQuery" );
            if ( orgInfoQuery == null )
            {
                throw new MissingReportElementException( "Report requires a QueryElement named 'OrgInfoQuery'" );
            }

            orgInfoQuery.OpeningRecordSet += orgInfoQuery_OpeningRecordSet;

            _accountSummaryQuery = report.GetQueryById( "AccountSummaryQuery" );

            if ( _accountSummaryQuery == null )
            {
                // not required.  Just don't do anything if it isn't there
            }
            else
            {
                _accountSummaryQuery.OpeningRecordSet += delegate( object s, OpeningRecordSetEventArgs ee )
                {
                    // create a recordset for the _accountSummaryQuery which is the GroupBy summary of AccountName, Amount
                    var summaryTable = _transactionsDataTable.AsEnumerable().GroupBy( g => g["AccountId"] ).Select( a => new
                    {
                        AccountName = a.Max(x => x["AccountName"].ToString()),
                        Amount = a.Sum( x => decimal.Parse( x["Amount"].ToString() ) )
                    } ).OrderBy( o => o.AccountName );

                    ee.RecordSet = new EnumerableRecordSet( summaryTable );
                };
            }

            UpdateProgress( "Getting Data..." );

            // get outer query data from Rock database via REST now vs in mainQuery_OpeningRecordSet to make sure we have data
            DataSet personGroupAddressDataSet = _rockRestClient.PostDataWithResult<Rock.Net.RestParameters.ContributionStatementOptions, DataSet>( "api/FinancialTransactions/GetContributionPersonGroupAddress", _contributionStatementOptionsREST );
            _personGroupAddressDataTable = personGroupAddressDataSet.Tables[0];
            RecordCount = _personGroupAddressDataTable.Rows.Count;

            if ( RecordCount > 0 )
            {
                Document doc = report.Run();
                return doc;
            }
            else
            {
                return null;
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Standardizes the address
        /// </summary>
        /// <param name="location">The location.</param>
        /// <param name="resultMsg">The result MSG.</param>
        /// <returns>
        /// True/False value of whether the address was standardized successfully
        /// </returns>
        public override VerificationResult Verify(Rock.Model.Location location, out string resultMsg)
        {
            VerificationResult result = VerificationResult.None;

            resultMsg = string.Empty;

            var requestArray = new RequestArray();

            requestArray.CustomerID       = GetAttributeValue("CustomerId");
            requestArray.OptAddressParsed = "True";

            RequestArrayRecord requestAddress = new RequestArrayRecord();

            requestAddress.AddressLine1 = location.Street1;
            requestAddress.AddressLine2 = location.Street2;
            requestAddress.City         = location.City;
            requestAddress.State        = location.State;
            requestAddress.Zip          = location.PostalCode;
            requestAddress.Country      = location.Country;
            requestAddress.RecordID     = "1";

            requestArray.Record    = new RequestArrayRecord[1];
            requestArray.Record[0] = requestAddress;

            ServiceClient serviceClient = new ServiceClient();
            var           responseArray = serviceClient.doAddressCheck(requestArray);

            if (responseArray.TotalRecords == "1" && responseArray.Record[0].RecordID == "1")
            {
                resultMsg = responseArray.Record[0].Results;
                if (string.IsNullOrWhiteSpace(resultMsg))
                {
                    resultMsg = responseArray.Results;
                }

                string[] validResultCodes = new string[] {
                    "AS01", // Address Fully Verified
                    "AS09"  // Foreign Address
                };

                if (validResultCodes.Any(a => responseArray.Record[0].Results.Contains(a)))
                {
                    bool foreignAddress = responseArray.Record[0].Results.Contains("AS09");
                    ResponseArrayRecordAddress responseAddress = responseArray.Record[0].Address;
                    location.Street1 = responseAddress.Address1;
                    location.Street2 = responseAddress.Address2;
                    location.City    = responseAddress.City.Name;
                    if (!foreignAddress || !string.IsNullOrWhiteSpace(responseAddress.State.Abbreviation))
                    {
                        // only set the State if we got a AS01 or a State back
                        location.State = responseAddress.State.Abbreviation;
                    }

                    if (!foreignAddress || !string.IsNullOrWhiteSpace(responseAddress.Zip))
                    {
                        // only set the PostalCode if we got a AS01 or a Zip back
                        location.PostalCode = responseAddress.Zip;
                        if (!string.IsNullOrWhiteSpace(requestAddress.Plus4))
                        {
                            location.PostalCode = responseAddress.Zip + '-' + responseAddress.Plus4;
                        }
                        else
                        {
                            location.PostalCode = responseAddress.Zip;
                        }
                    }

                    if (location.Street2.Trim() == string.Empty && responseAddress.Suite.Trim() != string.Empty)
                    {
                        location.Street2 = responseAddress.Suite;
                    }

                    result = VerificationResult.Standardized;
                }
            }
            else
            {
                result    = VerificationResult.ConnectionError;
                resultMsg = "No Records Returned";
            }

            return(result);
        }
Exemplo n.º 24
0
        /// <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
                ))
            {
                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);
        }
Exemplo n.º 25
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);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Creates the document.
        /// </summary>
        /// <param name="financialTransactionQry">The financial transaction qry.</param>
        /// <returns></returns>
        public Document RunReport()
        {
            UpdateProgress("Connecting...");

            // Login and setup options for REST calls
            RockConfig rockConfig = RockConfig.Load();

            _rockRestClient = new RockRestClient(rockConfig.RockBaseUrl);
            _rockRestClient.Login(rockConfig.Username, rockConfig.Password);

            _contributionStatementOptionsREST = new Rock.Net.RestParameters.ContributionStatementOptions
            {
                StartDate      = Options.StartDate,
                EndDate        = Options.EndDate,
                AccountIds     = Options.AccountIds,
                PersonId       = Options.PersonId,
                OrderByZipCode = true
            };

            var organizationAddressAttribute = _rockRestClient.GetData <List <Rock.Model.Attribute> >("api/attributes", "Key eq 'OrganizationAddress'").FirstOrDefault();

            if (organizationAddressAttribute != null)
            {
                Guid locationGuid = Guid.Empty;
                if (Guid.TryParse(organizationAddressAttribute.DefaultValue, out locationGuid))
                {
                    _organizationAddressLocation = _rockRestClient.GetDataByGuid <Rock.Model.Location>("api/locations", locationGuid);
                }
            }

            // If we don't have a _organizationAddressLocation, just create an empty location
            _organizationAddressLocation = _organizationAddressLocation ?? new Rock.Model.Location();

            // setup report layout and events
            DocumentLayout report = new DocumentLayout(this.Options.LayoutFile);

            //// if there is an imgLogo and the path is "logo.jpg", use the logo specified in rockconfig.
            //// We have to read the layout as Xml first to figure out what the Path of the imgLogo
            XmlDocument layoutXmlDoc = new XmlDocument();

            layoutXmlDoc.Load(this.Options.LayoutFile);
            var imageNodes = layoutXmlDoc.GetElementsByTagName("image");

            foreach (var imageNode in imageNodes.OfType <XmlNode>())
            {
                string imagePath = imageNode.Attributes["path"].Value;
                string imageId   = imageNode.Attributes["id"].Value;
                if (imageId.Equals("imgLogo") && imagePath.Equals(RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase))
                {
                    Image imgLogo = report.GetReportElementById("imgLogo") as Image;
                    if (imgLogo != null)
                    {
                        try
                        {
                            if (!rockConfig.LogoFile.Equals(RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase))
                            {
                                imgLogo.ImageData = ceTe.DynamicPDF.Imaging.ImageData.GetImage(rockConfig.LogoFile);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Error loading Logo Image: " + rockConfig.LogoFile + "\n\n" + ex.Message);
                        }
                    }
                }
            }


            Query query = report.GetQueryById("OuterQuery");

            if (query == null)
            {
                throw new MissingReportElementException("Report requires a QueryElement named 'OuterQuery'");
            }

            query.OpeningRecordSet += mainQuery_OpeningRecordSet;

            Query orgInfoQuery = report.GetQueryById("OrgInfoQuery");

            if (orgInfoQuery == null)
            {
                throw new MissingReportElementException("Report requires a QueryElement named 'OrgInfoQuery'");
            }

            orgInfoQuery.OpeningRecordSet += orgInfoQuery_OpeningRecordSet;

            _accountSummaryQuery = report.GetQueryById("AccountSummaryQuery");

            if (_accountSummaryQuery == null)
            {
                // not required.  Just don't do anything if it isn't there
            }
            else
            {
                _accountSummaryQuery.OpeningRecordSet += delegate(object s, OpeningRecordSetEventArgs ee)
                {
                    // create a recordset for the _accountSummaryQuery which is the GroupBy summary of AccountName, Amount
                    var summaryTable = _transactionsDataTable.AsEnumerable().GroupBy(g => g["AccountId"]).Select(a => new
                    {
                        AccountName = a.Max(x => x["AccountName"].ToString()),
                        Amount      = a.Sum(x => decimal.Parse(x["Amount"].ToString()))
                    }).OrderBy(o => o.AccountName);

                    ee.RecordSet = new EnumerableRecordSet(summaryTable);
                };
            }

            UpdateProgress("Getting Data...");

            // get outer query data from Rock database via REST now vs in mainQuery_OpeningRecordSet to make sure we have data
            DataSet personGroupAddressDataSet = _rockRestClient.PostDataWithResult <Rock.Net.RestParameters.ContributionStatementOptions, DataSet>("api/FinancialTransactions/GetContributionPersonGroupAddress", _contributionStatementOptionsREST);

            _personGroupAddressDataTable = personGroupAddressDataSet.Tables[0];
            RecordCount = _personGroupAddressDataTable.Rows.Count;

            if (RecordCount > 0)
            {
                Document doc = report.Run();
                return(doc);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 27
0
 /// <summary>
 /// Verifies the specified location.
 /// </summary>
 /// <param name="location">The location.</param>
 /// <param name="resultMsg">The result MSG.</param>
 /// <returns></returns>
 public virtual VerificationResult Verify(Rock.Model.Location location, out string resultMsg)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Standardizes and Geocodes an address using the mappify.io service
        /// </summary>
        /// <param name="location">The location.</param>
        /// <param name="resultMsg">The result</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)
        {
            resultMsg = string.Empty;
            VerificationResult result = VerificationResult.None;

            string apiKey = GetAttributeValue("APIKey");

            //Create address that encodes correctly
            var    addressParts  = new[] { location.Street1, location.Street2, location.City, location.State, location.PostalCode };
            string streetAddress = string.Join(" ", addressParts.Where(s => !string.IsNullOrEmpty(s)));

            //restsharp API request
            var client   = new RestClient("https://mappify.io/api/rpc/");
            var request  = BuildRequest(streetAddress, apiKey);
            var response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.OK)
            //Deserialize response into object
            {
                var settings = new JsonSerializerSettings
                {
                    NullValueHandling     = NullValueHandling.Ignore,
                    MissingMemberHandling = MissingMemberHandling.Ignore
                };
                var mappifyResponse = JsonConvert.DeserializeObject <ResponseObject>(response.Content, settings);
                var mappifyAddress  = mappifyResponse.result;
                if (mappifyAddress.Any())
                {
                    var address = mappifyAddress.FirstOrDefault();
                    int confidencePercentage = (int)(mappifyResponse.confidence * 100);

                    location.StandardizeAttemptedResult = address?.gnafId;

                    if (mappifyAddress.Count() == 1 || mappifyResponse.confidence >= 0.75)
                    {
                        bool updateResult    = UpdateLocation(location, address);
                        var  generalMsg      = string.Format("Verified with mappify.io to match GNAF: {0} with {1}% confidence. Input address: {2}. ", address?.gnafId, confidencePercentage, streetAddress);
                        var  standardisedMsg = "Coordinates NOT updated.";
                        var  geocodedMsg     = "Coordinates updated.";

                        if (updateResult)
                        {
                            result    = VerificationResult.Geocoded;
                            resultMsg = generalMsg + geocodedMsg;
                        }
                        else
                        {
                            result    = VerificationResult.Standardized;
                            resultMsg = generalMsg + standardisedMsg;
                        }
                    }
                    else
                    {
                        resultMsg = string.Format("Not verified: mappify.io closest matching address: {0} with {1}% confidence", address?.streetAddress, confidencePercentage);
                    }
                }
                else
                {
                    resultMsg = "No match.";
                }
            }
            else
            {
                result    = VerificationResult.ConnectionError;
                resultMsg = response.StatusDescription;
            }

            location.StandardizeAttemptedServiceType = "Mappify";
            location.StandardizeAttemptedDateTime    = RockDateTime.Now;

            location.GeocodeAttemptedServiceType = "Mappify";
            location.GeocodeAttemptedDateTime    = RockDateTime.Now;
            return(result);
        }
Exemplo n.º 29
0
 /// <summary>
 /// Abstract method for geocoding the specified address.  Derived classes should implement
 /// this method to geocode the address.
 /// </summary>
 /// <param name="location">The location.</param>
 /// <param name="result">The result code unique to the service.</param>
 /// <returns>
 /// True/False value of whether the address was standardized succesfully
 /// </returns>
 public abstract bool Geocode(Rock.Model.Location location, out string result);
Exemplo n.º 30
0
 public virtual bool VerifyLocation(Rock.Model.Location location, bool reVerify, out string result)
 {
     return(Verify(location, out result) != VerificationResult.None);
 }
Exemplo n.º 31
0
        /// <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);
        }