public void CanGetDynamicDocument()
        {
            Run(() =>
            {
                SearchIndexClient client = Data.GetSearchIndexClient();

                var expectedDoc =
                    new Document()
                {
                    { "hotelId", "1" },
                    { "baseRate", 199.0 },
                    { "description", "Best hotel in town" },
                    { "descriptionFr", "Meilleur hôtel en ville" },
                    { "hotelName", "Fancy Stay" },
                    { "category", "Luxury" },
                    { "tags", new[] { "pool", "view", "wifi", "concierge" } },
                    { "parkingIncluded", false },
                    { "smokingAllowed", false },
                    { "lastRenovationDate", new DateTimeOffset(2010, 6, 27, 0, 0, 0, TimeSpan.FromHours(-8)) },
                    { "rating", 5L },
                    { "location", GeographyPoint.Create(47.678581, -122.131577) }
                };

                var batch = new IndexBatch(new[] { new IndexAction(expectedDoc) });
                client.Documents.Index(batch);
                SearchTestUtilities.WaitForIndexing();

                DocumentGetResponse getResponse = client.Documents.Get("1");
                Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
                SearchAssert.DocumentsEqual(expectedDoc, getResponse.Document);
            });
        }
        public void CanGetStaticallyTypedDocument()
        {
            Run(() =>
            {
                SearchIndexClient client = Data.GetSearchIndexClient();

                var expectedDoc =
                    new Hotel()
                {
                    HotelId            = "1",
                    BaseRate           = 199.0,
                    Description        = "Best hotel in town",
                    DescriptionFr      = "Meilleur hôtel en ville",
                    HotelName          = "Fancy Stay",
                    Category           = "Luxury",
                    Tags               = new[] { "pool", "view", "wifi", "concierge" },
                    ParkingIncluded    = false,
                    SmokingAllowed     = false,
                    LastRenovationDate = new DateTimeOffset(2010, 6, 27, 0, 0, 0, TimeSpan.Zero),
                    Rating             = 5,
                    Location           = GeographyPoint.Create(47.678581, -122.131577)
                };

                var batch = IndexBatch.Create(IndexAction.Create(expectedDoc));
                client.Documents.Index(batch);

                DocumentGetResponse <Hotel> response = client.Documents.Get <Hotel>("1");
                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                Assert.Equal(expectedDoc, response.Document);
            });
        }
        public void TryConvertGeographyPoint()
        {
            var source = GeographyPoint.Create(10, 10);
            var result = Utils.TryConvert(source, typeof(GeographyPoint), out _);

            Assert.True(result);
        }
예제 #4
0
        private void mapCircuit_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (!App.ViewModel.Track.IsLocal)
            {
                return;
            }
            var mapPosition = e.GetPosition(mapCircuit);
            var mapLayer    = new MapLayer();

            var geoCoordinate = mapCircuit.ConvertViewportPointToGeoCoordinate(mapPosition);

            lastSectorNumber++;
            double heading         = (double)App.ViewModel.DegreesData.SelectedItem;
            var    geographyPoint  = GeographyPoint.Create(geoCoordinate.Latitude, geoCoordinate.Longitude, null, heading);
            var    lineCoordinates = geographyPoint.ConvertToLine(0.02);
            var    newSector       = new TrackSectorViewModel
            {
                StartLatitude  = lineCoordinates[0].Latitude,
                StartLongitude = lineCoordinates[0].Longitude,
                EndLatitude    = lineCoordinates[0].Latitude,
                EndLongitude   = lineCoordinates[0].Longitude,
                Heading        = heading,
                IsFinishLine   = false,
                SectorNumber   = lastSectorNumber
            };

            App.ViewModel.Track.Sectors.Add(newSector);
            App.ViewModel.Track.SelectedSector = newSector;
            NavigationService.Navigate(new Uri("/EditSectorPage.xaml", System.UriKind.Relative));
        }
        public void CanWriteGeoPoint()
        {
            var    point = GeographyPoint.Create(47.1, 121.9);
            string json  = JsonConvert.SerializeObject(point, _jsonSettings);

            Assert.Equal(@"{""type"":""Point"",""coordinates"":[121.9,47.1]}", json);
        }
예제 #6
0
        public static IEnumerable <object[]> GetWriteValueTestData()
        {
            // Enum
            yield return(new object[]
            {
                new ODataEnumValue("Black", "NS.Color"),
                "Black"
            });

            // Primitive
            yield return(new object[]
            {
                "foobar",
                "foobar"
            });

            // Spatial
            yield return(new object[]
            {
                GeographyPoint.Create(22.2, 22.2),
                "{\"type\":\"Point\",\"coordinates\":[22.2,22.2],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:4326\"}}}"
            });

            // byte array
            yield return(new object[]
            {
                new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 },
                "\u0001\u0002\u0003\u0004\u0005\u0006\a\b\t\0"
            });
        }
