private static void AddDocuments()
        {
            var credential = new AzureKeyCredential(adminKey);
            var client     = new SearchClient(endpoint, indexName, credential);
            var action1    = IndexDocumentsAction.Upload(new Ninja
            {
                Id   = Guid.NewGuid().ToString(),
                Name = "Naruto Uzumaki"
            });
            var action2 = IndexDocumentsAction.Upload(new Ninja
            {
                Id   = Guid.NewGuid().ToString(),
                Name = "Sasuke Uchiha"
            });
            var batch = IndexDocumentsBatch.Create(action1, action2);

            try
            {
                IndexDocumentsResult result = client.IndexDocuments(batch);
            }
            catch (Exception)
            {
                Console.WriteLine("Failed to index some of the documents: {0}");
            }
        }
Exemple #2
0
        static async Task Main(string[] args)
        {
            var reviewText = "The quality of the pictures are good, but the body is not durable";
            var productId  = "1"; // ID of the product reviewed
            var reviewId   = "1"; // ID of the review used as the search document ID
            var indexName  = "sample-index";

            // Cognitive Search credentials
            var searchKey      = Environment.GetEnvironmentVariable("COGNITIVE_SEARCH_KEY");
            var searchEndpoint = Environment.GetEnvironmentVariable("COGNITIVE_SEARCH_ENDPOINT");
            Uri searchUri      = new Uri(searchEndpoint);
            AzureKeyCredential searchCredential = new AzureKeyCredential(searchKey);

            // Initialize Search Index client
            var searchIndexClient = new SearchIndexClient(searchUri, searchCredential);

            // Create Index
            await CreateIndex(indexName, searchIndexClient);

            // Initialize Search client
            var searchClient = new SearchClient(searchUri, indexName, searchCredential);

            // TA credentials
            var textAnalyticsKey         = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_KEY");
            var textAnalyticsEndpoint    = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
            var textAnalyticsCredentials = new AzureKeyCredential(textAnalyticsKey);
            var textAnalyticsUri         = new Uri(textAnalyticsEndpoint);

            // Initialize TA client
            var textAnalyticsClient = new TextAnalyticsClient(textAnalyticsUri, textAnalyticsCredentials);

            // Enable opinion mining
            var options = new AnalyzeSentimentOptions()
            {
                IncludeOpinionMining = true
            };

            // Call TA analyze sentiment api
            var sentimentResponse = await textAnalyticsClient.AnalyzeSentimentAsync(reviewText, language : "en", options : options);

            // Map to review search document
            Review review = CreateReviewDocument(productId, reviewId, sentimentResponse);

            // Upload document
            var batch = IndexDocumentsBatch.Create(IndexDocumentsAction.Upload(review));

            try
            {
                IndexDocumentsResult result = await searchClient.IndexDocumentsAsync(batch);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemple #3
0
        static async Task Main(string[] args)
        {
            string environmentName  = Environment.GetEnvironmentVariable("ENVIRONMENT");
            string currentDirectory = Directory.GetCurrentDirectory();

            // Setup console application to read settings from appsettings.json
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
                                                         .SetBasePath(currentDirectory)
                                                         .AddJsonFile("appsettings.json", true, true)
                                                         .AddJsonFile($"appsettings.{environmentName}.json", true, true);

            IConfigurationRoot configuration = configurationBuilder.Build();

            // Configure default dependency injection container
            ServiceProvider serviceProvider = new ServiceCollection()
                                              .AddLogging(configure => configure.AddConsole())
                                              .AddSingleton <IConfigurationRoot>(configuration)
                                              .BuildServiceProvider();

            ILogger logger = serviceProvider.GetService <ILogger <Program> >();

            // Load JSON file of documents to upload
            logger.LogInformation("Reading JSON file of documents to load...");
            Documents documents = null;

            try
            {
                string jsonDocuments = await File.ReadAllTextAsync(Path.Combine(currentDirectory, "json_test_index.json"));

                documents = JsonConvert.DeserializeObject <Documents>(jsonDocuments);
                logger.LogInformation("Successfully read JSON file of documents to load.");
            }
            catch (Exception ex)
            {
                logger.LogError($"Failed to read JSON file of documents. Exception message is {ex.Message}");
            }

            if (documents != null)
            {
                // Update the Azure Search Index
                logger.LogInformation("Loading documents into search index...");
                try
                {
                    SearchClient         searchClient = new SearchClient(new Uri(configuration["AZURE_SEARCH_URI"]), configuration["AZURE_SEARCH_INDEX"], new AzureKeyCredential(configuration["AZURE_SEARCH_KEY"]));
                    IndexDocumentsResult indexResults = await searchClient.MergeOrUploadDocumentsAsync <Document>(documents.value);

                    logger.LogInformation("Documents successfully loaded into search index. Run complete.");
                }
                catch (Exception ex)
                {
                    logger.LogError($"Failed to load documents into search index. Exception message is {ex.Message}");
                }
            }
        }
        public async Task UploadDocument(AlbumInfoSearchObject document)
        {
            IndexDocumentsBatch <AlbumInfoSearchObject> batch = IndexDocumentsBatch.Create(IndexDocumentsAction.MergeOrUpload(document));

            try
            {
                IndexDocumentsResult result = await searchClient.IndexDocumentsAsync(batch);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemple #5
0
        private static void UploadDocuments(SearchClient searchClient)
        {
            IndexDocumentsBatch <Hotel> batch = IndexDocumentsBatch.Create(
                IndexDocumentsAction.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)
            }),
                IndexDocumentsAction.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)
            }));

            try
            {
                IndexDocumentsResult result = searchClient.IndexDocuments(batch);
            }
            catch (Exception)
            {
                // 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}");
            }

            Console.WriteLine("Waiting for documents to be indexed...\n");
            Thread.Sleep(2000);
        }
        public async Task <int> BuildIndexAsync(IEnumerable <SearchLocationIndex> searchLocations)
        {
            logger.LogInformation($"Starting to build index for {searchLocations.Count()}");
            try
            {
                var searchIndexClient = new SearchIndexClient(azureSearchIndexConfig.EndpointUri, GetAzureKeyCredential());
                var searchClient      = new SearchClient(azureSearchIndexConfig.EndpointUri, azureSearchIndexConfig.LocationSearchIndex, GetAzureKeyCredential());
                var fieldBuilder      = new FieldBuilder();
                var searchFields      = fieldBuilder.Build(typeof(SearchLocationIndex));
                var definition        = new SearchIndex(azureSearchIndexConfig.LocationSearchIndex, searchFields);
                var suggester         = new SearchSuggester(suggestorName, new[] { nameof(SearchLocationIndex.LocationName) });
                definition.Suggesters.Add(suggester);

                logger.LogInformation("created search objects and creating index");
                await searchIndexClient.CreateOrUpdateIndexAsync(definition).ConfigureAwait(false);

                logger.LogInformation("Created search index and uploading documents");

                var batch = IndexDocumentsBatch.Upload(searchLocations);
                IndexDocumentsResult result = await searchClient.IndexDocumentsAsync(batch).ConfigureAwait(false);

                var failedRecords = result.Results.Where(r => !r.Succeeded);
                if (failedRecords.Any())
                {
                    var sampleFailedRecord = failedRecords.FirstOrDefault();
                    var sampleMessage      = $"{failedRecords.Count()} have failed to upload to the index, sample failed record  message {sampleFailedRecord.ErrorMessage}, Status = {sampleFailedRecord.Status}";
                    logger.LogError(sampleMessage);
                    throw new DfcIndexUploadException("sampleMessage");
                }

                logger.LogInformation($"Created search index and uploaded {result.Results.Count} documents");

                return(result.Results.Count);
            }
            catch (Exception ex)
            {
                logger.LogError("Building index had an error", ex);
                throw;
            }
        }
        private static void IndexDocuments(string indexName, List <string> groups)
        {
            IndexDocumentsBatch <SecuredFiles> batch = IndexDocumentsBatch.Create(
                IndexDocumentsAction.Upload(
                    new SecuredFiles()
            {
                FileId   = "1",
                Name     = "secured_file_a",
                GroupIds = new[] { groups[0] }
            }),
                IndexDocumentsAction.Upload(
                    new SecuredFiles()
            {
                FileId   = "2",
                Name     = "secured_file_b",
                GroupIds = new[] { groups[0] }
            }),
                IndexDocumentsAction.Upload(
                    new SecuredFiles()
            {
                FileId   = "3",
                Name     = "secured_file_c",
                GroupIds = new[] { groups[1] }
            }));

            try
            {
                IndexDocumentsResult result = searchClient.IndexDocuments(batch);
            }
            catch (Exception)
            {
                // 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}");
            }

            Console.WriteLine("Waiting for documents to be indexed...\n");
            Thread.Sleep(2000);
        }
        private static void MergeOrUploadDocuments(SearchClient searchClient)
        {
            IndexDocumentsBatch <Hotel> batch = IndexDocumentsBatch.Create(
                IndexDocumentsAction.MergeOrUpload(
                    new Hotel()
            {
                HotelId = "4",
                Rating  = 1,
                Tags    = new[] { "concierge", "view", "24-hour front desk service" },
            })
                );

            try
            {
                IndexDocumentsResult result = searchClient.IndexDocuments(batch);
            }
            catch (Exception e)
            {
                // If for some reason any documents are dropped during indexing, you can compensate by delaying and
                // retrying. This simple demo just logs the failed document keys and continues.
                Console.WriteLine($"Failed to index some of the documents: {e}");
            }
        }
        private static async Task <IndexDocumentsResult> ExponentialBackoffAsync(SearchClient searchClient, List <Hotel> hotels, int id)
        {
            // Create batch of documents for indexing
            var batch = IndexDocumentsBatch.Upload(hotels);

            // Create an object to hold the result
            IndexDocumentsResult result = null;

            // Define parameters for exponential backoff
            int      attempts         = 0;
            TimeSpan delay            = delay = TimeSpan.FromSeconds(2);
            int      maxRetryAttempts = 5;

            // Implement exponential backoff
            do
            {
                try
                {
                    attempts++;
                    result = await searchClient.IndexDocumentsAsync(batch).ConfigureAwait(false);

                    var failedDocuments = result.Results.Where(r => r.Succeeded != true).ToList();

                    // handle partial failure
                    if (failedDocuments.Count > 0)
                    {
                        if (attempts == maxRetryAttempts)
                        {
                            Console.WriteLine("[MAX RETRIES HIT] - Giving up on the batch starting at {0}", id);
                            break;
                        }
                        else
                        {
                            Console.WriteLine("[Batch starting at doc {0} had partial failure]", id);
                            //Console.WriteLine("[Attempt: {0} of {1} Failed]", attempts, maxRetryAttempts);
                            Console.WriteLine("[Retrying {0} failed documents] \n", failedDocuments.Count);

                            // creating a batch of failed documents to retry
                            var failedDocumentKeys = failedDocuments.Select(doc => doc.Key).ToList();
                            hotels = hotels.Where(h => failedDocumentKeys.Contains(h.HotelId)).ToList();
                            batch  = IndexDocumentsBatch.Upload(hotels);

                            Task.Delay(delay).Wait();
                            delay = delay * 2;
                            continue;
                        }
                    }


                    return(result);
                }
                catch (RequestFailedException ex)
                {
                    Console.WriteLine("[Batch starting at doc {0} failed]", id);
                    //Console.WriteLine("[Attempt: {0} of {1} Failed] - Error: {2} \n", attempts, maxRetryAttempts, ex.Message);
                    Console.WriteLine("[Retrying entire batch] \n");

                    if (attempts == maxRetryAttempts)
                    {
                        Console.WriteLine("[MAX RETRIES HIT] - Giving up on the batch starting at {0}", id);
                        break;
                    }

                    Task.Delay(delay).Wait();
                    delay = delay * 2;
                }
            } while (true);

            return(null);
        }
        private static void UploadDocuments(SearchClient searchClient)
        {
            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,
                //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"
                //}
            }),
                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"
                //}
            }),
                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"
                //}
            })
                );

            try
            {
                IndexDocumentsResult result = searchClient.IndexDocuments(batch);
            }
            catch (Exception e)
            {
                // If for some reason any documents are dropped during indexing, you can compensate by delaying and
                // retrying. This simple demo just logs the failed document keys and continues.
                Console.WriteLine($"Failed to index some of the documents: {e}");
            }
        }
        /// <summary>
        /// Migrate users with random password
        /// </summary>
        /// <returns></returns>
        static async Task MigrateUsersWithRandomPasswordAsync()
        {
            string appDirecotyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            string dataFilePath    = Path.Combine(appDirecotyPath, Program.MigrationFile);

            // Check file existence
            if (!File.Exists(dataFilePath))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"File '{dataFilePath}' not found");
                Console.ResetColor();
                return;
            }

            // Read the data file and convert to object
            LocalAccountsModel users = LocalAccountsModel.Parse(File.ReadAllText(dataFilePath));

            // Create B2C graph client object
            B2CGraphClient b2CGraphClient = new B2CGraphClient(Program.Tenant, Program.ClientId, Program.ClientSecret);

            // Create Search client object
            SearchClient searchClient = new SearchClient(new Uri(ConfigurationManager.AppSettings["AZURE_SEARCH_URI"]), ConfigurationManager.AppSettings["AZURE_SEARCH_INDEX"], new AzureKeyCredential(ConfigurationManager.AppSettings["AZURE_SEARCH_KEY"]));

            int successes = 0;
            int fails     = 0;

            foreach (var item in users.Users)
            {
                GraphAccountModel newUser = await b2CGraphClient.CreateAccount(users.userType,
                                                                               item.signInName,
                                                                               item.issuer,
                                                                               item.issuerUserId,
                                                                               item.email,
                                                                               item.password,
                                                                               item.displayName,
                                                                               item.firstName,
                                                                               item.lastName,
                                                                               item.extension_Organization,
                                                                               item.extension_UserRole,
                                                                               true);

                if (newUser != null)
                {
                    // Update the Azure Search Index
                    string signInName = string.Empty;
                    string issuer     = string.Empty;
                    string issuerId   = string.Empty;
                    string email      = string.Empty;
                    if (newUser.signInNames != null && newUser.signInNames.Count > 0)
                    {
                        signInName = newUser.signInNames[0].value;
                    }
                    if (newUser.userIdentities != null && newUser.userIdentities.Count > 0)
                    {
                        issuer   = newUser.userIdentities[0].issuer;
                        issuerId = newUser.userIdentities[0].issuerUserId;
                    }
                    if (newUser.otherMails != null && newUser.otherMails.Count > 0)
                    {
                        email = newUser.otherMails[0];
                    }
                    Document document = new Document()
                    {
                        id           = newUser.objectId,
                        signInName   = signInName,
                        issuer       = issuer,
                        issuerId     = issuerId,
                        email        = email,
                        displayName  = newUser.displayName,
                        firstName    = newUser.givenName,
                        lastName     = newUser.surname,
                        organization = newUser.extension_Organization,
                        userRole     = newUser.extension_UserRole
                    };
                    List <Document> documents = new List <Document>()
                    {
                        document
                    };
                    IndexDocumentsResult indexResults = await searchClient.MergeOrUploadDocumentsAsync(documents);

                    successes += 1;
                }
                else
                {
                    fails += 1;
                }
            }

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"\r\nUsers migration report:\r\n\tSuccesses: {successes}\r\n\tFails: {fails} ");
            Console.ResetColor();
        }
