Ejemplo n.º 1
0
        public void PostUsingAtomShouldBeFailed()
        {
            var entryWrapper = new ODataResourceWrapper()
            {
                Resource = new ODataResource()
                {
                    TypeName   = NameSpacePrefix + "Person",
                    Properties = new[]
                    {
                        new ODataProperty {
                            Name = "PersonID", Value = 101
                        },
                        new ODataProperty {
                            Name = "FirstName", Value = "Peter"
                        },
                        new ODataProperty {
                            Name = "LastName", Value = "Zhang"
                        },
                        new ODataProperty
                        {
                            Name  = "Home",
                            Value = GeographyPoint.Create(32.1, 23.1)
                        },
                        new ODataProperty
                        {
                            Name  = "Numbers",
                            Value = new ODataCollectionValue
                            {
                                TypeName = "Collection(Edm.String)",
                                Items    = new string[] { "12345" }
                            }
                        },
                        new ODataProperty
                        {
                            Name  = "Emails",
                            Value = new ODataCollectionValue
                            {
                                TypeName = "Collection(Edm.String)",
                                Items    = new string[] { "*****@*****.**" }
                            }
                        }
                    }
                },
                NestedResourceInfoWrappers = new List <ODataNestedResourceInfoWrapper>()
                {
                    new ODataNestedResourceInfoWrapper()
                    {
                        NestedResourceInfo = new ODataNestedResourceInfo()
                        {
                            Name         = "HomeAddress",
                            IsCollection = false
                        },
                        NestedResourceOrResourceSet = new ODataResourceWrapper()
                        {
                            Resource = new ODataResource()
                            {
                                TypeName   = NameSpacePrefix + "HomeAddress",
                                Properties = new[]
                                {
                                    new ODataProperty
                                    {
                                        Name  = "Street",
                                        Value = "ZiXing Road"
                                    },
                                    new ODataProperty
                                    {
                                        Name  = "City",
                                        Value = "Chengdu"
                                    },
                                    new ODataProperty
                                    {
                                        Name  = "PostalCode",
                                        Value = "200241"
                                    },
                                    new ODataProperty
                                    {
                                        Name  = "FamilyName",
                                        Value = "Tigers"
                                    }
                                }
                            }
                        }
                    }
                }
            };

            var settings = new ODataMessageWriterSettings();

            settings.BaseUri = ServiceBaseUri;

            var personType = Model.FindDeclaredType(NameSpacePrefix + "Person") as IEdmEntityType;
            var peopleSet  = Model.EntityContainer.FindEntitySet("People");

            var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri + "People"));

            requestMessage.SetHeader("Content-Type", MimeTypes.ApplicationAtomXml);
            requestMessage.SetHeader("Accept", MimeTypes.ApplicationAtomXml);
            requestMessage.Method = "POST";
            using (var messageWriter = new ODataMessageWriter(requestMessage, settings, Model))
            {
                try
                {
                    var odataWriter = messageWriter.CreateODataResourceWriter(peopleSet, personType);
                    ODataWriterHelper.WriteResource(odataWriter, entryWrapper);
                }
                catch (Microsoft.OData.ODataContentTypeException)
                {
                    return;
                }
                Assert.IsTrue(false);
            }
        }
Ejemplo n.º 2
0
        public List <SpeciesInfo> Filter(List <SpeciesInfo> speciesInfos, GeographyPoint coordinates)
        {
            var localTaxonomies = _iucnClient.GetLocalSpeciesTaxonomiesList(coordinates);

            return(GetBestMatches(speciesInfos, localTaxonomies));
        }
Ejemplo n.º 3
0
        public void CanMergeDynamicDocuments()
        {
            Run(() =>
            {
                SearchIndexClient client = Data.GetSearchIndexClient();

                var originalDoc =
                    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 updatedDoc =
                    new Document()
                {
                    { "hotelId", "1" },
                    { "baseRate", 99.0 },
                    { "description", null },
                    { "category", "Business" },
                    { "tags", new[] { "pool", "view", "wifi" } },
                    { "parkingIncluded", true },
                    { "lastRenovationDate", null },
                    { "rating", 4L },
                    { "location", null }
                };

                var expectedDoc =
                    new Document()
                {
                    { "hotelId", "1" },
                    { "baseRate", 99.0 },
                    { "description", null },
                    { "descriptionFr", "Meilleur hôtel en ville" },
                    { "hotelName", "Fancy Stay" },
                    { "category", "Business" },
                    { "tags", new[] { "pool", "view", "wifi" } },
                    { "parkingIncluded", true },
                    { "smokingAllowed", false },
                    { "lastRenovationDate", null },
                    { "rating", 4L },
                    { "location", null }
                };

                client.Documents.Index(IndexBatch.MergeOrUpload(new[] { originalDoc }));
                SearchTestUtilities.WaitForIndexing();

                client.Documents.Index(IndexBatch.Merge(new[] { updatedDoc }));
                SearchTestUtilities.WaitForIndexing();

                Document actualDoc = client.Documents.Get("1");

                Assert.Equal(expectedDoc, actualDoc);

                client.Documents.Index(IndexBatch.MergeOrUpload(new[] { originalDoc }));
                SearchTestUtilities.WaitForIndexing();

                actualDoc = client.Documents.Get("1");

                Assert.Equal(originalDoc, actualDoc);
            });
        }
Ejemplo n.º 4
0
        public void MappingPoco()
        {
            var now = DateTime.Now;
            // TODO: ms = 0 ??
            var dt = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
            var a  = new Aoba
            {
                Id       = "id-6502",
                IgnoreMe = false,
                Title    = "Umiko",
                Tags     = new List <string> {
                    "hi", "ho"
                },
                Location = new GeoPoint(130.56, 220.44),
                Clever   = true,
                Work     = dt,
                Bees     = new List <ComplexItem> {
                    new ComplexItem {
                        Text = "Maya", Number = 100, Flag = false
                    },
                    new ComplexItem {
                        Text = "Hornet", Number = 130, Flag = true
                    }
                }
            };

            var search = a.MapToIndex();

            // class mappings
            Assert.AreEqual("myproject/aoba", search.Entity);
            Assert.AreEqual(true, search.Flag8);
            Assert.AreEqual(null, search.Flag1);

            // property mappins
            Assert.AreEqual("id-6502", search.Id);
            Assert.AreEqual("Umiko", search.Text0);
            Assert.AreEqual(null, search.Flag3);
            Assert.AreEqual(true, search.Flag4);
            Assert.AreEqual(2, search.Tags7.Count);
            Assert.AreEqual("ho", search.Tags7[1]);
            Assert.AreEqual(220, search.Number0);
            Assert.AreEqual(120, search.Number1);
            Assert.AreEqual((Int64)(Int32)Color.Blue, search.Number2);
            Assert.AreEqual(3.14, search.Double2);
            Assert.AreEqual(dt, search.Date0);
            Assert.AreEqual(GeographyPoint.Create(130.56, 220.44).Latitude, search.Point0.Latitude);
            Assert.AreEqual(GeographyPoint.Create(130.56, 220.44).Longitude, search.Point0.Longitude);
            Assert.AreEqual("Maya", search.Complex0.First().Text);
            Assert.AreEqual(100, search.Complex0.First().Number);
            Assert.AreEqual(false, search.Complex0.First().Flag);
            Assert.AreEqual("Hornet", search.Complex0.Last().Text);
            Assert.AreEqual(130, search.Complex0.Last().Number);
            Assert.AreEqual(true, search.Complex0.Last().Flag);

            var a2 = search.MapFromIndex <Aoba>();

            Assert.AreEqual("id-6502", a2.Id);
            Assert.AreEqual("Umiko", a2.Title);
            Assert.AreEqual(null, a2.DoNotIgnoreMe);
            Assert.AreEqual(true, a2.Clever);
            Assert.AreEqual(2, a2.Tags.Count);
            Assert.AreEqual("ho", a2.Tags[1]);
            Assert.AreEqual(220, a2.Iq);
            Assert.AreEqual(120, a2.RealIq);
            Assert.AreEqual(3.14, a2.Money);
            Assert.AreEqual(dt, a2.Work);
            Assert.AreEqual(new GeoPoint(130.56, 220.44).Coordinates[0], a2.Location.Coordinates[0]);
            Assert.AreEqual(new GeoPoint(130.56, 220.44).Coordinates[1], a2.Location.Coordinates[1]);
            Assert.AreEqual(new GeoPoint(130.56, 220.44).Type, a2.Location.Type);
            Assert.AreEqual("Maya", a2.Bees.First().Text);
            Assert.AreEqual(100, a2.Bees.First().Number);
            Assert.AreEqual(false, a2.Bees.First().Flag);
            Assert.AreEqual("Hornet", a2.Bees.Last().Text);
            Assert.AreEqual(130, a2.Bees.Last().Number);
            Assert.AreEqual(true, a2.Bees.Last().Flag);
        }