예제 #7
0
        // [Ignore] // Remove Atom
        // [Fact] // github issuse: #896
        public void InsertUsingAtomShouldBeFailedClientTest()
        {
            // TestClientContext.Format.UseAtom();

            Person newPerson = new Person()
            {
                PersonID    = 10001,
                FirstName   = "New",
                LastName    = "Person",
                MiddleName  = "Guy",
                Home        = GeographyPoint.Create(32.1, 23.1),
                HomeAddress = new HomeAddress
                {
                    City       = "Shanghai",
                    Street     = "Zixing Rd",
                    PostalCode = "200241",
                    FamilyName = "New"
                }
            };

            TestClientContext.AddToPeople(newPerson);
            try
            {
                TestClientContext.SaveChanges();
            }
            catch (Microsoft.OData.Client.DataServiceRequestException e)
            {
                var message = e.InnerException.Message;
                Assert.True(message.StartsWith("A supported MIME type could not be found that matches the content type of the response."));
                return;
            }
        }
예제 #8
0
        /************************************************************************************************************************/
        /*****PRIVATE METHODS****************************************************************************************************/
        /************************************************************************************************************************/

        private void UpdateSpeciesGeographyForTaxonomicClass(String taxonomicClass)
        {
            var shapeFileInfo = GetShapeFileInfo(taxonomicClass);

            using (var shapeFile = new ShapeFile(shapeFileInfo.FullName))
            {
                shapeFile.Open();
                const double minLatitude  = -3.5;
                const double maxLatitude  = 0.0;
                const double maxLongitude = 180.0;
                const double minLongitude = -180.0;
                const double interval     = 0.5;

                for (var latitude = minLatitude; latitude < maxLatitude; Math.Round(latitude = latitude + interval, 1))
                {
                    for (var longitude = minLongitude; longitude < maxLongitude; Math.Round(longitude = longitude + interval, 1))
                    {
                        var point = GeographyPoint.Create(latitude, longitude);
AttemptUpdate:

                        try
                        {
                            UpdateSpeciesGeographyTableIfNeeded(shapeFile, point, taxonomicClass);
                        }
                        catch (Exception e)
                        {
                            Trace.TraceError(e.Message, e);
                            goto AttemptUpdate;
                        }
                    }
                }
            }
        }
        public void When_Updating_GeoSpatial_Primitive_Property_On_Client_Then_That_Property_Must_Be_Updated_On_Server()
        {
            using (var scenario =
                       new ODataScenario()
                       .WithSuppliedProducts(Any.Suppliers())
                       .Start())
            {
                var context = GetDataServiceContext(scenario.GetBaseAddress());
                context.MergeOption = MergeOption.OverwriteChanges;
                var dQuery    = context.CreateQuery <Supplier>("/" + "Suppliers");
                var suppliers = context.ExecuteAsync <Supplier, ISupplier>(dQuery).Result;
                suppliers.CurrentPage.Count.Should().Be(5);

                var supplier = suppliers.CurrentPage[2] as Supplier;
                // make sure that the binary primitive property is serialized
                supplier.Location.Should().NotBeNull();

                // lets update the geospatial primitive property
                var newLocation = GeographyPoint.Create(Any.Double(-90, 90), Any.Double(-180, 180));
                supplier.Location = newLocation;
                supplier.CallOnPropertyChanged("Location");

                // Bug - Location is a property of primitive type - "Microsoft.Spatial.GeographyPoint".
                // Its underlying type is "Microsoft.Data.Spatial.GeographyPointImplementation".
                // In the ASP.Net stack when deserializing the 'Location' property InvalidCastException is thrown.
                supplier.UpdateAsync().Wait();

                var updatedsuppliers = context.ExecuteAsync <Supplier, ISupplier>(dQuery).Result;
                updatedsuppliers.CurrentPage.Count.Should().Be(5);
                updatedsuppliers.CurrentPage[2].Location.Should().Be(newLocation);
            }
        }
