Exemplo n.º 1
0
        public void LoadFromJsonToAzureSearch()
        {
            using (var azureSearchHelper = new AzureSearchHelper(LamaConfiguration.Current(), NullLogger.Instance))
            {
                var createIndexServiceResult = AsyncHelper.RunSync(() => azureSearchHelper.CreateSearchIndex <Listing>(Index));

                if (!createIndexServiceResult.IsStatusOk())
                {
                    throw createIndexServiceResult.PotentialException.GetException();
                }

                var countServiceResult = AsyncHelper.RunSync(() => azureSearchHelper.CountDocuments <Listing>(new SearchParameters(), indexName: Index));

                if (!countServiceResult.IsStatusOk() || countServiceResult.Data != ExpectedDataCount)
                {
                    var baseDirectory  = AppContext.BaseDirectory;
                    var mockedDataPath = Path.Combine(baseDirectory, "App_Data\\listings-mocked.json");

                    var searchParameters = new SearchParameters()
                    {
                        Select = new List <string>()
                        {
                            "id"
                        },
                        Top = 1000
                    };

                    if (countServiceResult.Data > 0)
                    {
                        var allDocuments = AsyncHelper.RunSync(() => azureSearchHelper.SearchDocuments <Listing>(searchParameters, indexName: Index));

                        AsyncHelper.RunSync(() => azureSearchHelper
                                            .DeleteDocumentsInIndex(allDocuments.Data.Results.Select(q => new Listing {
                            Id = q.Document.Id
                        }), Index));

                        azureSearchHelper.WaitForSearchOperationCompletion <Listing>(0, Index);
                    }

                    var listings = JsonConvert.DeserializeObject <List <Listing> >(File.ReadAllText(mockedDataPath), new JsonSerializerSettings
                    {
                        Converters = new List <JsonConverter> {
                            new GeographyPointJsonConverter()
                        }
                    });

                    var uploadOrMergeListingsServiceResult = AsyncHelper.RunSync(() => azureSearchHelper.ChangeDocumentsInIndex(listings, Index));

                    if (!uploadOrMergeListingsServiceResult.IsStatusOk())
                    {
                        throw uploadOrMergeListingsServiceResult.PotentialException.GetException();
                    }

                    azureSearchHelper.WaitForSearchOperationCompletion <Listing>(listings.Count, Index);
                }
            }
        }