Ejemplo n.º 5
0
        public GeographyPoint LocationSwipe([FromODataUri] int key, ODataActionParameters parameters)
        {
            var loc = (GeographyPoint)parameters["Loc"] ?? null;

            return(GeographyPoint.Create(loc.Longitude, loc.Latitude));
        }
Ejemplo n.º 6
0
        public void CanIndexStaticallyTypedDocuments()
        {
            Run(() =>
            {
                SearchIndexClient client = Data.GetSearchIndexClient();

                var batch = IndexBatch.New(new[]
                {
                    IndexAction.Upload(
                        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.FromHours(-8)),
                        Rating             = 5,
                        Location           = GeographyPoint.Create(47.678581, -122.131577)
                    }),
                    IndexAction.Upload(
                        new Hotel()
                    {
                        HotelId            = "2",
                        BaseRate           = 79.99,
                        Description        = "Cheapest hotel in town",
                        DescriptionFr      = "Hôtel le moins cher en ville",
                        HotelName          = "Roach Motel",
                        Category           = "Budget",
                        Tags               = new[] { "motel", "budget" },
                        ParkingIncluded    = true,
                        SmokingAllowed     = true,
                        LastRenovationDate = new DateTimeOffset(1982, 4, 28, 0, 0, 0, TimeSpan.Zero),       //aka.ms/sre-codescan/disable
                        Rating             = 1,
                        Location           = GeographyPoint.Create(49.678581, -122.131577)
                    }),
                    IndexAction.Merge(
                        new Hotel()
                    {
                        HotelId            = "3",
                        BaseRate           = 279.99,
                        Description        = "Surprisingly expensive",
                        LastRenovationDate = null
                    }),
                    IndexAction.Delete(new Hotel()
                    {
                        HotelId = "4"
                    }),
                    IndexAction.MergeOrUpload(
                        new Hotel()
                    {
                        HotelId   = "5",
                        BaseRate  = Double.NaN,
                        HotelName = null,
                        Tags      = new string[0]
                    })
                });

                IndexBatchException e = Assert.Throws <IndexBatchException>(() => client.Documents.Index(batch));
                AssertIsPartialFailure(e, "3");

                Assert.Equal(5, e.IndexingResults.Count);

                AssertIndexActionSucceeded("1", e.IndexingResults[0], 201);
                AssertIndexActionSucceeded("2", e.IndexingResults[1], 201);
                AssertIndexActionFailed("3", e.IndexingResults[2], "Document not found.", 404);
                AssertIndexActionSucceeded("4", e.IndexingResults[3], 200);
                AssertIndexActionSucceeded("5", e.IndexingResults[4], 201);

                SearchTestUtilities.WaitForIndexing();

                Assert.Equal(3, client.Documents.Count());
            });
        }