예제 #10
0
        public void ParseCountAfterNonComposableFunctionShouldFail()
        {
            var    point     = GeographyPoint.Create(1, 2);
            Action parsePath = () => this.testSubject.ParsePath(new[] { "People(1)", "Fully.Qualified.Namespace.GetNearbyPriorAddresses(currentLocation=geography'" + SpatialHelpers.WriteSpatial(point) + "',limit=null)", "$count" });

            parsePath.ShouldThrow <ODataException>().WithMessage(ErrorStrings.RequestUriProcessor_MustBeLeafSegment("Fully.Qualified.Namespace.GetNearbyPriorAddresses"));
        }
예제 #11
0
        private static void UploadDocuments(SearchIndexClient indexClient, List <Place> places)
        {
            var documents = places.Select(x => new PlaceDocument
            {
                Id               = Guid.NewGuid().ToString(),
                City             = x.Address.City,
                State            = x.Address.State,
                StreetName       = x.Address.FullStreet,
                Neighborhood     = x.Address.Neighborhood,
                FloorArea        = x.FloorArea,
                Geolocation      = GeographyPoint.Create(x.Address.Latitude, x.Address.Longitude),
                LocationValue    = x.LocationValue,
                NumberOfBedrooms = x.NumberOfBedrooms,
                NumberOfSuites   = x.NumberOfSuites,
                PlaceType        = x.Type
            }).AsEnumerable();

            try
            {
                var batch = IndexBatch.Upload(documents);
                indexClient.Documents.Index(batch);
            }
            catch (IndexBatchException e)
            {
                // Sometimes when your Search service is under load, indexing will fail for some of the documents in
                // the batch. Depending on your application, you can take compensating actions like delaying and
                // retrying. For this simple demo, we just log the failed document keys and continue.
                Console.WriteLine(
                    "Failed to index some of the documents: {0}",
                    String.Join(", ", e.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key)));
            }

            // Wait a while for indexing to complete.
            Thread.Sleep(2000);
        }
예제 #12
0
 public void WriteRawValueWritesGeographyValue()
 {
     RawValueWriter target = new RawValueWriter(this.settings, this.stream, new UTF32Encoding());
     var value = GeographyPoint.Create(22.2, 22.2);
     target.WriteRawValue(value);
     this.StreamAsString(target).Should().Be("SRID=4326;POINT (22.2 22.2)");
 }
예제 #13
0
        public static IndexModel NewIndexModel(string data)
        {
            IndexModel model = new IndexModel();
            var        x     = JsonConvert.DeserializeObject <IndexModel>(data);

            x.IndexKey             = x.DeviceDataType + "_" + x.DeviceId;
            model.ActiveHours      = x.ActiveHours;
            model.ActualDistance   = x.ActualDistance;
            model.AverageHeartRate = x.AverageHeartRate;
            model.DeviceDataType   = x.DeviceDataType;
            model.DeviceId         = x.DeviceId;
            model.EndTime          = x.EndTime;
            model.IndexKey         = x.IndexKey;
            model.LocationKeywords = x.LocationKeywords;
            model.LocationName     = x.LocationName;
            model.Latitude         = x.Latitude;
            model.Longitude        = x.Longitude;
            model.GeoLocation      = GeographyPoint.Create(x.Latitude, x.Longitude);
            model.LowestHeartRate  = x.LowestHeartRate;
            model.MaxElevation     = x.MaxElevation;
            model.MinElevation     = x.MinElevation;
            model.ParentDay        = x.ParentDay;
            model.PeakHeartRate    = x.PeakHeartRate;
            model.Speed            = x.Speed;
            model.StartTime        = x.StartTime;
            model.StepsTaken       = x.StepsTaken;
            model.TotalCalories    = x.TotalCalories;
            model.TotalDistance    = x.TotalDistance;
            model.UserId           = x.UserId;
            model.UvExposure       = x.UvExposure;
            model.UserAge          = x.UserAge;
            model.UserGender       = x.UserGender;

            return(model);
        }
예제 #14
0
        public void GeographyPointToGeographyShouldNotDoAnything()
        {
            var point  = GeographyPoint.Create(1, 2);
            var result = this.jsonConverter.ConvertPrimitiveValue(point, typeof(Geography));

            result.Should().BeSameAs(point);
        }
