Exemplo n.º 1
0
        public void GetProfilesByNameAddress_ValidNA_ProfilesReturned()
        {
            //Arrange
            NameAddress nameAddress = new NameAddress
            {
                AddressLine = "129 West 81st Street",
                FirstName   = "Jerry",
                LastName    = "Seinfeld",
                City        = "New York",
                State       = "NY"
            };

            string jsonProfiles = Properties.Resources.JsonProfiles;

            Mock <IHttpTransport> httpTransportMock = new Mock <IHttpTransport>(MockBehavior.Strict);

            httpTransportMock.Setup(httpTransport => httpTransport.Request(It.IsAny <string>(), It.IsAny <ContentType>(), It.IsIn("GET", "POST"), null, null))
            .Returns(jsonProfiles);


            //Action
            NextCallerClient client   = new NextCallerClient(httpTransportMock.Object);
            string           profiles = client.GetByNameAddressJson(nameAddress);

            //Assert
            httpTransportMock.Verify(httpTransport => httpTransport.Request(It.IsAny <string>(), It.IsAny <ContentType>(), It.IsIn("GET", "POST"), null, null), Times.Once);

            Assert.IsNotNull(profiles);
            Assert.AreEqual(jsonProfiles, profiles);
        }
        public async Task <IActionResult> Edit(int id, [Bind("NameAddressId,FirstName,LastName,CompanyName,StreetAddress,City,PostalCode,ProvinceCode,Email,Phone")] NameAddress nameAddress)
        {
            if (id != nameAddress.NameAddressId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(nameAddress);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!NameAddressExists(nameAddress.NameAddressId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                TempData["Message"] = "Update successful.";
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ProvinceCode"] = new SelectList(_context.Province.OrderBy(a => a.Name), "Name", "Name");
            return(View(nameAddress));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Gets list of profiles, associated with the particular name-address or name-zip pair.
        /// Throws an exception if response status is 404.
        /// More information at: https://nextcaller.com/platform/documentation/v2.1/#/profiles/get-profile-name-and-address/curl.
        /// </summary>
        /// <param name="nameAddressData">Pair of name and address or name and zip code.</param>
        /// <param name="accountId">Platform account ID.</param>
        /// <returns>Profiles, associated with the particular name-address or name-zip pair.</returns>
        public string GetByNameAddressJson(NameAddress nameAddressData, string accountId = null)
        {
            var headers = PrepareAccountIdHeader(accountId);

            var parameters = new[]
            {
                new UrlParameter(nameAddressFirstNameParameterName, nameAddressData.FirstName ?? ""),
                new UrlParameter(nameAddressLastNameParameterName, nameAddressData.LastName ?? ""),
                new UrlParameter(nameAddressAddressParameterName, nameAddressData.AddressLine ?? ""),
                new UrlParameter(formatParameterName, DefaultResponseType.ToString())
            };
            var additional = nameAddressData.ZipCode != 0
                ? new[]
            {
                new UrlParameter(nameAddressZipParameterName, nameAddressData.ZipCode.ToString(CultureInfo.InvariantCulture))
            }
                : new[]
            {
                new UrlParameter(nameAddressCityParameterName, nameAddressData.City ?? ""),
                new UrlParameter(nameAddressStateParameterName, nameAddressData.State ?? "")
            };

            string url = BuildUrl(phoneUrl, parameters.Concat(additional).ToArray());

            return(httpTransport.Request(url, DefaultResponseType, headers: headers));
        }
        /// <summary>
        /// Gets list of profiles, associated with the particular name-address or name-zip pair.
        /// Throws an exception if response status is 404.
        /// More information at: https://nextcaller.com/documentation/v2.1/#/profiles/retreive-profile-name-address/curl.
        /// </summary>
        /// <param name="nameAddressData">Pair of name and address or name and zip code.</param>
        /// <returns>Profiles, associated with the particular name-address or name-zip pair.</returns>
        public IList <Profile> GetByNameAddress(NameAddress nameAddressData)
        {
            Utility.EnsureParameterValid(!(nameAddressData == null), "nameAddressData");

            string content = GetByNameAddressJson(nameAddressData);

            return(JsonSerializer.ParseProfileList(content));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Gets list of profiles, associated with the particular name-address or name-zip pair.
        /// Throws an exception if response status is 404.
        /// More info at: https://nextcaller.com/platform/documentation/v2.1/#/profiles/get-profile-name-and-address/curl.
        /// </summary>
        /// <param name="nameAddressData">Pair of name and address or name and zip code.</param>
        /// <param name="accountId">Platform account ID.</param>
        /// <returns>Profiles, associated with the particular name-address or name-zip pair.</returns>
        public IList <Profile> GetByNameAddress(NameAddress nameAddressData, string accountId = null)
        {
            Utility.EnsureParameterValid(!(nameAddressData == null), "nameAddressData");

            string response = GetByNameAddressJson(nameAddressData, accountId);

            return(JsonSerializer.ParseProfileList(response));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Check is location of geocodable object valid and replace it by candidate from local
        /// geocoder if exists.
        /// </summary>
        /// <param name="geocodable">Geocodable object to check.</param>
        /// <returns>Is geocodable object valid.</returns>
        private bool _SourceGeocodedObject(IGeocodable geocodable)
        {
            Debug.Assert(null != geocodable); // created

            bool isObjectGeocoded = false;

            // First check if name address pair exists in local geocoder database.
            // If exists - overwrite geolocation and address from it.
            App currentApp    = App.Current;
            var localGeocoder =
                new LocalGeocoder(currentApp.Geocoder, currentApp.NameAddressStorage);

            var nameAddress = new NameAddress();

            nameAddress.Name    = geocodable.ToString();
            nameAddress.Address = geocodable.Address.Clone() as Address;

            AddressCandidate localCandidate = localGeocoder.Geocode(nameAddress);

            if (localCandidate == null)
            {   // Update from internal object information.
                AppGeometry.Envelope extent = currentApp.Map.ImportCheckExtent;
                if (extent.IsPointIn(geocodable.GeoLocation.Value))
                {
                    geocodable.Address.MatchMethod =
                        currentApp.FindString("ImportSourceMatchMethod");
                    isObjectGeocoded = true;

                    // Full address property must be combined from other fields, because
                    // it is not importing field.
                    if (App.Current.Geocoder.AddressFormat == AddressFormat.MultipleFields)
                    {
                        GeocodeHelpers.SetFullAddress(geocodable.Address);
                    }
                    else
                    {
                        // Do nothing: do not update full address since
                        // it is used for geocoding in Single Address Field Format.
                    }
                }
                // Else could not locate object using X/Y attributes - need geocode.
            }
            else
            {   // Init from local candidate.
                // Set location.
                geocodable.GeoLocation = new AppGeometry.Point(localCandidate.GeoLocation.X,
                                                               localCandidate.GeoLocation.Y);
                // Set address.
                localCandidate.Address.CopyTo(geocodable.Address);

                isObjectGeocoded = true;
            }

            return(isObjectGeocoded);
        }
        public IActionResult Post([FromBody] VMNameAddress vmnameaddress)
        {
            Name nameToAdd = new Name
            {
                Id          = vmnameaddress.NameId,
                FirstName   = vmnameaddress.FirstName,
                LastName    = vmnameaddress.LastName,
                DateOfBirth = vmnameaddress.DateOfBirth,
                FatherId    = vmnameaddress.FatherId,
                MotherId    = vmnameaddress.MotherId
            };
            Address addressToAdd = new Address
            {
                Id            = vmnameaddress.AddressId,
                AddressType   = vmnameaddress.AddressType,
                StreetAddress = vmnameaddress.StreetAddress,
                City          = vmnameaddress.City,
                StateName     = vmnameaddress.StateName,
                PostalCode    = vmnameaddress.PostalCode
            };

            if (nameToAdd != null)
            {
                if (nameToAdd.Id == 0)
                {
                    _db.Names.Add(nameToAdd);
                    _db.SaveChanges();
                }
                if (addressToAdd != null)
                {
                    _db.Addresses.Add(addressToAdd);
                    _db.SaveChanges();

                    NameAddress nameaddress = new NameAddress
                    {
                        NameId = nameToAdd.Id,
                        //  Name = nameToAdd,
                        AddressId = addressToAdd.Id,
                        //  Address = addressToAdd
                    };
                    _db.NameAddresses.Add(nameaddress);
                    _db.SaveChanges();
                    return(Ok(nameaddress));
                }
                else
                {
                    return(BadRequest());
                }
            }
            else
            {
                return(BadRequest());
            }
        }
        public async Task <IActionResult> Create([Bind("NameAddressId,FirstName,LastName,CompanyName,StreetAddress,City,PostalCode,ProvinceCode,Email,Phone")] NameAddress nameAddress)
        {
            if (ModelState.IsValid)
            {
                _context.Add(nameAddress);
                await _context.SaveChangesAsync();

                TempData["Message"] = "Create successful.";
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ProvinceCode"] = new SelectList(_context.Province, "ProvinceCode", "ProvinceCode", nameAddress.ProvinceCode);
            return(View(nameAddress));
        }
Exemplo n.º 9
0
        public async Task <IActionResult> Create([Bind("NameAddressId,FirstName,LastName,CompanyName,StreetAddress,City,PostalCode,ProvinceCode,Email,Phone")] NameAddress nameAddress)
        {
            ViewData["ProvinceCode"] = new SelectList(_context.Province, "ProvinceCode", "ProvinceCode", nameAddress.ProvinceCode);
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(nameAddress);
                    await _context.SaveChangesAsync();

                    TempData["SuccessMessage"] = "Successfully Saved";
                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", $"error adding new record: {ex.GetBaseException().Message}");
            }
            return(View(nameAddress));
        }
        /** 生成默认的平台订单,主要是接入到E邮宝时相关默认字段的填充 */
        private PlatformOrder ObtainDefaultPlatformOrder()
        {
            PlatformOrder order = new PlatformOrder();

            order.ClctType = ConfigurationManager.AppSettings["clct_type"];
            order.Pod      = ConfigurationManager.AppSettings["pod"];
            order.Untread  = ConfigurationManager.AppSettings["untread"];

            NameAddress sender = new NameAddress();

            sender.Name     = ConfigurationManager.AppSettings["sender_name"];
            sender.PostCode = ConfigurationManager.AppSettings["sender_postcode"];
            sender.Phone    = ConfigurationManager.AppSettings["sender_phone"];
            sender.Mobile   = ConfigurationManager.AppSettings["sender_mobile"];
            sender.Country  = ConfigurationManager.AppSettings["sender_country"];
            sender.Province = ConfigurationManager.AppSettings["sender_province"];
            sender.City     = ConfigurationManager.AppSettings["sender_city"];
            sender.County   = ConfigurationManager.AppSettings["sender_county"];
            sender.Company  = ConfigurationManager.AppSettings["sender_company"];
            sender.Street   = ConfigurationManager.AppSettings["sender_street"];
            sender.Email    = ConfigurationManager.AppSettings["sender_email"];
            order.Sender    = sender;

            NameAddress collect = new NameAddress();

            collect.Name     = ConfigurationManager.AppSettings["collect_name"];
            collect.PostCode = ConfigurationManager.AppSettings["collect_postcode"];
            collect.Phone    = ConfigurationManager.AppSettings["collect_phone"];
            collect.Mobile   = ConfigurationManager.AppSettings["collect_mobile"];
            collect.Country  = ConfigurationManager.AppSettings["collect_country"];
            collect.Province = ConfigurationManager.AppSettings["collect_province"];
            collect.City     = ConfigurationManager.AppSettings["collect_city"];
            collect.County   = ConfigurationManager.AppSettings["collect_county"];
            collect.Company  = ConfigurationManager.AppSettings["collect_company"];
            collect.Street   = ConfigurationManager.AppSettings["collect_street"];
            collect.Email    = ConfigurationManager.AppSettings["collect_email"];
            order.Collect    = collect;
            return(order);
        }
        /** 根据数据库中查询出来的记录填充平台订单的收件人名址信息 */
        private void FillReceiver(PlatformOrder order, DataRow row)
        {
            NameAddress receiver = new NameAddress();

            receiver.Name     = Convert.ToString(row[COL_RECEIVER_NAME]);
            receiver.PostCode = Convert.ToString(row[COL_RECEIVER_POSTCODE]);
            receiver.Country  = Convert.ToString(row[COL_RECEIVER_COUNTRY]);
            receiver.Province = Convert.ToString(row[COL_RECEIVER_RPOVINCE]);
            receiver.City     = Convert.ToString(row[COL_RECEIVER_CITY]);
            receiver.Street   = Convert.ToString(row[COL_RECEIVER_STREET]);

            if (null != row[COL_RECEIVER_PHONE])
            {
                receiver.Phone = Convert.ToString(row[COL_RECEIVER_PHONE]);
            }

            if (null != row[COL_RECEIVER_MOBILE])
            {
                receiver.Mobile = Convert.ToString(row[COL_RECEIVER_MOBILE]);
            }

            if (null != row[COL_RECEIVER_COUNTY])
            {
                receiver.County = Convert.ToString(row[COL_RECEIVER_COUNTY]);
            }

            if (null != row[COL_RECEIVER_COMPANY])
            {
                receiver.Company = Convert.ToString(row[COL_RECEIVER_COMPANY]);
            }

            if (null != row[COL_RECEIVER_EMAIL])
            {
                receiver.Email = Convert.ToString(row[COL_RECEIVER_EMAIL]);
            }

            order.Receiver = receiver;
        }
Exemplo n.º 12
0
        public async Task <IActionResult> Edit(int id, [Bind("NameAddressId,FirstName,LastName,CompanyName,StreetAddress,City,PostalCode,ProvinceCode,Email,Phone")] NameAddress nameAddress)
        {
            if (id != nameAddress.NameAddressId)
            {
                return(NotFound());
            }

            try
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        _context.Update(nameAddress);
                        await _context.SaveChangesAsync();
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                        if (!NameAddressExists(nameAddress.NameAddressId))
                        {
                            return(NotFound());
                        }
                        else
                        {
                            throw;
                        }
                    }
                    TempData["SuccessMessage"] = "Successfully Saved";
                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", $"error saving the edits: {ex.GetBaseException().Message}");
            }
            ViewData["ProvinceName"] = new SelectList(_context.Province, "ProvinceCode", "Name", nameAddress.ProvinceCodeNavigation);
            return(View(nameAddress));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Create name address record from order.
        /// </summary>
        /// <param name="order">Source order.</param>
        /// <param name="oldAddress">Address before geocoding.</param>
        /// <returns>Name address record.</returns>
        public static NameAddressRecord CreateNameAddressPair(Order order, Address oldAddress)
        {
            Debug.Assert(order != null);

            NameAddressRecord nameAddressRecord = new NameAddressRecord();

            nameAddressRecord.NameAddress = new NameAddress();

            NameAddress nameAddress = nameAddressRecord.NameAddress;

            nameAddress.Name = order.Name;

            Debug.Assert(order.GeoLocation.HasValue);

            nameAddressRecord.GeoLocation = new ESRI.ArcLogistics.Geometry.Point(order.GeoLocation.Value.X, order.GeoLocation.Value.Y);

            Address matchedAddress;

            if (oldAddress == null)
            {
                nameAddress.Address = (Address)order.Address.Clone();

                // Make matched address empty.
                matchedAddress = new Address();
            }
            else
            {
                // Set old order address as source address.
                nameAddressRecord.NameAddress.Address = (Address)oldAddress.Clone();

                // Set current address as matched.
                matchedAddress = (Address)order.Address.Clone();
            }

            nameAddressRecord.MatchedAddress = matchedAddress;

            return(nameAddressRecord);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Creates named address list for input objects.
        /// </summary>
        /// <param name="objects">Source object.</param>
        /// <returns>Created named address list for input objects.</returns>
        /// <remarks>Progress show.</remarks>
        private NameAddress[] _CreateNamedAddressList(IList <AppData.DataObject> objects)
        {
            Debug.Assert(null != objects);   // created
            Debug.Assert(0 < objects.Count); // not empty
            Debug.Assert(null != _checker);  // inited

            // init progress
            int count     = objects.Count;
            var addresses = new NameAddress[count];

            for (int index = 0; index < count; ++index)
            {
                _checker.ThrowIfCancellationRequested();

                IGeocodable geocodable  = _GetGeocodable(objects[index]);
                var         nameAddress = new NameAddress();
                nameAddress.Name    = geocodable.ToString();
                nameAddress.Address = geocodable.Address;
                addresses[index]    = nameAddress;
            }

            return(addresses);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Geocode batch of of items.
        /// </summary>
        /// <param name="nameAddresses">Name\Address pairs to geocode.</param>
        /// <returns></returns>
        public AddressCandidate[] BatchGeocode(NameAddress[] nameAddresses)
        {
            Debug.Assert(nameAddresses != null);
            Debug.Assert(_geocoder != null);

            // Create candidates array.
            AddressCandidate[] candidates = new AddressCandidate[nameAddresses.Length];

            // Try to find candidates in local storage and put in appropriate position in candidates array.
            // Leave null if candidate not found. Return not addresses, which not exists in local storage.
            List<Address> addressesToGeocode = _ProcessLocalBatchGeocoding(nameAddresses, candidates);

            if (addressesToGeocode.Count > 0)
            {
                // Make batch geocode at server.
                AddressCandidate[] candidatesFromServer = _geocoder.BatchGeocode(addressesToGeocode.ToArray());

                // Fill results of batch geocoding in candidates array.
                _ProcessServerBatchGeocoding(candidatesFromServer, candidates);
            }

            return candidates;
        }
        public async Task <IActionResult> Edit(int id, [Bind("NameAddressId,FirstName,LastName,CompanyName,StreetAddress,City,PostalCode,ProvinceCode,Email,Phone")] NameAddress nameAddress)
        {
            if (id != nameAddress.NameAddressId)
            {
                ModelState.AddModelError("", "A record being updated is not the one requested.");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(nameAddress);
                    await _context.SaveChangesAsync();

                    TempData["message"] = $"Name & Address record updated successfully";
                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    if (!NameAddressExists(nameAddress.NameAddressId))
                    {
                        ModelState.AddModelError("", $"NameAddressId is not on file: {nameAddress.NameAddressId}");
                    }
                    else
                    {
                        ModelState.AddModelError("", $"Concurrency exception: {ex.GetBaseException().Message}");
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", $"Error while updating a record: {ex.GetBaseException().Message}");
                }
            }
            // display the province name in the drop-down, ordered by name
            ViewData["ProvinceCode"] = new SelectList(_context.Province.OrderBy(p => p.Name), "ProvinceCode", "Name", nameAddress.ProvinceCode);
            return(View(nameAddress));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Get address candidates from local storage and from server.
        /// </summary>
        /// <param name="nameAddress">Name\Address pair to geocode.</param>
        /// <param name="includeDisabledLocators">Is need to add candidates from disabled locators.</param>
        /// <returns>Candidates list.</returns>
        public AddressCandidate[] GeocodeCandidates(NameAddress nameAddress, bool includeDisabledLocators)
        {
            Debug.Assert(nameAddress != null);

            List<AddressCandidate> candidates = _GeocodeCandidates(nameAddress.Address, includeDisabledLocators);

            AddressCandidate candidateFromLocalStorage = Geocode(nameAddress);

            if (candidateFromLocalStorage != null)
            {
                // If candidate from local storage exists - insert it to first position.
                candidates.Insert(0, candidateFromLocalStorage);
            }

            return candidates.ToArray();
        }
Exemplo n.º 18
0
        /// <summary>
        /// Creates named address list for input objects.
        /// </summary>
        /// <param name="objects">Source object.</param>
        /// <returns>Created named address list for input objects.</returns>
        /// <remarks>Progress show.</remarks>
        private NameAddress[] _CreateNamedAddressList(IList<AppData.DataObject> objects)
        {
            Debug.Assert(null != objects); // created
            Debug.Assert(0 < objects.Count); // not empty
            Debug.Assert(null != _checker); // inited

            // init progress
            int count = objects.Count;
            var addresses = new NameAddress[count];
            for (int index = 0; index < count; ++index)
            {
                _checker.ThrowIfCancellationRequested();

                IGeocodable geocodable = _GetGeocodable(objects[index]);
                var nameAddress = new NameAddress();
                nameAddress.Name = geocodable.ToString();
                nameAddress.Address = geocodable.Address;
                addresses[index] = nameAddress;
            }

            return addresses;
        }
Exemplo n.º 19
0
        /// <summary>
        /// Check is location of geocodable object valid and replace it by candidate from local
        /// geocoder if exists.
        /// </summary>
        /// <param name="geocodable">Geocodable object to check.</param>
        /// <returns>Is geocodable object valid.</returns>
        private bool _SourceGeocodedObject(IGeocodable geocodable)
        {
            Debug.Assert(null != geocodable); // created

            bool isObjectGeocoded = false;

            // First check if name address pair exists in local geocoder database.
            // If exists - overwrite geolocation and address from it.
            App currentApp = App.Current;
            var localGeocoder =
                new LocalGeocoder(currentApp.Geocoder, currentApp.NameAddressStorage);

            var nameAddress = new NameAddress();
            nameAddress.Name = geocodable.ToString();
            nameAddress.Address = geocodable.Address.Clone() as Address;

            AddressCandidate localCandidate = localGeocoder.Geocode(nameAddress);
            if (localCandidate == null)
            {   // Update from internal object information.
                AppGeometry.Envelope extent = currentApp.Map.ImportCheckExtent;
                if (extent.IsPointIn(geocodable.GeoLocation.Value))
                {
                    geocodable.Address.MatchMethod =
                        currentApp.FindString("ImportSourceMatchMethod");
                    isObjectGeocoded = true;

                    // Full address property must be combined from other fields, because
                    // it is not importing field.
                    if (App.Current.Geocoder.AddressFormat == AddressFormat.MultipleFields)
                        GeocodeHelpers.SetFullAddress(geocodable.Address);
                    else
                    {
                        // Do nothing: do not update full address since
                        // it is used for geocoding in Single Address Field Format.
                    }
                }
                // Else could not locate object using X/Y attributes - need geocode.
            }
            else
            {   // Init from local candidate.
                // Set location.
                geocodable.GeoLocation = new AppGeometry.Point(localCandidate.GeoLocation.X,
                                                               localCandidate.GeoLocation.Y);
                // Set address.
                localCandidate.Address.CopyTo(geocodable.Address);

                isObjectGeocoded = true;
            }

            return isObjectGeocoded;
        }
        /// <summary>
        /// Searches in local storage by name/address pair.
        /// </summary>
        /// <param name="nameAddress">Name/address pair to search.</param>
        /// <param name="format">Current Address Format.</param>
        /// <returns>Name address record.</returns>
        public NameAddressRecord Search(NameAddress nameAddress, AddressFormat format)
        {
            Debug.Assert(nameAddress != null);
            Debug.Assert(_IsInitialized());

            NameAddressRecord recordFromDB = null;

            try
            {
                recordFromDB = _GetRecordFromDB(nameAddress, format);
            }
            catch (Exception ex)
            {
                Logger.Warning(ex);
            }

            return recordFromDB;
        }
Exemplo n.º 21
0
        /// <summary>
        /// Geocode order, using local geocoder.
        /// </summary>
        /// <param name="order">Order to geocode.</param>
        /// <param name="useLocalAsPrimary">If true and record exists in storage, than dont use server geocoder.</param>
        /// <param name="includeDisabledLocators">Is need to add candidates from disabled locators.</param>
        /// <returns>Candidates list.</returns>
        private static List<AddressCandidate> _DoLocalOrderGeocode(Order order, bool useLocalAsPrimary, bool includeDisabledLocators)
        {
            LocalGeocoder localGeocoder = new LocalGeocoder(App.Current.Geocoder, App.Current.NameAddressStorage);

            NameAddress nameAddress = new NameAddress();
            nameAddress.Name = order.Name;
            nameAddress.Address = (Address)order.Address.Clone();

            List<AddressCandidate> candidates = new List<AddressCandidate>();

            AddressCandidate candidateFromLocalGeocoder = localGeocoder.Geocode(nameAddress);

            if (useLocalAsPrimary && candidateFromLocalGeocoder != null)
            {
                candidates.Add(candidateFromLocalGeocoder);
            }
            else
            {
                AddressCandidate[] candidatesArray = localGeocoder.GeocodeCandidates(nameAddress, includeDisabledLocators);
                candidates.AddRange(candidatesArray);
            }

            return candidates;
        }
        /// <summary>
        /// Fill parameters of SQL command from name\address pair.
        /// </summary>
        /// <param name="nameAddress">Source name\address record.</param>
        /// <param name="command">Command to fill.</param>
        private void _FillCommandParameters(NameAddress nameAddress, SqlCeCommand command)
        {
            _AddParameter(command, NAME_PARAMETER_NAME, nameAddress.Name);

            Address address = nameAddress.Address;

            _AddParameter(command, UNIT_PARAMETER_NAME, address.Unit);
            _AddParameter(command, ADDRESSLINE_PARAMETER_NAME, address.AddressLine);
            _AddParameter(command, LOCALITY1_PARAMETER_NAME, address.Locality1);
            _AddParameter(command, LOCALITY2_PARAMETER_NAME, address.Locality2);
            _AddParameter(command, LOCALITY3_PARAMETER_NAME, address.Locality3);
            _AddParameter(command, COUNTYPREFECTURE_PARAMETER_NAME, address.CountyPrefecture);
            _AddParameter(command, POSTALCODE1_PARAMETER_NAME, address.PostalCode1);
            _AddParameter(command, POSTALCODE2_PARAMETER_NAME, address.PostalCode2);
            _AddParameter(command, STATEPROVINCE_PARAMETER_NAME, address.StateProvince);
            _AddParameter(command, COUNTRY_PARAMETER_NAME, address.Country);
            _AddParameter(command, FULL_ADDRESS_PARAMETER_NAME, address.FullAddress);
        }
        /// <summary>
        /// Get record from database.
        /// </summary>
        /// <param name="nameAddress">Name\address pair to find.</param>
        /// <param name="format">Current Address Format.</param>
        /// <returns>Extracted record.</returns>
        private NameAddressRecord _GetRecordFromDB(NameAddress nameAddress, AddressFormat format)
        {
            NameAddressRecord nameAddressRecord = null;

            string queryStr = string.Empty;

            // Choose queries in dependence of used address format.
            if (format == AddressFormat.SingleField)
                queryStr = FULL_ADDRESS_SELECT_QUERY;
            else if (format == AddressFormat.MultipleFields)
                queryStr = SELECT_QUERY;
            else
            {
                // Do nothing.
            }

            SqlCeCommand command = new SqlCeCommand(queryStr, _connection);
            _FillCommandParameters(nameAddress, command);

            SqlCeDataReader reader = null;
            try
            {
                reader = command.ExecuteReader();

                if (reader.Read())
                {
                    nameAddressRecord = _ReadRecord(reader);
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }

            return nameAddressRecord;
        }
Exemplo n.º 24
0
        private static XmlElement ToCollectXmlElement(XmlDocument document, NameAddress nameAddress)
        {
            XmlElement collectElement = document.CreateElement("collect");
            XmlElement nameElement    = document.CreateElement("name");

            nameElement.InnerText = nameAddress.Name;
            collectElement.AppendChild(nameElement);
            XmlElement postCodeElement = document.CreateElement("postcode");

            postCodeElement.InnerText = nameAddress.PostCode;
            collectElement.AppendChild(postCodeElement);

            if (null != nameAddress.Phone && !"".Equals(nameAddress.Phone))
            {
                XmlElement phoneElement = document.CreateElement("phone");
                phoneElement.InnerText = nameAddress.Phone;
                collectElement.AppendChild(phoneElement);
            }

            if (null != nameAddress.Mobile && !"".Equals(nameAddress.Mobile))
            {
                XmlElement mobileElement = document.CreateElement("mobile");
                mobileElement.InnerText = nameAddress.Mobile;
                collectElement.AppendChild(mobileElement);
            }

            XmlElement countryElement = document.CreateElement("country");

            countryElement.InnerText = nameAddress.Country;
            collectElement.AppendChild(countryElement);

            XmlElement provinceElement = document.CreateElement("province");

            provinceElement.InnerText = nameAddress.Province;
            collectElement.AppendChild(provinceElement);


            XmlElement cityElement = document.CreateElement("city");

            cityElement.InnerText = nameAddress.City;
            collectElement.AppendChild(cityElement);

            XmlElement countyElement = document.CreateElement("county");

            countyElement.InnerText = nameAddress.County;
            collectElement.AppendChild(countyElement);

            if (null != nameAddress.Company && !"".Equals(nameAddress.Company))
            {
                XmlElement companyElement = document.CreateElement("company");
                companyElement.InnerText = nameAddress.Company;
                collectElement.AppendChild(companyElement);
            }

            XmlElement streetElement = document.CreateElement("street");

            streetElement.InnerText = nameAddress.Street;
            collectElement.AppendChild(streetElement);

            if (null != nameAddress.Email && !"".Equals(nameAddress.Email))
            {
                XmlElement emailElement = document.CreateElement("email");
                emailElement.InnerText = nameAddress.Email;
                collectElement.AppendChild(emailElement);
            }

            return(collectElement);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Get address candidate from local storage.
        /// </summary>
        /// <param name="nameAddress">Name\Address pair to geocode.</param>
        /// <returns>Address candidate if exists in local storage. Null otherwise.</returns>
        public AddressCandidate Geocode(NameAddress nameAddress)
        {
            Debug.Assert(nameAddress != null);
            Debug.Assert(_nameAddressStorage != null);

            // Search record in storage.
            NameAddressRecord nameAddressRecord = _nameAddressStorage.Search(
                nameAddress, App.Current.Geocoder.AddressFormat);

            AddressCandidate candidateFromLocalStorage = null;

            // Extract candidate from record, if record exists.
            if (nameAddressRecord != null)
            {
                candidateFromLocalStorage = _ConvertToCandidate(nameAddressRecord);
            }

            return candidateFromLocalStorage;
        }
        /// <summary>
        /// Read record from database.
        /// </summary>
        /// <param name="reader">Database reader.</param>
        /// <returns>Readed record.</returns>
        private NameAddressRecord _ReadRecord(SqlCeDataReader reader)
        {
            NameAddressRecord nameAddressRecord = new NameAddressRecord();

            NameAddress nameAddress = new NameAddress();
            nameAddressRecord.NameAddress = nameAddress;

            nameAddress.Name = (string)reader[NAME_FIELD_NAME];

            Address address = new Address();
            nameAddress.Address = address;
            address.Unit = (string)reader[UNIT_FIELD_NAME];
            address.AddressLine = (string)reader[ADDRESSLINE_FIELD_NAME];
            address.Locality1 = (string)reader[LOCALITY1_FIELD_NAME];
            address.Locality2 = (string)reader[LOCALITY2_FIELD_NAME];
            address.Locality3 = (string)reader[LOCALITY3_FIELD_NAME];
            address.CountyPrefecture = (string)reader[COUNTYPREFECTURE_FIELD_NAME];
            address.PostalCode1 = (string)reader[POSTALCODE1_FIELD_NAME];
            address.PostalCode2 = (string)reader[POSTALCODE2_FIELD_NAME];
            address.StateProvince = (string)reader[STATEPROVINCE_FIELD_NAME];
            address.Country = (string)reader[COUNTRY_FIELD_NAME];
            address.FullAddress = (string)reader[FULL_ADDRESS_FIELD_NAME];
            float x = (float)reader[X_FIELD_NAME];
            float y = (float)reader[Y_FIELD_NAME];
            nameAddressRecord.GeoLocation = new ESRI.ArcLogistics.Geometry.Point(x, y);

            Address matchedAddress = new Address();
            nameAddressRecord.MatchedAddress = matchedAddress;
            matchedAddress.Unit = (string)reader[MUNIT_FIELD_NAME];
            matchedAddress.AddressLine = (string)reader[MADDRESSLINE_FIELD_NAME];
            matchedAddress.Locality1 = (string)reader[MLOCALITY1_FIELD_NAME];
            matchedAddress.Locality2 = (string)reader[MLOCALITY2_FIELD_NAME];
            matchedAddress.Locality3 = (string)reader[MLOCALITY3_FIELD_NAME];
            matchedAddress.CountyPrefecture = (string)reader[MCOUNTYPREFECTURE_FIELD_NAME];
            matchedAddress.PostalCode1 = (string)reader[MPOSTALCODE1_FIELD_NAME];
            matchedAddress.PostalCode2 = (string)reader[MPOSTALCODE2_FIELD_NAME];
            matchedAddress.StateProvince = (string)reader[MSTATEPROVINCE_FIELD_NAME];
            matchedAddress.Country = (string)reader[MCOUNTRY_FIELD_NAME];
            matchedAddress.FullAddress = (string)reader[MFULL_ADDRESS_FIELD_NAME];

            string matchMethod = (string)reader[MATCHMETHOD_FIELD_NAME];
            if (CommonHelpers.IsAllAddressFieldsEmpty(matchedAddress) && string.IsNullOrEmpty(matchedAddress.MatchMethod))
            {
                address.MatchMethod = matchMethod;
            }
            else
            {
                matchedAddress.MatchMethod = matchMethod;
            }

            return nameAddressRecord;
        }
        public static void Run()
        {
            const string Username = "";
            const string Password = "";
            const bool   Sandbox  = true;

            NextCallerClient client = new NextCallerClient(Username, Password, Sandbox);

            NameAddress nameAddress = new NameAddress
            {
                AddressLine = "129 West 81st Street",
                FirstName   = "Jerry",
                LastName    = "Seinfeld",
                City        = "New York",
                State       = "NY"
            };

            try
            {
                IList <Profile> profiles = client.GetByNameAddress(nameAddress);

                Profile profile = profiles.First();

                //profile.Id = "97d949a413f4ea8b85e9586e1f2d9a";
                //profile.FirstName = "Jerry";
                //profile.LastName = "Seinfeld";
                //profile.Name = "Jerry K Seingeld";
                //profile.Language = "English";

                //Phone phone = profile.Phones.First();
                //phone.Number = "2125558383";
                //phone.ResourceUri = "/v2/records/2125558383/";

                //profile.Carrier = "Verizon Wireless";
                //profile.LineType = "LAN";

                //Address address = profile.Addresses.First();
                //address.City = "New York";
                //address.State = "NY";
                //address.Country = "USA";
                //address.Line1 = "129 West 81st Street";
                //address.Line2 = "Apt 5a";
                //address.ZipCode = "10024";
                //address.ExtendedZip = "";

                //profile.Email = "*****@*****.**";
                //profile.LinkedEmails = new[]
                //{
                //	"*****@*****.**", "*****@*****.**", "*****@*****.**"
                //};
                //profile.SocialLinks = new[]
                //{
                //	new Dictionary<string, object>()
                //	{
                //		{ "type", "twitter" },
                //		{ "url", "http://www.twitter.com/example" },
                //		{ "followers", 323 }
                //	}
                //};
                //profile.Relatives = new []
                //{
                //	new Relative
                //	{
                //		Id = "a4bf8cff1bfd61d8611d396997bb29",
                //		Name = "Clark Kent",
                //		ResourceUri = "/v2/users/90c6a00c6391421d3a764716927cd8/"
                //	}
                //};
                //profile.DateOfBirth = "05/15/1970";
                //profile.Gender = "Male";
                //profile.Age = "45-54";
                //profile.HouseholdIncome = "50k-75k";
                //profile.HomeOwnerStatus = "Rent";
                //profile.LengthOfResidence = "12 Years";
                //profile.Occupation = "Entertainer";
                //profile.Education = "Completed College";
                //profile.ResourceUri = "/v2/users/97d949a413f4ea8b85e9586e1f2d9a/";
            }
            catch (FormatException formatException)
            {
                HttpWebRequest  request  = formatException.Request;
                HttpWebResponse response = formatException.Response;

                HttpStatusCode code = response.StatusCode;
                Console.WriteLine("Status code: {0}", code);

                string reasonPhrase = response.StatusDescription;
                Console.WriteLine("Reason Phrase: {0}", reasonPhrase);

                string responseContent = formatException.Content;
                Console.WriteLine("Content : {0}", responseContent);
            }
            catch (BadRequestException badRequestException)
            {
                HttpWebRequest  request  = badRequestException.Request;
                HttpWebResponse response = badRequestException.Response;

                Error parsedError = badRequestException.Error;

                string errorCode = parsedError.Code;
                string message   = parsedError.Message;
                string type      = parsedError.Type;

                Dictionary <string, string[]> description = parsedError.Description;

                Console.WriteLine(parsedError.ToString());
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Try to find candidates in local storage and put in appropriate position in candidates array.
        /// Leave null if candidate not found. Return addresses, which not exists in local storage.
        /// </summary>
        /// <param name="nameAddresses">Name\Address pairs to geocode.</param>
        /// <param name="candidates">Candidates list.</param>
        /// <returns>Addresses, which not exists in local storage.</returns>
        private List<Address> _ProcessLocalBatchGeocoding(NameAddress[] nameAddresses,
                                                          AddressCandidate[] candidates)
        {
            Debug.Assert(nameAddresses != null);
            Debug.Assert(candidates != null);

            List<Address> addressesToGeocode = new List<Address>();

            for (int index = 0; index < nameAddresses.Length; index++)
            {
                AddressCandidate candidate = Geocode(nameAddresses[index]);

                // If candidate exists in local storage - put it to candidates list.
                // Otherwise add address to geocode on server.
                if (candidate != null)
                {
                    candidates[index] = candidate;
                }
                else
                {
                    addressesToGeocode.Add(nameAddresses[index].Address);
                }
            }

            return addressesToGeocode;
        }