Ejemplo n.º 7
0
        public void CanGetDynamicDocument()
        {
            Run(() =>
            {
                SearchIndexClient client = Data.GetSearchIndexClient();

                var expectedDoc =
                    new Document()
                {
                    ["hotelId"]            = "1",
                    ["hotelName"]          = "Secret Point Motel",
                    ["description"]        = "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.",
                    ["descriptionFr"]      = "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.",
                    ["category"]           = "Boutique",
                    ["tags"]               = new[] { "pool", "air conditioning", "concierge" },
                    ["parkingIncluded"]    = false,
                    ["smokingAllowed"]     = true,
                    ["lastRenovationDate"] = new DateTimeOffset(1970, 1, 18, 0, 0, 0, TimeSpan.FromHours(-5)),
                    ["rating"]             = 4L,
                    ["location"]           = GeographyPoint.Create(40.760586, -73.975403),
                    ["address"]            = new Document()
                    {
                        ["streetAddress"] = "677 5th Ave",
                        ["city"]          = "New York",
                        ["stateProvince"] = "NY",
                        ["country"]       = "USA",
                        ["postalCode"]    = "10022"
                    },
                    ["rooms"] = new[]
                    {
                        new Document()
                        {
                            ["description"]    = "Budget Room, 1 Queen Bed (Cityside)",
                            ["descriptionFr"]  = "Chambre Économique, 1 grand lit (côté ville)",
                            ["type"]           = "Budget Room",
                            ["baseRate"]       = 9.69,
                            ["bedOptions"]     = "1 Queen Bed",
                            ["sleepsCount"]    = 2L,
                            ["smokingAllowed"] = true,
                            ["tags"]           = new[] { "vcr/dvd" }
                        },
                        new Document()
                        {
                            ["description"]    = "Budget Room, 1 King Bed (Mountain View)",
                            ["descriptionFr"]  = "Chambre Économique, 1 très grand lit (Mountain View)",
                            ["type"]           = "Budget Room",
                            ["baseRate"]       = 8.09,
                            ["bedOptions"]     = "1 King Bed",
                            ["sleepsCount"]    = 2L,
                            ["smokingAllowed"] = true,
                            ["tags"]           = new[] { "vcr/dvd", "jacuzzi tub" }
                        }
                    }
                };

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

                Document actualDoc = client.Documents.Get("1");
                Assert.Equal(expectedDoc, actualDoc);
            });
        }
        private static void UploadDocuments(SearchServiceClient serviceClient)
        {
            SearchIndexClient indexClient = serviceClient.Indexes.GetClient("hotels");

            var actions =
                new IndexAction <Hotel>[]
            {
                IndexAction.Upload(
                    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)
                }),
                IndexAction.Upload(
                    new Hotel()
                {
                    HotelId            = "2",
                    BaseRate           = 79.99,
                    Description        = "Cheapest hotel in town",
                    DescriptionFr      = "Hôtel le moins cher en ville",
                    HotelName          = "Roach Motel",
                    Category           = "Budget",
                    Tags               = new[] { "motel", "budget" },
                    ParkingIncluded    = true,
                    SmokingAllowed     = true,
                    LastRenovationDate = new DateTimeOffset(1982, 4, 28, 0, 0, 0, TimeSpan.Zero),
                    Rating             = 1,
                    Location           = GeographyPoint.Create(49.678581, -122.131577)
                }),
                IndexAction.MergeOrUpload(
                    new Hotel()
                {
                    HotelId     = "3",
                    BaseRate    = 129.99,
                    Description = "Close to town hall and the river"
                }),
                IndexAction.Delete(new Hotel()
                {
                    HotelId = "6"
                })
            };

            var batch = IndexBatch.New(actions);

            try
            {
                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)));
            }

            Console.WriteLine("Waiting for documents to be indexed...\n");
            Thread.Sleep(2000);
        }
 public override void Process(JsonReader reader)
 {
     GeographyPoint = reader.ReadPoint();
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Populates the data source.
        /// </summary>
        private static void EnsureDataSource()
        {
            if (people == null)
            {
                people = new List <Person>()
                {
                    new Customer()
                    {
                        FirstName = "Bob",
                        LastName  = "Cat",
                        Numbers   = new Collection <string> {
                            "111-111-1111"
                        },
                        PersonID = 1,
                        Birthday = new DateTime(1957, 4, 3),
                        City     = "London",
                        Home     = GeographyPoint.Create(32.1, 23.1)
                    },
                    new Customer()
                    {
                        FirstName = "Jill",
                        LastName  = "Jones",
                        Numbers   = new Collection <string> {
                        },
                        PersonID  = 2,
                        Birthday  = new DateTime(1983, 1, 15),
                        City      = "Sydney",
                        Home      = GeographyPoint.Create(15.0, 161.8)
                    },
                    new Employee()
                    {
                        FirstName = "Jacob",
                        LastName  = "Zip",
                        Numbers   = new Collection <string> {
                            "333-333-3333"
                        },
                        PersonID  = 3,
                        DateHired = new DateTime(2010, 12, 13),
                        Home      = GeographyPoint.Create(15.0, 161.8),
                        Office    = GeographyPoint.Create(15.0, 162)
                    },
                    new Employee()
                    {
                        FirstName = "Elmo",
                        LastName  = "Rogers",
                        Numbers   = new Collection <string> {
                            "444-444-4444", "555-555-5555", "666-666-6666"
                        },
                        PersonID  = 4,
                        DateHired = new DateTime(2008, 3, 27),
                        Home      = GeographyPoint.Create(-15.0, -61.8),
                        Office    = GeographyPoint.Create(-15.0, -62)
                    }
                };

                products = new List <Product>()
                {
                    new Product()
                    {
                        Name            = "Cheetos",
                        ProductID       = 5,
                        QuantityInStock = 100,
                        QuantityPerUnit = "100g Bag",
                        UnitPrice       = 3.24f,
                        Discontinued    = true
                    },
                    new Product()
                    {
                        Name            = "Mushrooms",
                        ProductID       = 6,
                        QuantityInStock = 100,
                        QuantityPerUnit = "Pound",
                        UnitPrice       = 3.24f,
                        Discontinued    = false
                    }
                };

                orders = new List <Order>()
                {
                    new Order()
                    {
                        OrderID          = 7,
                        CustomerForOrder = people.OfType <Customer>().ElementAt(1),
                        CustomerID       = people.OfType <Customer>().ElementAt(1).PersonID,
                        LoggedInEmployee = people.OfType <Employee>().ElementAt(0),
                        EmployeeID       = people.OfType <Employee>().ElementAt(0).PersonID,
                        OrderDate        = new DateTime(2011, 5, 29, 14, 21, 12)
                    },
                    new Order()
                    {
                        OrderID          = 8,
                        CustomerForOrder = people.OfType <Customer>().ElementAt(0),
                        CustomerID       = people.OfType <Customer>().ElementAt(0).PersonID,
                        LoggedInEmployee = people.OfType <Employee>().ElementAt(1),
                        EmployeeID       = people.OfType <Employee>().ElementAt(1).PersonID,
                        OrderDate        = new DateTime(2011, 3, 4, 16, 3, 57)
                    }
                };

                orderdetails = new List <OrderDetail>()
                {
                    new OrderDetail()
                    {
                        OrderID         = orders[0].OrderID,
                        AssociatedOrder = orders[0],
                        ProductID       = products[0].ProductID,
                        ProductOrdered  = products[0],
                        Quantity        = 50,
                        UnitPrice       = products[0].UnitPrice
                    },
                    new OrderDetail()
                    {
                        OrderID         = orders[0].OrderID,
                        AssociatedOrder = orders[0],
                        ProductID       = products[1].ProductID,
                        ProductOrdered  = products[1],
                        Quantity        = 2,
                        UnitPrice       = products[1].UnitPrice
                    },
                    new OrderDetail()
                    {
                        OrderID         = orders[1].OrderID,
                        AssociatedOrder = orders[1],
                        ProductID       = products[1].ProductID,
                        ProductOrdered  = products[1],
                        Quantity        = 5,
                        UnitPrice       = products[1].UnitPrice
                    }
                };
            }
        }
Ejemplo n.º 11
0
        // Upload documents in a single Upload request.
        public async Task UploadDocumentsAsync()
        {
            IndexDocumentsBatch <Hotel> batch = IndexDocumentsBatch.Create(
                IndexDocumentsAction.Upload(
                    new Hotel()
            {
                HotelId            = "1",
                HotelName          = "Secret Point Motel",
                Description        = "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.",
                DescriptionFr      = "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.",
                Category           = "Boutique",
                Tags               = new[] { "pool", "air conditioning", "concierge" },
                ParkingIncluded    = false,
                LastRenovationDate = new DateTimeOffset(1970, 1, 18, 0, 0, 0, TimeSpan.Zero),
                Rating             = 3.6,
                Location           = GeographyPoint.Create(22, 22),
                Rooms              = new Room[]
                {
                    new Room()
                    {
                        Description = "Room Des", BaseRate = 100, DescriptionFr = "Le Room", BedOptions = "Any", Type = "Single", SmokingAllowed = false, SleepsCount = 3, Tags = new string[] { "single", "front", "near pool" }
                    }
                },
                cheapest  = 100,
                expensive = 300,
                Address   = new Address()
                {
                    StreetAddress = "677 5th Ave",
                    City          = "New York",
                    StateProvince = "NY",
                    PostalCode    = "10022",
                    Country       = "USA"
                }
            }),
                IndexDocumentsAction.Upload(
                    new Hotel()
            {
                HotelId            = "2",
                HotelName          = "Twin Dome Motel",
                Description        = "The hotel is situated in a  nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts.",
                DescriptionFr      = "L'hôtel est situé dans une place du XIXe siècle, qui a été agrandie et rénovée aux plus hautes normes architecturales pour créer un hôtel moderne, fonctionnel et de première classe dans lequel l'art et les éléments historiques uniques coexistent avec le confort le plus moderne.",
                Category           = "Boutique",
                Tags               = new[] { "pool", "free wifi", "concierge" },
                ParkingIncluded    = false,
                LastRenovationDate = new DateTimeOffset(1979, 2, 18, 0, 0, 0, TimeSpan.Zero),
                Rating             = 3.60,
                Address            = new Address()
                {
                    StreetAddress = "140 University Town Center Dr",
                    City          = "Sarasota",
                    StateProvince = "FL",
                    PostalCode    = "34243",
                    Country       = "USA"
                },
                Location = GeographyPoint.Create(22, 22),
                Rooms    = new Room[]
                {
                    new Room()
                    {
                        Description = "Room Des", BaseRate = 100, DescriptionFr = "Le Room", BedOptions = "Any", Type = "Single", SmokingAllowed = false, SleepsCount = 3, Tags = new string[] { "single", "front", "near pool" }
                    }
                },
                cheapest  = 100,
                expensive = 300,
            }),
                IndexDocumentsAction.Upload(
                    new Hotel()
            {
                HotelId            = "3",
                HotelName          = "Triple Landscape Hotel",
                Description        = "The Hotel stands out for its gastronomic excellence under the management of William Dough, who advises on and oversees all of the Hotel’s restaurant services.",
                DescriptionFr      = "L'hôtel est situé dans une place du XIXe siècle, qui a été agrandie et rénovée aux plus hautes normes architecturales pour créer un hôtel moderne, fonctionnel et de première classe dans lequel l'art et les éléments historiques uniques coexistent avec le confort le plus moderne.",
                Category           = "Resort and Spa",
                Tags               = new[] { "air conditioning", "bar", "continental breakfast" },
                ParkingIncluded    = true,
                LastRenovationDate = new DateTimeOffset(2015, 9, 20, 0, 0, 0, TimeSpan.Zero),
                Rating             = 4.80,
                Address            = new Address()
                {
                    StreetAddress = "3393 Peachtree Rd",
                    City          = "Atlanta",
                    StateProvince = "GA",
                    PostalCode    = "30326",
                    Country       = "USA"
                },
                Location = GeographyPoint.Create(22, 22),
                Rooms    = new Room[]
                {
                    new Room()
                    {
                        Description = "Room Des", BaseRate = 100, DescriptionFr = "Le Room", BedOptions = "Any", Type = "Single", SmokingAllowed = false, SleepsCount = 3, Tags = new string[] { "single", "front", "near pool" }
                    }
                },
                cheapest  = 100,
                expensive = 300,
            }),
                IndexDocumentsAction.Upload(
                    new Hotel()
            {
                HotelId            = "4",
                HotelName          = "Sublime Cliff Hotel",
                Description        = "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 1800 palace.",
                DescriptionFr      = "Le sublime Cliff Hotel est situé au coeur du centre historique de sublime dans un quartier extrêmement animé et vivant, à courte distance de marche des sites et monuments de la ville et est entouré par l'extraordinaire beauté des églises, des bâtiments, des commerces et Monuments. Sublime Cliff fait partie d'un Palace 1800 restauré avec amour.",
                Category           = "Boutique",
                Tags               = new[] { "concierge", "view", "24-hour front desk service" },
                ParkingIncluded    = true,
                LastRenovationDate = new DateTimeOffset(1960, 2, 06, 0, 0, 0, TimeSpan.Zero),
                Rating             = 4.60,
                Address            = new Address()
                {
                    StreetAddress = "7400 San Pedro Ave",
                    City          = "San Antonio",
                    StateProvince = "TX",
                    PostalCode    = "78216",
                    Country       = "USA"
                },
                Location = GeographyPoint.Create(22, 22),
                Rooms    = new Room[]
                {
                    new Room()
                    {
                        Description = "Room Des", BaseRate = 100, DescriptionFr = "Le Room", BedOptions = "Any", Type = "Single", SmokingAllowed = false, SleepsCount = 3, Tags = new string[] { "single", "front", "near pool" }
                    }
                },
                cheapest  = 100,
                expensive = 300,
            })
                );

            IndexDocumentsResult result = await _searchClient.IndexDocumentsAsync(batch);
        }
 public List <SpeciesInfo> Filter(List <SpeciesInfo> speciesInfos, GeographyPoint coordinates)
 {
     return(speciesInfos.Where(candidate => !IsOutlier(candidate.Taxonomy,
                                                       speciesInfos.Select(speciesInfo => candidate.Taxonomy).ToList())).ToList());
 }
Ejemplo n.º 13
0
        private static GeographyFactory <GeographyCollection> Add(this GeographyFactory <GeographyCollection> factory, GeographyPoint point)
        {
            factory = factory.Point(point.Latitude, point.Longitude);

            return(factory);
        }
Ejemplo n.º 14
0
        public void WriteInstanceAnnotationShouldWriteValueTypeIfMoreDerivedThanMetadataType()
        {
            // Add a term of type Geography to the model.
            this.referencedModel.AddElement(new EdmTerm("My.Namespace", "GeographyTerm", EdmPrimitiveTypeKind.Geography));
            var instanceAnnotation = new ODataInstanceAnnotation("My.Namespace.GeographyTerm", new ODataPrimitiveValue(GeographyPoint.Create(0.0, 0.0)));

            bool writingTypeName = false;
            bool wroteTypeName   = false;

            this.jsonWriter.WriteNameVerifier = s =>
            {
                writingTypeName = s.EndsWith("odata.type");
            };

            this.jsonWriter.WriteValueVerifier = s =>
            {
                if (writingTypeName)
                {
                    Assert.Equal("#GeographyPoint", s);
                    wroteTypeName = true;
                }
            };

            this.valueWriter.WritePrimitiveVerifier = (o, reference) => { };

            this.jsonLightInstanceAnnotationWriter.WriteInstanceAnnotation(instanceAnnotation);

            Assert.True(wroteTypeName);
        }
Ejemplo n.º 15
0
        public void CanGetDocumentMappedToStruct()
        {
            Run(() =>
            {
                SearchIndexClient client = Data.GetSearchIndexClient();

                var expectedDoc =
                    new StructHotel()
                {
                    HotelId            = "1",
                    HotelName          = "Secret Point Motel",
                    Description        = "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.",
                    DescriptionFr      = "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.",
                    Category           = "Boutique",
                    Tags               = new[] { "pool", "air conditioning", "concierge" },
                    ParkingIncluded    = false,
                    SmokingAllowed     = true,
                    LastRenovationDate = new DateTimeOffset(1970, 1, 18, 0, 0, 0, TimeSpan.FromHours(-5)),
                    Rating             = 4,
                    Location           = GeographyPoint.Create(40.760586, -73.975403),
                    Address            = new StructHotelAddress()
                    {
                        StreetAddress = "677 5th Ave",
                        City          = "New York",
                        StateProvince = "NY",
                        Country       = "USA",
                        PostalCode    = "10022"
                    },
                    Rooms = new[]
                    {
                        new StructHotelRoom()
                        {
                            Description    = "Budget Room, 1 Queen Bed (Cityside)",
                            DescriptionFr  = "Chambre Économique, 1 grand lit (côté ville)",
                            Type           = "Budget Room",
                            BaseRate       = 9.69,
                            BedOptions     = "1 Queen Bed",
                            SleepsCount    = 2,
                            SmokingAllowed = true,
                            Tags           = new[] { "vcr/dvd" }
                        },
                        new StructHotelRoom()
                        {
                            Description    = "Budget Room, 1 King Bed (Mountain View)",
                            DescriptionFr  = "Chambre Économique, 1 très grand lit (Mountain View)",
                            Type           = "Budget Room",
                            BaseRate       = 8.09,
                            BedOptions     = "1 King Bed",
                            SleepsCount    = 2,
                            SmokingAllowed = true,
                            Tags           = new[] { "vcr/dvd", "jacuzzi tub" }
                        }
                    }
                };

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

                StructHotel actualDoc = client.Documents.Get <StructHotel>("1");
                Assert.Equal(expectedDoc, actualDoc);
            });
        }
Ejemplo n.º 16
0
        public void MultipleTypeCustomInstanceAnnotationsOnErrorShouldRoundtrip()
        {
            var            originalInt            = new KeyValuePair <string, ODataValue>("int.error", new ODataPrimitiveValue(1));
            var            originalDouble         = new KeyValuePair <string, ODataValue>("double.error", new ODataPrimitiveValue(double.NaN));
            DateTimeOffset dateTimeOffset         = new DateTimeOffset(2012, 10, 10, 12, 12, 59, new TimeSpan());
            var            originalDateTimeOffset = new KeyValuePair <string, ODataValue>("DateTimeOffset.error", new ODataPrimitiveValue(dateTimeOffset));
            Date           date              = new Date(2014, 12, 12);
            var            originalDate      = new KeyValuePair <string, ODataValue>("Date.error", new ODataPrimitiveValue(date));
            TimeOfDay      time              = new TimeOfDay(10, 12, 3, 9);
            var            originaltime      = new KeyValuePair <string, ODataValue>("TimeOfDay.error", new ODataPrimitiveValue(time));
            TimeSpan       timeSpan          = new TimeSpan(12345);
            var            originalTimeSpan  = new KeyValuePair <string, ODataValue>("TimeSpan.error", new ODataPrimitiveValue(timeSpan));
            GeographyPoint geographyPoint    = GeographyPoint.Create(32.0, -100.0);
            var            originalGeography = new KeyValuePair <string, ODataValue>("Geography.error", new ODataPrimitiveValue(geographyPoint));
            var            originalNull      = new KeyValuePair <string, ODataValue>("null.error", new ODataNullValue());

            /*
             * var complexValue = new ODataComplexValue
             * {
             *  TypeName = "ns.ErrorDetails",
             *  Properties = new[] { new ODataProperty { Name = "ErrorDetailName", Value = "inner property value" } }
             * };
             * var originalComplex = new KeyValuePair<string, ODataValue>("sample.error", complexValue);
             */

            var error = this.WriteThenReadErrorWithInstanceAnnotation(originalInt, originalDouble, originalDate, originalDateTimeOffset, originaltime, originalTimeSpan, originalGeography, originalNull);

            var annotation = RunBasicVerificationAndGetAnnotationValue("int.error", error);

            annotation.Should().BeOfType <ODataPrimitiveValue>();
            annotation.As <ODataPrimitiveValue>().Value.Should().Be(1);

            annotation = RunBasicVerificationAndGetAnnotationValue("double.error", error);
            annotation.Should().BeOfType <ODataPrimitiveValue>();
            annotation.As <ODataPrimitiveValue>().Value.Should().Be(double.NaN);

            annotation = RunBasicVerificationAndGetAnnotationValue("Date.error", error);
            annotation.Should().BeOfType <ODataPrimitiveValue>();
            annotation.As <ODataPrimitiveValue>().Value.Should().Be(date);

            annotation = RunBasicVerificationAndGetAnnotationValue("DateTimeOffset.error", error);
            annotation.Should().BeOfType <ODataPrimitiveValue>();
            annotation.As <ODataPrimitiveValue>().Value.Should().Be(dateTimeOffset);

            annotation = RunBasicVerificationAndGetAnnotationValue("TimeOfDay.error", error);
            annotation.Should().BeOfType <ODataPrimitiveValue>();
            annotation.As <ODataPrimitiveValue>().Value.Should().Be(time);

            annotation = RunBasicVerificationAndGetAnnotationValue("TimeSpan.error", error);
            annotation.Should().BeOfType <ODataPrimitiveValue>();
            annotation.As <ODataPrimitiveValue>().Value.Should().Be(timeSpan);

            annotation = RunBasicVerificationAndGetAnnotationValue("Geography.error", error);
            annotation.Should().BeOfType <ODataPrimitiveValue>();
            annotation.As <ODataPrimitiveValue>().Value.Should().Be(geographyPoint);

            annotation = RunBasicVerificationAndGetAnnotationValue("null.error", error);
            annotation.Should().BeOfType <ODataNullValue>();

            /*
             * annotation = RunBasicVerificationAndGetAnnotationValue("sample.error", error);
             * annotation.Should().BeOfType<ODataComplexValue>();
             * annotation.As<ODataComplexValue>().Properties.First().Value.Should().Be("inner property value");
             */
        }
Ejemplo n.º 17
0
        public void GetStaticallyTypedDocumentSetsUnselectedFieldsToNull()
        {
            Run(() =>
            {
                SearchIndexClient client = Data.GetSearchIndexClient();

                var indexedDoc =
                    new Hotel()
                {
                    HotelId            = "2",
                    HotelName          = "Countryside Hotel",
                    Description        = "Save up to 50% off traditional hotels.  Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.",
                    DescriptionFr      = "Économisez jusqu'à 50% sur les hôtels traditionnels.  WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.",
                    Category           = "Budget",
                    Tags               = new[] { "24-hour front desk service", "coffee in lobby", "restaurant" },
                    ParkingIncluded    = false,
                    SmokingAllowed     = true,
                    LastRenovationDate = new DateTimeOffset(1999, 9, 6, 0, 0, 0, TimeSpan.Zero),       //aka.ms/sre-codescan/disable
                    Rating             = 3,
                    Location           = GeographyPoint.Create(35.904160, -78.940483),
                    Address            = new HotelAddress()
                    {
                        StreetAddress = "6910 Fayetteville Rd",
                        City          = "Durham",
                        StateProvince = "NC",
                        Country       = "USA",
                        PostalCode    = "27713"
                    },
                    Rooms = new[]
                    {
                        new HotelRoom()
                        {
                            Description    = "Suite, 1 King Bed (Amenities)",
                            DescriptionFr  = "Suite, 1 très grand lit (Services)",
                            Type           = "Suite",
                            BaseRate       = 2.44,
                            BedOptions     = "1 King Bed",
                            SleepsCount    = 2,
                            SmokingAllowed = true,
                            Tags           = new[] { "coffee maker" }
                        },
                        new HotelRoom()
                        {
                            Description    = "Budget Room, 1 Queen Bed (Amenities)",
                            DescriptionFr  = "Chambre Économique, 1 grand lit (Services)",
                            Type           = "Budget Room",
                            BaseRate       = 7.69,
                            BedOptions     = "1 Queen Bed",
                            SleepsCount    = 2,
                            SmokingAllowed = false,
                            Tags           = new [] { "coffee maker" }
                        }
                    }
                };

                var expectedDoc =
                    new Hotel()
                {
                    HotelName   = "Countryside Hotel",
                    Description = "Save up to 50% off traditional hotels.  Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.",
                    Address     = new HotelAddress()
                    {
                        City = "Durham"
                    },
                    Rooms = new[]
                    {
                        new HotelRoom()
                        {
                            BaseRate = 2.44
                        },
                        new HotelRoom()
                        {
                            BaseRate = 7.69
                        }
                    }
                };

                var batch = IndexBatch.Upload(new[] { indexedDoc });
                client.Documents.Index(batch);

                var selectedFields = new[] { "description", "hotelName", "address/city", "rooms/baseRate" };
                Hotel actualDoc    = client.Documents.Get <Hotel>("2", selectedFields);
                Assert.Equal(expectedDoc, actualDoc);
            });
        }
 private GeoProperty[] GetGeoProps(Dictionary <SearchAttribute, object> values) =>
 GetPropertiesObjects <Point>(Related.GEO, values).Select(s => new GeoProperty {
     PropertyIndex = s.PropertyIndex,
     Value         = GeographyPoint.Create(s.Value.Position.Latitude, s.Value.Position.Longitude)
 }).ToArray();
        public void ReadNullReturnsNull()
        {
            GeographyPoint point = JsonConvert.DeserializeObject <GeographyPoint>("null", _jsonSettings);

            Assert.Null(point);
        }
Ejemplo n.º 20
0
        public override void Process(IODataRequestMessage requestMessage, IODataResponseMessage responseMessage)
        {
            var token = HttpUtility.ParseQueryString(RequestUri.Query).Get("$token");

            if (string.IsNullOrEmpty(token))
            {
                deltaToken = "common";
            }
            else
            {
                deltaToken = token;
            }

            if (deltaToken == "common")
            {
                originalUri = new Uri(ServiceConstants.ServiceBaseUri, "Customers?$expand=Orders");
                using (var messageWriter = this.CreateMessageWriter(responseMessage))
                {
                    var entitySet  = this.DataSource.Model.FindDeclaredEntitySet("Customers");
                    var entityType = entitySet.EntityType();
                    ODataDeltaWriter deltaWriter = messageWriter.CreateODataDeltaWriter(entitySet, entityType);

                    var deltaFeed  = new ODataDeltaFeed();
                    var deltaEntry = new ODataEntry
                    {
                        Id         = new Uri(ServiceConstants.ServiceBaseUri, entitySet.Name + "(1)"),
                        Properties = new[] { new ODataProperty {
                                                 Name = "FirstName", Value = "GGGG"
                                             } }
                    };
                    var deletedLink = new ODataDeltaDeletedLink(
                        new Uri(ServiceConstants.ServiceBaseUri, entitySet.Name + "(1)"), new Uri(ServiceConstants.ServiceBaseUri, "Orders(8)"), "Orders");
                    var addedLink = new ODataDeltaLink(
                        new Uri(ServiceConstants.ServiceBaseUri, entitySet.Name + "(1)"), new Uri(ServiceConstants.ServiceBaseUri, "Orders(7)"), "Orders");
                    var navigationEntry = new ODataEntry
                    {
                        Id         = new Uri(ServiceConstants.ServiceBaseUri, "Orders(100)"),
                        TypeName   = "Microsoft.Test.OData.Services.ODataWCFService.Order",
                        Properties = new[]
                        {
                            new ODataProperty {
                                Name = "OrderID", Value = 100
                            },
                            new ODataProperty {
                                Name = "OrderDate", Value = new DateTimeOffset(DateTime.Now)
                            }
                        }
                    };
                    navigationEntry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo
                    {
                        NavigationSourceEntityTypeName = "Microsoft.Test.OData.Services.ODataWCFService.Order",
                        NavigationSourceKind           = EdmNavigationSourceKind.EntitySet,
                        NavigationSourceName           = "Orders"
                    });

                    var deletedEntry = new ODataDeltaDeletedEntry(
                        new Uri(ServiceConstants.ServiceBaseUri, entitySet.Name + "(2)").AbsoluteUri, DeltaDeletedEntryReason.Deleted);

                    deltaFeed.DeltaLink = new Uri(ServiceConstants.ServiceBaseUri, "$delta?$token=common");

                    deltaWriter.WriteStart(deltaFeed);
                    deltaWriter.WriteStart(deltaEntry);
                    deltaWriter.WriteEnd();
                    deltaWriter.WriteDeltaDeletedLink(deletedLink);
                    deltaWriter.WriteDeltaLink(addedLink);
                    deltaWriter.WriteStart(navigationEntry);
                    deltaWriter.WriteEnd();
                    deltaWriter.WriteDeltaDeletedEntry(deletedEntry);
                    deltaWriter.WriteEnd();
                }
            }
            else if (deltaToken == "containment")
            {
                originalUri = new Uri(ServiceConstants.ServiceBaseUri, "Accounts(103)/MyPaymentInstruments?$expand=BillingStatements");
                using (var messageWriter = this.CreateMessageWriter(responseMessage))
                {
                    var accountsSet = this.DataSource.Model.FindDeclaredEntitySet("Accounts");
                    var accountType = accountsSet.EntityType();
                    var myPisNav    = accountType.FindProperty("MyPaymentInstruments") as IEdmNavigationProperty;
                    var piSet       = accountsSet.FindNavigationTarget(myPisNav);
                    var piType      = piSet.EntityType();
                    ODataDeltaWriter deltaWriter = messageWriter.CreateODataDeltaWriter(piSet as IEdmContainedEntitySet, piType);

                    var deltaFeed  = new ODataDeltaFeed();
                    var deltaEntry = new ODataEntry
                    {
                        Id         = new Uri(ServiceConstants.ServiceBaseUri, "Accounts(103)/MyPaymentInstruments(103901)"),
                        Properties = new[] { new ODataProperty {
                                                 Name = "FriendlyName", Value = "GGGG"
                                             } }
                    };

                    var deletedEntry = new ODataDeltaDeletedEntry(
                        new Uri(ServiceConstants.ServiceBaseUri, "Accounts(103)/MyPaymentInstruments(103901)/BillingStatements(103901001)").AbsoluteUri,
                        DeltaDeletedEntryReason.Deleted);
                    deletedEntry.SetSerializationInfo(new ODataDeltaSerializationInfo()
                    {
                        NavigationSourceName = "Accounts(103)/MyPaymentInstruments(103901)/BillingStatements"
                    });

                    var deletedLink = new ODataDeltaDeletedLink(
                        new Uri(ServiceConstants.ServiceBaseUri, "Accounts(103)/MyPaymentInstruments(103901)"),
                        new Uri(ServiceConstants.ServiceBaseUri, "Accounts(103)/MyPaymentInstruments(103901)/BillingStatements(103901001)"),
                        "BillingStatements");

                    var navigationEntry = new ODataEntry
                    {
                        Id         = new Uri(ServiceConstants.ServiceBaseUri, "Accounts(103)/MyPaymentInstruments(103901)/BillingStatements(103901005)"),
                        TypeName   = "Microsoft.Test.OData.Services.ODataWCFService.Statement",
                        Properties = new[]
                        {
                            new ODataProperty {
                                Name = "TransactionType", Value = "OnlinePurchase"
                            },
                            new ODataProperty {
                                Name = "TransactionDescription", Value = "unknown purchase"
                            },
                            new ODataProperty {
                                Name = "Amount", Value = 32.1
                            }
                        }
                    };
                    navigationEntry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo
                    {
                        NavigationSourceEntityTypeName = "Microsoft.Test.OData.Services.ODataWCFService.Statement",
                        NavigationSourceKind           = EdmNavigationSourceKind.ContainedEntitySet,
                        NavigationSourceName           = "Accounts(103)/MyPaymentInstruments(103901)/BillingStatements"
                    });

                    var addedLink = new ODataDeltaLink(
                        new Uri(ServiceConstants.ServiceBaseUri, "Accounts(103)/MyPaymentInstruments(103901)"),
                        new Uri(ServiceConstants.ServiceBaseUri, "Accounts(103)/MyPaymentInstruments(103901)/BillingStatements(103901005)"),
                        "BillingStatements");

                    deltaWriter.WriteStart(deltaFeed);
                    deltaWriter.WriteStart(deltaEntry);
                    deltaWriter.WriteEnd();
                    deltaWriter.WriteDeltaDeletedEntry(deletedEntry);
                    deltaWriter.WriteDeltaDeletedLink(deletedLink);
                    deltaWriter.WriteStart(navigationEntry);
                    deltaWriter.WriteEnd();
                    deltaWriter.WriteDeltaLink(addedLink);
                    deltaWriter.WriteEnd();
                }
            }
            else if (deltaToken == "derived")
            {
                originalUri = new Uri(ServiceConstants.ServiceBaseUri, "People?$expand=Microsoft.Test.OData.Services.ODataWCFService.Customer/Orders");
                using (var messageWriter = this.CreateMessageWriter(responseMessage))
                {
                    var peopleSet  = this.DataSource.Model.FindDeclaredEntitySet("People");
                    var personType = peopleSet.EntityType();
                    ODataDeltaWriter deltaWriter = messageWriter.CreateODataDeltaWriter(peopleSet, personType);

                    var deltaFeed  = new ODataDeltaFeed();
                    var deltaEntry = new ODataEntry
                    {
                        Id         = new Uri(ServiceConstants.ServiceBaseUri, "People(1)"),
                        TypeName   = "Microsoft.Test.OData.Services.ODataWCFService.Customer",
                        Properties = new[]
                        {
                            new ODataProperty {
                                Name = "City", Value = "GGGG"
                            }
                        }
                    };

                    var addedLink = new ODataDeltaLink(
                        new Uri(ServiceConstants.ServiceBaseUri, "People(1)"), new Uri(ServiceConstants.ServiceBaseUri, "Orders(7)"), "Orders");

                    var deletedEntry = new ODataDeltaDeletedEntry(
                        new Uri(ServiceConstants.ServiceBaseUri, "People(2)").AbsoluteUri,
                        DeltaDeletedEntryReason.Changed);

                    var deletedLink = new ODataDeltaDeletedLink(
                        new Uri(ServiceConstants.ServiceBaseUri, "People(1)"),
                        new Uri(ServiceConstants.ServiceBaseUri, "Orders(8)"),
                        "Orders");

                    var navigationEntry = new ODataEntry
                    {
                        Id         = new Uri(ServiceConstants.ServiceBaseUri, "Orders(100)"),
                        TypeName   = "Microsoft.Test.OData.Services.ODataWCFService.Order",
                        Properties = new[]
                        {
                            new ODataProperty {
                                Name = "OrderID", Value = 100
                            },
                            new ODataProperty {
                                Name = "OrderDate", Value = new DateTimeOffset(DateTime.Now)
                            }
                        }
                    };
                    navigationEntry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo
                    {
                        NavigationSourceEntityTypeName = "Microsoft.Test.OData.Services.ODataWCFService.Order",
                        NavigationSourceKind           = EdmNavigationSourceKind.EntitySet,
                        NavigationSourceName           = "Orders"
                    });

                    deltaWriter.WriteStart(deltaFeed);
                    deltaWriter.WriteStart(deltaEntry);
                    deltaWriter.WriteEnd();
                    deltaWriter.WriteDeltaDeletedLink(deletedLink);
                    deltaWriter.WriteDeltaLink(addedLink);
                    deltaWriter.WriteStart(navigationEntry);
                    deltaWriter.WriteEnd();
                    deltaWriter.WriteDeltaDeletedEntry(deletedEntry);
                    deltaWriter.WriteEnd();
                }
            }
            else if (deltaToken == "expanded")
            {
                originalUri = new Uri(ServiceConstants.ServiceBaseUri, "Customers?$expand=Orders");
                using (var messageWriter = this.CreateMessageWriter(responseMessage))
                {
                    var customerSet              = this.DataSource.Model.FindDeclaredEntitySet("Customers");
                    var orderSet                 = this.DataSource.Model.FindDeclaredEntitySet("Orders");
                    var peopleSet                = this.DataSource.Model.FindDeclaredEntitySet("People");
                    var customerType             = customerSet.EntityType();
                    ODataDeltaWriter deltaWriter = messageWriter.CreateODataDeltaWriter(customerSet, customerType);

                    // Delta feed and entry
                    var deltaFeed = new ODataDeltaFeed
                    {
                        DeltaLink = new Uri(ServiceConstants.ServiceBaseUri, "$delta?$token=expanded")
                    };
                    var deltaEntry = new ODataEntry
                    {
                        Id         = new Uri(ServiceConstants.ServiceBaseUri, customerSet.Name + "(1)"),
                        Properties = new[] { new ODataProperty {
                                                 Name = "FirstName", Value = "GGGG"
                                             } }
                    };

                    // Expanded feed
                    var navigationLink = new ODataNavigationLink()
                    {
                        Name         = "Orders",
                        IsCollection = true,
                    };
                    var expandedFeed  = new ODataFeed();
                    var expandedEntry = new ODataEntry
                    {
                        Id         = new Uri(ServiceConstants.ServiceBaseUri, orderSet.Name + "(8)"),
                        Properties = new[]
                        {
                            new ODataProperty {
                                Name = "OrderDate", Value = new DateTimeOffset(2011, 3, 4, 16, 03, 57, TimeSpan.FromHours(-8))
                            },
                            new ODataProperty {
                                Name = "OrderID", Value = 8
                            },
                            new ODataProperty {
                                Name = "OrderShelfLifes", Value = new ODataCollectionValue {
                                    Items = new[] { new TimeSpan(1) }
                                }
                            },
                            new ODataProperty {
                                Name = "ShelfLife", Value = new TimeSpan(1)
                            },
                            new ODataProperty {
                                Name = "ShipDate", Value = new Date(2014, 8, 12)
                            },
                            new ODataProperty {
                                Name = "ShipTime", Value = new TimeOfDay(6, 5, 30, 0)
                            },
                        }
                    };

                    // Expanded entry
                    var navigationLinkSingle = new ODataNavigationLink()
                    {
                        Name         = "Parent",
                        IsCollection = false,
                    };
                    var expandedEntrySingle = new ODataEntry
                    {
                        Id         = new Uri(ServiceConstants.ServiceBaseUri, peopleSet.Name + "(2)"),
                        Properties = new[]
                        {
                            new ODataProperty {
                                Name = "FirstName", Value = "Jill"
                            },
                            new ODataProperty {
                                Name = "LastName", Value = "Jones"
                            },
                            new ODataProperty {
                                Name = "Numbers", Value = new ODataCollectionValue()
                            },
                            new ODataProperty {
                                Name = "Emails", Value = new ODataCollectionValue()
                            },
                            new ODataProperty {
                                Name = "PersonID", Value = 2
                            },
                            new ODataProperty {
                                Name = "Home", Value = GeographyPoint.Create(15.0, 161.8)
                            },
                        }
                    };

                    // Delta feed and entry
                    deltaWriter.WriteStart(deltaFeed);
                    deltaWriter.WriteStart(deltaEntry);

                    // Expanded feed
                    deltaWriter.WriteStart(navigationLink);
                    deltaWriter.WriteStart(expandedFeed);
                    deltaWriter.WriteStart(expandedEntry);
                    deltaWriter.WriteEnd();
                    deltaWriter.WriteEnd();
                    deltaWriter.WriteEnd();

                    // Expanded entry
                    deltaWriter.WriteStart(navigationLinkSingle);
                    deltaWriter.WriteStart(expandedEntrySingle);
                    deltaWriter.WriteEnd();
                    deltaWriter.WriteEnd();

                    // Delta feed and entry
                    deltaWriter.WriteEnd();
                    deltaWriter.WriteEnd();
                }
            }
            else if (deltaToken == "projection")
            {
                originalUri = new Uri(ServiceConstants.ServiceBaseUri, "Customers?$select=PersonID,FirstName,LastName&$expand=Orders($select=OrderID,OrderDate)");
                using (var messageWriter = this.CreateMessageWriter(responseMessage))
                {
                    var entitySet  = this.DataSource.Model.FindDeclaredEntitySet("Customers");
                    var entityType = entitySet.EntityType();
                    ODataDeltaWriter deltaWriter = messageWriter.CreateODataDeltaWriter(entitySet, entityType);

                    var deltaFeed   = new ODataDeltaFeed();
                    var deltaEntry1 = new ODataEntry
                    {
                        Properties = new[]
                        {
                            new ODataProperty {
                                Name = "PersonID", Value = 1
                            },
                            new ODataProperty {
                                Name = "FirstName", Value = "FFFF"
                            },
                            new ODataProperty {
                                Name = "LastName", Value = "LLLL"
                            },
                            new ODataProperty {
                                Name = "City", Value = "Beijing"
                            }
                        }
                    };
                    var deletedLink = new ODataDeltaDeletedLink(
                        new Uri(ServiceConstants.ServiceBaseUri, entitySet.Name + "(1)"), new Uri(ServiceConstants.ServiceBaseUri, "Orders(8)"), "Orders");
                    var addedLink = new ODataDeltaLink(
                        new Uri(ServiceConstants.ServiceBaseUri, entitySet.Name + "(1)"), new Uri(ServiceConstants.ServiceBaseUri, "Orders(7)"), "Orders");
                    var navigationEntry = new ODataEntry
                    {
                        Id         = new Uri(ServiceConstants.ServiceBaseUri, "Orders(100)"),
                        TypeName   = "Microsoft.Test.OData.Services.ODataWCFService.Order",
                        Properties = new[]
                        {
                            new ODataProperty {
                                Name = "OrderID", Value = 100
                            },
                            new ODataProperty {
                                Name = "OrderDate", Value = new DateTimeOffset(DateTime.Now)
                            }
                        }
                    };
                    navigationEntry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo
                    {
                        NavigationSourceEntityTypeName = "Microsoft.Test.OData.Services.ODataWCFService.Order",
                        NavigationSourceKind           = EdmNavigationSourceKind.EntitySet,
                        NavigationSourceName           = "Orders"
                    });

                    var deletedOrderEntry = new ODataDeltaDeletedEntry(
                        new Uri(ServiceConstants.ServiceBaseUri, "Orders(20)").AbsoluteUri, DeltaDeletedEntryReason.Deleted);
                    deletedOrderEntry.SetSerializationInfo(new ODataDeltaSerializationInfo()
                    {
                        NavigationSourceName = "Orders"
                    });

                    var deltaEntry2 = new ODataEntry
                    {
                        Properties = new[]
                        {
                            new ODataProperty {
                                Name = "PersonID", Value = 2
                            },
                            new ODataProperty {
                                Name = "FirstName", Value = "AAAA"
                            },
                        }
                    };

                    deltaWriter.WriteStart(deltaFeed);
                    deltaWriter.WriteStart(deltaEntry1);
                    deltaWriter.WriteEnd();
                    deltaWriter.WriteDeltaDeletedLink(deletedLink);
                    deltaWriter.WriteDeltaLink(addedLink);
                    deltaWriter.WriteStart(navigationEntry);
                    deltaWriter.WriteEnd();
                    deltaWriter.WriteDeltaDeletedEntry(deletedOrderEntry);
                    deltaWriter.WriteStart(deltaEntry2);
                    deltaWriter.WriteEnd();
                    deltaWriter.WriteEnd();
                }
            }
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            // Useful tool for working with search service: https://azsearch.azurewebsites.net/

            string searchServiceName = "ebornorth";
            string indexname         = "hotels";
            string adminApiKey       = "AF04406350DA2FA54BD24674A1F8B411";
            string queryApiKey       = "CEA041884F40DAC1F9B0D457067C9C7D";

            #region Create Schema
            Console.WriteLine("Defining the schema.....");

            SearchServiceClient serviceClient = new SearchServiceClient(searchServiceName, new SearchCredentials(adminApiKey));

            var definition = new Index()
            {
                Name   = indexname,
                Fields = new[]
                {   // Every entry need a unique ID, just like an primary key. The IsKey=true denotes this.
                    new Field("hotelId", DataType.String)
                    {
                        IsKey = true, IsFilterable = true
                    },
                    new Field("baseRate", DataType.Double)
                    {
                        IsFilterable = true, IsSortable = true, IsFacetable = true
                    },
                    new Field("description", DataType.String)
                    {
                        IsSearchable = true
                    },
                    //new Field("description_fr", AnalyzerName.FrLucene), // needed for multi-language support
                    new Field("hotelName", DataType.String)
                    {
                        IsSearchable = true, IsFilterable = true, IsSortable = true
                    },
                    new Field("category", DataType.String)
                    {
                        IsSearchable = true, IsFilterable = true, IsSortable = true, IsFacetable = true
                    },
                    new Field("tags", DataType.Collection(DataType.String))
                    {
                        IsSearchable = true, IsFilterable = true, IsFacetable = true
                    },
                    new Field("parkingIncluded", DataType.Boolean)
                    {
                        IsFilterable = true, IsFacetable = true
                    },
                    new Field("smokingAllowed", DataType.Boolean)
                    {
                        IsFilterable = true, IsFacetable = true
                    },
                    new Field("lastRenovationDate", DataType.DateTimeOffset)
                    {
                        IsFilterable = true, IsSortable = true, IsFacetable = true
                    },
                    new Field("rating", DataType.Int32)
                    {
                        IsFilterable = true, IsSortable = true, IsFacetable = true
                    },
                    new Field("location", DataType.GeographyPoint)
                    {
                        IsFilterable = true, IsSortable = true
                    }
                }
            };

            // Now create the index.
            //serviceClient.Indexes.Create(definition);

            #endregion

            #region Upload data
            Console.WriteLine("Populating the index....");

            SearchIndexClient indexClient = serviceClient.Indexes.GetClient("hotels");

            var actions = new IndexAction <Hotel>[]
            {
                IndexAction.Upload(
                    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)
                }),
                IndexAction.Upload(
                    new Hotel()
                {
                    HotelId     = "2",
                    BaseRate    = 79.99,
                    Description = "Cheapest hotel in town",
                    //DescriptionFr = "Hôtel le moins cher en ville",
                    HotelName          = "Roach Motel",
                    Category           = "Budget",
                    Tags               = new[] { "motel", "budget" },
                    ParkingIncluded    = true,
                    SmokingAllowed     = true,
                    LastRenovationDate = new DateTimeOffset(1982, 4, 28, 0, 0, 0, TimeSpan.Zero),
                    Rating             = 1,
                    Location           = GeographyPoint.Create(49.678581, -122.131577)
                }),
                IndexAction.MergeOrUpload(
                    new Hotel()
                {
                    HotelId     = "3",
                    BaseRate    = 129.99,
                    Description = "Close to town hall and the river"
                }),
                IndexAction.Delete(new Hotel()
                {
                    HotelId = "6"
                })
            };

            var batch = IndexBatch.New(actions);

            try
            {
                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)));
            }

            Console.WriteLine("Waiting for documents to be indexed...\n");
            Thread.Sleep(2000);

            #endregion

            #region Perform a query

            SearchIndexClient indexqueryClient = new SearchIndexClient(searchServiceName, indexname, new SearchCredentials(queryApiKey));

            //Perform a query.
            // See https://azure.microsoft.com/en-gb/documentation/articles/search-query-dotnet/ for more examples


            Console.Write("Search the entire index, order by a specific field (lastRenovationDate) ");
            Console.Write("in descending order, take the top two results, and show only hotelName and ");
            Console.WriteLine("lastRenovationDate:\n");

            SearchParameters             parameters;
            DocumentSearchResult <Hotel> results;

            parameters =
                new SearchParameters()
            {
                OrderBy = new[] { "lastRenovationDate desc" },
                Select  = new[] { "hotelName", "lastRenovationDate" },
                Top     = 2
            };

            results = indexClient.Documents.Search <Hotel>("*", parameters);

            WriteDocuments(results);


            #endregion

            Console.ReadKey();
        }