예제 #15
0
        //public MapPoint GetLatLongFromAddress(string strAddress)
        //{
        //    var locationService = new GoogleLocationService(this.Options.ApiKey);
        //    var point = locationService.GetLatLongFromAddress(strAddress);
        //    return point;
        //}

        public GeographyPoint GetLatLongFromAddress(string strAddress)
        {
            var locationService = new GoogleLocationService(this.Options.ApiKey);
            var point           = locationService.GetLatLongFromAddress(strAddress);

            return(GeographyPoint.Create(point.Latitude, point.Longitude));
        }
        private static IEnumerable GetMicrosoftSpatialPointsData()
        {
            GeographyPoint point = GeographyPoint.Create(3.0, 2.0);

            yield return new TestCaseData(SearchFilter.Create($"geo.distance({point}, Foo) < 3"));
            yield return new TestCaseData(SearchFilter.Create($"geo.distance({GeographyPoint.Create(3.0, 2.0, 5.0)}, Foo) < 3"));
        }
        private static GeographyPoint ReadCoordinates(JsonReader coordinatesReader)
        {
            coordinatesReader.ExpectAndAdvance(JsonToken.StartArray);

            double ReadFloatOrInt()
            {
                switch (coordinatesReader.TokenType)
                {
                case JsonToken.Integer:
                    return(coordinatesReader.ExpectAndAdvance <long>(JsonToken.Integer));

                // Treat all other cases as Float and let ExpectAndAdvance() handle any errors.
                default:
                    return(coordinatesReader.ExpectAndAdvance <double>(JsonToken.Float));
                }
            }

            double longitude = ReadFloatOrInt();
            double latitude  = ReadFloatOrInt();

            // Skip remaining coordinates, e.g. z and m.
            while (coordinatesReader.TokenType != JsonToken.EndArray)
            {
                coordinatesReader.Advance();
            }

            coordinatesReader.ExpectAndAdvance(JsonToken.EndArray);

            return(GeographyPoint.Create(latitude, longitude));
        }
        public SpeciesCandidatesResult Post(Double latitude, Double longitude, Boolean multisample, byte[] imageBytes)
        {
            if (imageBytes == null)
            {
                return(new SpeciesCandidatesResult(new List <SpeciesCandidate>(), FailureStatus, "Valid image must be supplied."));
            }

            try
            {
                var image                 = ImageConversion.ByteArrayToImage(imageBytes);
                var geographyPoint        = GeographyPoint.Create(latitude, longitude);
                var speciesIdentityResult = _speciesIdentifier.GetMostLikelyIdentity(image, geographyPoint, true, multisample);
                var speciesInfo           = speciesIdentityResult.LikelySpeciesInfo;

                var speciesCandidates = new List <SpeciesCandidate>
                {
                    new SpeciesCandidate(speciesInfo.GetName(),
                                         speciesInfo.Taxonomy.GetGenus() + " " + speciesInfo.Taxonomy.GetSpecies(),
                                         speciesInfo.GetProbability())
                };
                return(new SpeciesCandidatesResult(speciesCandidates, SuccessStatus, ""));
            }
            catch (Exception e)
            {
                var message = "Failure while processing request: " + e.Message;
                return(new SpeciesCandidatesResult(new List <SpeciesCandidate>(), FailureStatus, message));
            }
        }
예제 #19
0
 public void DerivedPrimitiveValueShouldReturnNull()
 {
     Assert.Equal("Edm.GeographyPoint", this.testSubject.GetValueTypeNameForWriting(
                      new ODataPrimitiveValue(GeographyPoint.Create(42, 42)),
                      this.geographyTypeReference,
                      this.geographyPointTypeReference,
                      /*isOpen*/ false));
 }
예제 #20
0
        public void GeographyAndNullParameterValuesShouldWorkInPath()
        {
            var point     = GeographyPoint.Create(1, 2);
            Uri queryUri  = new Uri("People(0)/Fully.Qualified.Namespace.GetNearbyPriorAddresses(currentLocation=geography'" + SpatialHelpers.WriteSpatial(point) + "',limit=null)", UriKind.Relative);
            Uri actualUri = UriBuilder(queryUri, ODataUrlKeyDelimiter.Parentheses, settings);

            Assert.Equal(new Uri("http://gobbledygook/People(0)/Fully.Qualified.Namespace.GetNearbyPriorAddresses(currentLocation=geography'" + SpatialHelpers.WriteSpatial(point) + "',limit=null)"), actualUri);
        }
예제 #21
0
        public void WriteRawValueWritesGeographyValue()
        {
            RawValueWriter target = new RawValueWriter(this.settings, this.stream, new UTF32Encoding());
            var            value  = GeographyPoint.Create(22.2, 22.2);

            target.WriteRawValue(value);
            Assert.Equal(@"{""type"":""Point"",""coordinates"":[22.2,22.2],""crs"":{""type"":""name"",""properties"":{""name"":""EPSG:4326""}}}", this.StreamAsString(target));
        }
 public static GeographyPoint AsGeographyPoint(this LapDataPointViewModel point)
 {
     if (!point.Latitude.HasValue || !point.Longitude.HasValue)
     {
         return(null);
     }
     return(GeographyPoint.Create(point.Latitude.Value, point.Longitude.Value, null, point.Heading));
 }