Exemple #12
0
        public async Task <ActionResult> UploadBlobPost(IFormFile uploadedFile)
        {
            Random random = new Random();

            string[] categories    = { "Technical", "Certification", "Leisure" };
            string[] subCategories = { "ASP.Net", "Azure", "Science Fiction" };

            if (uploadedFile.Length > 0)
            {
                string connectionString = _configuration.GetValue <string>("AZURE_STORAGE_CONNECTION_STRING");

                // Create a BlobServiceClient object which will be used to create a container client
                BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

                // Create a unique name for the container
                string containerName = "fileuploads";

                // Create the container and return a container client object
                BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);

                // Get the file name
                string fileName = Path.GetFileName(uploadedFile.FileName);

                // Get a reference to a blob
                BlobClient blobClient = containerClient.GetBlobClient(fileName);

                // Generate some metadata
                Dictionary <string, string> metadata = new Dictionary <string, string>();
                string category    = categories[random.Next(0, 2)];
                string subCategory = subCategories[random.Next(0, 2)];
                metadata.Add("Category", category);
                metadata.Add("SubCategory", subCategory);
                BlobUploadOptions blobUploadOptions = new BlobUploadOptions()
                {
                    Metadata = metadata
                };

                // Open the file and upload its data
                await blobClient.UploadAsync(uploadedFile.OpenReadStream(), blobUploadOptions);

                // Retrieve the blob's properties
                BlobProperties blobProperties = await blobClient.GetPropertiesAsync();

                // Update the Azure Search Index
                SearchClient searchClient = new SearchClient(new Uri(_configuration.GetValue <string>("AZURE_SEARCH_URI")), _configuration.GetValue <string>("AZURE_SEARCH_INDEX"), new AzureKeyCredential(_configuration.GetValue <string>("AZURE_SEARCH_KEY")));
                Document     document     = new Document()
                {
                    Category    = category,
                    SubCategory = subCategory,
                    metadata_storage_content_type   = blobProperties.ContentType,
                    metadata_storage_size           = (int)blobProperties.ContentLength,
                    metadata_storage_last_modified  = blobProperties.LastModified,
                    metadata_storage_name           = blobClient.Name,
                    metadata_storage_path           = Convert.ToBase64String(Encoding.UTF8.GetBytes(blobClient.Uri.ToString())),
                    metadata_storage_file_extension = Path.GetExtension(uploadedFile.FileName),
                    metadata_creation_date          = blobProperties.CreatedOn
                };
                List <Document> documents = new List <Document>()
                {
                    document
                };
                IndexDocumentsResult indexResults = await searchClient.MergeOrUploadDocumentsAsync(documents);

                ViewBag.Message = $"File {fileName} uploaded successfully";
            }

            return(View());
        }
        // Upload documents in a single Upload request.
        private static void UploadDocuments(SearchClient searchClient)
        {
            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(40.760586, -73.975403),
                Address            = new Address()
                {
                    StreetAddress = "677 5th Ave",
                    City          = "New York",
                    StateProvince = "NY",
                    PostalCode    = "10022",
                    Country       = "USA"
                },
                Rooms = new Room[]
                {
                    new Room()
                    {
                        Description    = "Budget Room, 1 Queen Bed (Cityside)",
                        DescriptionFr  = "Chambre Économique, 1 grand lit (côté ville)",
                        Type           = "Budget Room",
                        BaseRate       = 96.99,
                        BedOptions     = "1 Queen Bed",
                        SleepsCount    = 2,
                        SmokingAllowed = true,
                        Tags           = new[] { "vcr/dvd" }
                    },
                    new Room()
                    {
                        Description    = "Budget Room, 1 King Bed (Mountain View)",
                        DescriptionFr  = "Chambre Économique, 1 très grand lit (Mountain View)",
                        Type           = "Budget Room",
                        BaseRate       = 80.99,
                        BedOptions     = "1 King Bed",
                        SleepsCount    = 2,
                        SmokingAllowed = true,
                        Tags           = new[] { "vcr/dvd", "jacuzzi tub" }
                    },
                    new Room()
                    {
                        Description    = "Deluxe Room, 2 Double Beds (City View)",
                        DescriptionFr  = "Chambre Deluxe, 2 lits doubles (vue ville)",
                        Type           = "Deluxe Room",
                        BaseRate       = 150.99,
                        BedOptions     = "2 Double Beds",
                        SleepsCount    = 2,
                        SmokingAllowed = false,
                        Tags           = new[] { "suite", "bathroom shower", "coffee maker" }
                    }
                }
            }),
                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,
                Location           = GeographyPoint.Create(27.384417, -82.452843),
                Address            = new Address()
                {
                    StreetAddress = "140 University Town Center Dr",
                    City          = "Sarasota",
                    StateProvince = "FL",
                    PostalCode    = "34243",
                    Country       = "USA"
                },
                Rooms = new Room[]
                {
                    new Room()
                    {
                        Description    = "Suite, 2 Double Beds (Mountain View)",
                        DescriptionFr  = "Suite, 2 lits doubles (vue sur la montagne)",
                        Type           = "Suite",
                        BaseRate       = 250.99,
                        BedOptions     = "2 Double Beds",
                        SleepsCount    = 2,
                        SmokingAllowed = false,
                        Tags           = new[] { "Room Tags" }
                    },
                    new Room()
                    {
                        Description    = "Standard Room, 1 Queen Bed (City View)",
                        DescriptionFr  = "Chambre Standard, 1 grand lit (vue ville)",
                        Type           = "Standard Room",
                        BaseRate       = 121.99,
                        BedOptions     = "1 Queen Bed",
                        SleepsCount    = 2,
                        SmokingAllowed = false,
                        Tags           = new[] { "jacuzzi tub" }
                    },
                    new Room()
                    {
                        Description    = "Budget Room, 1 King Bed (Waterfront View)",
                        DescriptionFr  = "Chambre Économique, 1 très grand lit (vue sur le front de mer)",
                        Type           = "Budget Room",
                        BaseRate       = 88.99,
                        BedOptions     = "1 King Bed",
                        SleepsCount    = 2,
                        SmokingAllowed = false,
                        Tags           = new[] { "suite", "tv", "jacuzzi tub" }
                    }
                }
            }),
                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,
                Location           = GeographyPoint.Create(33.84643, -84.362465),
                Address            = new Address()
                {
                    StreetAddress = "3393 Peachtree Rd",
                    City          = "Atlanta",
                    StateProvince = "GA",
                    PostalCode    = "30326",
                    Country       = "USA"
                },
                Rooms = new Room[]
                {
                    new Room()
                    {
                        Description    = "Standard Room, 2 Queen Beds (Amenities)",
                        DescriptionFr  = "Chambre Standard, 2 grands lits (Services)",
                        Type           = "Standard Room",
                        BaseRate       = 101.99,
                        BedOptions     = "2 Queen Beds",
                        SleepsCount    = 4,
                        SmokingAllowed = true,
                        Tags           = new[] { "vcr/dvd", "vcr/dvd" }
                    },
                    new Room()
                    {
                        Description    = "Standard Room, 2 Double Beds (Waterfront View)",
                        DescriptionFr  = "Chambre Standard, 2 lits doubles (vue sur le front de mer)",
                        Type           = "Standard Room",
                        BaseRate       = 106.99,
                        BedOptions     = "2 Double Beds",
                        SleepsCount    = 2,
                        SmokingAllowed = true,
                        Tags           = new[] { "coffee maker" }
                    },
                    new Room()
                    {
                        Description    = "Deluxe Room, 2 Double Beds (Cityside)",
                        DescriptionFr  = "Chambre Deluxe, 2 lits doubles (Cityside)",
                        Type           = "Budget Room",
                        BaseRate       = 180.99,
                        BedOptions     = "2 Double Beds",
                        SleepsCount    = 2,
                        SmokingAllowed = true,
                        Tags           = new[] { "suite" }
                    }
                }
            }));

            try
            {
                IndexDocumentsResult result = searchClient.IndexDocuments(batch);
            }
            catch (Exception)
            {
                // 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}");
            }

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