Ejemplo n.º 22
0
        public void CanIndexDynamicDocuments()
        {
            Run(() =>
            {
                SearchIndexClient client = Data.GetSearchIndexClient();

                var batch = IndexBatch.New(new[]
                {
                    IndexAction.Upload(
                        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", 5 },
                        { "location", GeographyPoint.Create(47.678581, -122.131577) }
                    }),
                    IndexAction.Upload(
                        new Document()
                    {
                        { "hotelId", "2" },
                        { "baseRate", 79.99 },
                        { "description", "Cheapest hotel in town" },
                        { "descriptionFr", "Hôtel le moins cher en ville" },
                        { "hotelName", "Roach Motel" },
                        { "category", "Budget" },
                        { "tags", new[] { "motel", "budget" } },
                        { "parkingIncluded", true },
                        { "smokingAllowed", true },
                        { "lastRenovationDate", new DateTimeOffset(1982, 4, 28, 0, 0, 0, TimeSpan.Zero) },      //aka.ms/sre-codescan/disable
                        { "rating", 1 },
                        { "location", GeographyPoint.Create(49.678581, -122.131577) }
                    }),
                    IndexAction.Merge(
                        new Document()
                    {
                        { "hotelId", "3" },
                        { "baseRate", 279.99 },
                        { "description", "Surprisingly expensive" },
                        { "lastRenovationDate", null }
                    }),
                    IndexAction.Delete(keyName: "hotelId", keyValue: "4"),
                    IndexAction.MergeOrUpload(
                        new Document()
                    {
                        { "hotelId", "5" },
                        { "baseRate", Double.NaN },
                        { "hotelName", null },
                        { "tags", new string[0] }
                    })
                });

                IndexBatchException e = Assert.Throws <IndexBatchException>(() => client.Documents.Index(batch));
                AssertIsPartialFailure(e, "3");

                Assert.Equal(5, e.IndexingResults.Count);

                AssertIndexActionSucceeded("1", e.IndexingResults[0], 201);
                AssertIndexActionSucceeded("2", e.IndexingResults[1], 201);
                AssertIndexActionFailed("3", e.IndexingResults[2], "Document not found.", 404);
                AssertIndexActionSucceeded("4", e.IndexingResults[3], 200);
                AssertIndexActionSucceeded("5", e.IndexingResults[4], 201);

                SearchTestUtilities.WaitForIndexing();

                Assert.Equal(3L, client.Documents.Count());
            });
        }