예제 #23
0
        public void TryConvertGeographyPoint()
        {
            var    source = GeographyPoint.Create(10, 10);
            object targetValue;
            var    result = Utils.TryConvert(source, typeof(GeographyPoint), out targetValue);

            Assert.Equal(true, result);
        }
예제 #24
0
        private static List <Location> CreateList()
        {
            /* Example of the data in the file as a JSON
             *  {
             *      "id": 4794350,
             *      "name": "Wolf Trap",
             *      "ascii": "Wolf Trap",
             *      "alt_name": null,
             *      "lat": 38.93983,
             *      "long": -77.28609,
             *      "feat_class": "P",
             *      "feat_code": "PPL",
             *      "country": "US",
             *      "cc2": null,
             *      "admin1": "VA",
             *      "admin2": 59,
             *      "admin3": null,
             *      "admin4": null,
             *      "population": 16131,
             *      "elevation": 86,
             *      "dem": 89,
             *      "tz": "America/New_York",
             *      "modified_at": "2011-05-14"
             *  }, */

            string filePath = System.IO.Path.GetFullPath("data/cities_canada-usa.tsv");

            var locations = new List <Location>();

            // Haven't find a library that does this, so doing manually
            using (var streamReader = System.IO.File.OpenText(filePath))
            {
                while (!streamReader.EndOfStream)
                {
                    var line = streamReader.ReadLine();
                    var data = line.Split(new[] { '\t' });

                    if (!String.IsNullOrEmpty(data[0]) && data[0] != "id")
                    {
                        var location = new Location()
                        {
                            Id             = data[0],
                            Name           = data[1],
                            AsciiName      = data[2],
                            AlternatifName = data[3],
                            Geo            = GeographyPoint.Create(
                                double.Parse(data[4]),
                                double.Parse(data[5])
                                )
                        };

                        locations.Add(location);
                    }
                }
            }

            return(locations);
        }
예제 #25
0
        private static GeographyPoint CreateGeographyPoint(Location location)
        {
            if (location != null && location.Latitude != null && location.Longitude != null)
            {
                return(GeographyPoint.Create(location.Latitude.Value, location.Longitude.Value));
            }

            return(null);
        }
예제 #26
0
 public MappingProfile()
 {
     CreateMap <RealProperty, ApartmentDataIndexDocument>()
     .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.PropertyID))
     .ForMember(dest => dest.Location, opt => opt.MapFrom(src => GeographyPoint.Create((double)src.Lat, (double)src.Lng)));
     CreateMap <MgmntCompany, ApartmentDataIndexDocument>()
     .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.MgmtID));
     CreateMap <ApartmentDataIndexDocument, ApartmentDataSearchEntry>();
 }
예제 #27
0
        public void TryConvertGeographyPoint()
        {
            ITypeCache typeCache = new TypeCache();

            var source = GeographyPoint.Create(10, 10);
            var result = typeCache.TryConvert(source, typeof(GeographyPoint), out _);

            Assert.True(result);
        }
예제 #28
0
        public void WhenPropertiesAreDuplicatedTheLastInstanceIsUsed()
        {
            const string Json = @"{ ""type"": ""Point"", ""coordinates"": [ 121.9, 47.1 ], ""coordinates"": [ 122.1, 49.1 ] }";

            var            expectedPoint = GeographyPoint.Create(49.1, 122.1);
            GeographyPoint actualPoint   = DeserializeAndExpectSuccess(Json);

            Assert.Equal(expectedPoint, actualPoint);
        }
예제 #29
0
        public void CanReadWellFormedGeoPointWithIntegerCoordinates()
        {
            var          expectedPoint = GeographyPoint.Create(47, 121);
            const string Json          = @"{ ""type"": ""Point"", ""coordinates"": [ 121, 47 ] }";

            GeographyPoint actualPoint = DeserializeAndExpectSuccess(Json);

            Assert.Equal(expectedPoint, actualPoint);
        }
예제 #30
0
        public void GeographyToGeometryInJson()
        {
            var point  = GeographyPoint.Create(1, 2);
            var result = this.jsonConverter.ConvertPrimitiveValue(point, typeof(Geometry));

            result.Should().BeAssignableTo <GeometryPoint>();
            result.As <GeometryPoint>().X.Should().BeInRange(2, 2);
            result.As <GeometryPoint>().Y.Should().BeInRange(1, 1);
        }