Ejemplo n.º 23
0
 public bool Equals(GeographyPoint other)
 {
     return(this.BaseEquals(other) ?? this.Latitude == other.Latitude && this.Longitude == other.Longitude && this.Z == other.Z && this.M == other.M);
 }
Ejemplo n.º 24
0
 public bool Equals(GeographyPoint other)
 {
     return this.BaseEquals(other) ?? this.Latitude == other.Latitude && this.Longitude == other.Longitude && this.Z == other.Z && this.M == other.M;
 }
        /// <inheritdoc/>
        public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.Null)
            {
                return(null);
            }

            string type      = default;
            double?longitude = default;
            double?latitude  = default;

            reader.Expect(JsonTokenType.StartObject);
            while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)
            {
                reader.Expect(JsonTokenType.PropertyName);
                string propertyName = reader.GetString();

                reader.Read();
                if (string.Equals(TypePropertyName, propertyName, StringComparison.Ordinal))
                {
                    reader.Expect(JsonTokenType.String);
                    type = reader.GetString();
                }
                else if (string.Equals(CoordinatesPropertyName, propertyName, StringComparison.Ordinal))
                {
                    reader.Expect(JsonTokenType.StartArray);

                    // Longitude
                    reader.Read();
                    reader.Expect(JsonTokenType.Number);
                    longitude = reader.GetDouble();

                    // Latitude
                    reader.Read();
                    reader.Expect(JsonTokenType.Number);
                    latitude = reader.GetDouble();

                    // Skip the rest.
                    do
                    {
                        reader.Read();
                    } while (reader.TokenType != JsonTokenType.EndArray);
                }
                else
                {
                    reader.Skip();
                }
            }

            if (!string.Equals(PointTypeName, type, StringComparison.Ordinal))
            {
                throw new JsonException($"Deserialization of {nameof(GeographyPoint)} failed. Expected geographic type: '{PointTypeName}'.");
            }

            if (!longitude.HasValue || !latitude.HasValue)
            {
                throw new JsonException($"Deserialization of {nameof(GeographyPoint)} failed. Expected both longitude and latitude.");
            }

            return(GeographyPoint.Create(latitude.Value, longitude.Value));
        }