public void it_does_not_share_references() { _builder .WithName("name") .WithClass("class"); var field1 = _builder.Build(); var field2 = _builder.Build(); Assert.That(field1, Is.Not.SameAs(field2)); Assert.That(field1.Class, Is.Not.SameAs(field2.Class)); }
public void LoadConfigurableFields() { Fields = new ObservableCollection <IField>(); var serializer = new XmlSerializer(typeof(Page), ""); using (var reader = new StreamReader("Page.xml")) { var page = (Page)serializer.Deserialize(reader); reader.Close(); foreach (var field in page.Fields.Field) { Fields.Add(FieldBuilder.Build(field.id, field.type, field.Mask)); } foreach (var fieldGroup in page.Fields.FieldGroup) { var fg = new Model.FieldGroup(fieldGroup.id); foreach (var field in fieldGroup.Field) { fg.AddField(FieldBuilder.Build(field.id, field.type, field.Mask)); } FieldGroup.AddFieldGroup(fg); } } }
private async Task <SearchIndex> CreateDemoIndexAsync(SearchIndexClient indexClient) { FieldBuilder builder = new FieldBuilder(); var index = new SearchIndex(_indexName) { Fields = builder.Build(typeof(DemoIndex)) }; try { indexClient.GetIndex(index.Name); indexClient.DeleteIndex(index.Name); } catch (RequestFailedException ex) when(ex.Status == 404) { //if the specified index not exist, 404 will be thrown. } try { await indexClient.CreateIndexAsync(index); } catch (RequestFailedException ex) { throw new Exception("Failed to create the index", ex); } return(index); }
public Silanis.ESL.SDK.Field ToSDKField() { if (apiField == null) { return(sdkField); } FieldBuilder fieldBuilder = FieldBuilder.NewField() .OnPage(apiField.Page.Value) .AtPosition(apiField.Left.Value, apiField.Top.Value) .WithSize(apiField.Width.Value, apiField.Height.Value) .WithStyle(new FieldStyleAndSubTypeConverter(apiField.Subtype, apiField.Binding).ToSDKFieldStyle()) .WithName(apiField.Name); if (apiField.Id != null) { fieldBuilder.WithId(apiField.Id); } if (apiField.Extract.Value) { fieldBuilder.WithPositionExtracted(); } if (apiField.Validation != null) { fieldBuilder.WithValidation(new FieldValidatorConverter(apiField.Validation).ToSDKFieldValidator()); } fieldBuilder.WithValue(apiField.Value); return(fieldBuilder.Build()); }
private static SearchIndex CreateDemoIndex(SearchIndexClient indexClient) { FieldBuilder builder = new FieldBuilder(); var index = new SearchIndex("demoindex") { Fields = builder.Build(typeof(DemoIndex)) }; try { indexClient.GetIndex(index.Name); indexClient.DeleteIndex(index.Name); } catch (RequestFailedException ex) when(ex.Status == 404) { //if the specified index not exist, 404 will be thrown. } try { indexClient.CreateIndex(index); } catch (RequestFailedException ex) { Console.WriteLine("Failed to create the index\n Exception message: {0}\n", ex.Message); ExitProgram("Cannot continue without an index"); } return(index); }
private static async Task CreateIndexAsync(string indexName, SearchIndexClient indexClient) { // Create a new search index structure that matches the properties of the Book class. FieldBuilder bulder = new FieldBuilder(); var definition = new SearchIndex(indexName, bulder.Build(typeof(Book))); await indexClient.CreateIndexAsync(definition); }
private static void CreateHotelsIndex(SearchIndexClient indexClient) { FieldBuilder fieldBuilder = new FieldBuilder(); var searchFields = fieldBuilder.Build(typeof(Hotel)); var searchIndex = new SearchIndex("hotels", searchFields); indexClient.CreateOrUpdateIndex(searchIndex); }
private Field NewField(Action <FieldBuilder> setUp = null) { FieldBuilder fieldBuilder = new FieldBuilder(); setUp?.Invoke(fieldBuilder); return(fieldBuilder.Build()); }
private static void CreateIndex(string indexName, SearchIndexClient indexClient) { FieldBuilder fieldBuilder = new FieldBuilder(); var searchFields = fieldBuilder.Build(typeof(Hotel)); var definition = new SearchIndex(indexName, searchFields); indexClient.CreateOrUpdateIndex(definition); }
private static async Task CreateIndex(string indexName, SearchIndexClient adminClient) { FieldBuilder fieldBuilder = new FieldBuilder(); var searchFields = fieldBuilder.Build(typeof(Review)); var definition = new SearchIndex(indexName, searchFields); await adminClient.CreateOrUpdateIndexAsync(definition); }
public static Fields Add(this Fields self, Action <IFieldBuilder> build) { var builder = new FieldBuilder(); build(builder); var field = builder.Build(); self.Add(field); return(self); }
private static async Task CreateIndexAsync(string indexName, SearchIndexClient indexClient) { // Create a new search index structure that matches the properties of the Hotel class. // The Address class is referenced from the Hotel class. The FieldBuilder // will enumerate these to create a complex data structure for the index. FieldBuilder builder = new FieldBuilder(); var definition = new SearchIndex(indexName, builder.Build(typeof(Hotel))); await indexClient.CreateIndexAsync(definition); }
public async Task CreateIndex() { FieldBuilder bulder = new FieldBuilder(); var definition = new SearchIndex(_index, bulder.Build(typeof(PersonCity))); definition.Suggesters.Add(new SearchSuggester( "personSg", new string[] { "Name", "FamilyName", "Info", "CityCountry" } )); await _searchIndexClient.CreateIndexAsync(definition).ConfigureAwait(false); }
private static void CreateHotelsIndexEncryptedUsingCustomerManagedKey(SearchIndexClient indexClient, IConfigurationRoot configuration) { FieldBuilder fieldBuilder = new FieldBuilder(); var searchFields = fieldBuilder.Build(typeof(Hotel)); var definition = new SearchIndex("hotels", searchFields) { EncryptionKey = GetEncryptionKeyFromConfiguration(configuration) }; indexClient.CreateOrUpdateIndex(definition); }
private async Task <SearchClient> CreateOrUpdateIndexAsync <T>(string indexName = null) { indexName = string.IsNullOrEmpty(indexName) ? typeof(T).Name : indexName; var fieldBuilder = new FieldBuilder(); var searchFields = fieldBuilder.Build(typeof(T)); var definition = new SearchIndex(indexName, searchFields); await _searchIndexClient.CreateOrUpdateIndexAsync(definition); return(_searchIndexClient.GetSearchClient(indexName)); }
// Create hotels-quickstart index private static void CreateIndex(string indexName, SearchIndexClient adminClient) { FieldBuilder fieldBuilder = new FieldBuilder(); var searchFields = fieldBuilder.Build(typeof(Hotel)); var definition = new SearchIndex(indexName, searchFields); var suggester = new SearchSuggester("sg", new[] { "HotelName", "Category", "Address/City", "Address/StateProvince" }); definition.Suggesters.Add(suggester); adminClient.CreateOrUpdateIndex(definition); }
public static async Task Create(SearchIndexClient indexClient, SearchIndexName searchIndexName) { var fieldBuilder = new FieldBuilder(); IList <SearchField>?searchFields = fieldBuilder.Build(typeof(IndexableProduct)); var definition = new SearchIndex(searchIndexName.Value, searchFields); var suggester = new SearchSuggester("sg", new[] { nameof(IndexableProduct.Title), nameof(IndexableProduct.Description) }); definition.Suggesters.Add(suggester); var _ = await indexClient.CreateOrUpdateIndexAsync(definition); }
/// <inheritdoc /> protected override Field Bind(FieldContext node, IFieldContainer parent) { var builder = new FieldBuilder() .SetNode(node) .SetParent(parent) .SetBinderProvider(this.binderProvider) .SetFieldId(this.GetFieldId(node)) .SetIsFieldIdImplicit(node.fieldId == null) .SetRawFieldId(node.fieldId?.Text) .SetRequiredness(this.GetFieldRequiredness(node)) .SetName(node.name.Text); return(builder.Build()); }
public async Task <SearchIndex> CreateIndex <TDocument>(string indexName) { try { FieldBuilder fieldBuilder = new FieldBuilder(); var searchFields = fieldBuilder.Build(typeof(TDocument)); var definition = new SearchIndex(indexName, searchFields); return(await _searchIndex.SearchIndexClient.CreateOrUpdateIndexAsync(definition)); } catch (Exception ex) { throw new Exception(ex.Message); } }
private static void CreateIndex(string indexName) { // Create the Azure Search index based on the included schema try { FieldBuilder fieldBuilder = new FieldBuilder(); var searchFields = fieldBuilder.Build(typeof(SecuredFiles)); var definition = new SearchIndex(indexName, searchFields); indexClient.CreateOrUpdateIndex(definition); } catch (Exception ex) { Console.WriteLine("Error creating index: {0}\r\n", ex.Message); throw; } }
/// <summary> /// Crea o actualiza el índice en el azure search. /// </summary> public void CreateOrUpdateIndex() { var indexName = Index; // creación del índice. FieldBuilder fieldBuilder = new FieldBuilder(); var searchFields = fieldBuilder.Build(typeof(EntitySearch)); var definition = new SearchIndex(indexName, searchFields); var cors_option = new CorsOptions(new List <string> { "*" }); cors_option.MaxAgeInSeconds = 300; definition.CorsOptions = cors_option; definition.Suggesters.Add(new SearchSuggester("sug", new List <string> { "sug/value" })); //definition.CorsOptions = this.corsOptions; _searchIndex.CreateOrUpdateIndex(definition); }
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; } }
public SearchAPI(IOptions <Configuration.SearchOptions> options) { Uri endpointUri = new Uri(options.Value.Endpoint !); Azure.AzureKeyCredential credentials = new Azure.AzureKeyCredential(options.Value.AccessKey !); searchIndexClient = new SearchIndexClient(endpointUri, credentials); searchClient = new SearchClient(endpointUri, IndexName, credentials); FieldBuilder fieldBuilder = new FieldBuilder(); var searchFields = fieldBuilder.Build(typeof(AlbumInfoSearchObject)); var definition = new SearchIndex(IndexName, searchFields); var suggester = new SearchSuggester("AlbumsSuggester", new[] { nameof(AlbumInfoSearchObject.AlbumName), nameof(AlbumInfoSearchObject.ArtistName), nameof(AlbumInfoSearchObject.Colors), nameof(AlbumInfoSearchObject.Tags), nameof(AlbumInfoSearchObject.Captions) }); definition.Suggesters.Add(suggester); searchIndexClient.CreateOrUpdateIndex(definition); }
static void Main(string[] args) { var fieldBuilder = new FieldBuilder(50, 80); fieldBuilder .AddLivePoint(10, 10) .AddLivePoint(10, 11) .AddLivePoint(10, 12) .AddLivePoint(9, 12) .AddLivePoint(8, 11); var field = fieldBuilder.Build(); var drawer = new Drawer(); while (true) { drawer.Draw(field); field.Recalc(); field.NextTurn(); Thread.Sleep(300); } }
public async Task <IActionResult> Accept(int id) { if (_activeWar.TheWar != null) { return(BadRequest("You can have only one active war.")); } var invitedPlayer = await _player.GetEntity(); var invitation = await _invitationRepo.GetByIdAsync(id); if (invitation == null) { return(NotFound(id)); } var newWar = new War { Player1Id = invitation.InviterId, Player2Id = invitation.InvitedId, WhoShotId = invitation.InvitedId, Field = JsonConvert.SerializeObject(_fieldBuilder.Build()), Status = WarStatus.Active, Rows = _config.Rows, Cols = _config.Cols, WinScore = CalcWinScore() }; _warRepo.Insert(newWar); _invitationRepo.Delete(invitation); await _warRepo.CommitAsync(); _notifServ.Add(new Notification(invitation.InviterId, InvitationAccepted)); return(RedirectToAction("Index", "Home")); }
public ActionResult Index() { ViewBag.Fields = FieldBuilder.Build <TEntity>(); return(View("Admin/Index")); }
public void CreateCustomerIndex() { //creating index SearchIndexClient indexClient = new SearchIndexClient(Uri, keyCredential); SearchIndexerClient indexerClient = new SearchIndexerClient(Uri, keyCredential); Console.WriteLine("Creating index..."); FieldBuilder fieldBuilder = new FieldBuilder(); var searchFields = fieldBuilder.Build(typeof(ServiceOrder)); //var searchIndex = new SearchIndex("serviceorder-sql-idx", searchFields); var searchIndex = new SearchIndex("serviceorder-sql-idx", searchFields); // If we have run the sample before, this index will be populated // We can clear the index by deleting it if it exists and creating // it again CleanupSearchIndexClientResources(indexClient, searchIndex); indexClient.CreateOrUpdateIndex(searchIndex); //Creating data source Console.WriteLine("Creating data source..."); var dataSource = new SearchIndexerDataSourceConnection( "serviceorder-sql-ds", SearchIndexerDataSourceType.AzureSql, azureSQLConnectionStr, new SearchIndexerDataContainer("[ServiceOrder]")); indexerClient.CreateOrUpdateDataSourceConnection(dataSource); //Creating indexer Console.WriteLine("Creating Azure SQL indexer..."); //var schedule = new IndexingSchedule(TimeSpan.FromDays(1)) //{ // StartTime = DateTimeOffset.Now //}; var parameters = new IndexingParameters() { BatchSize = 100, MaxFailedItems = 0, MaxFailedItemsPerBatch = 0 }; // Indexer declarations require a data source and search index. // Common optional properties include a schedule, parameters, and field mappings // The field mappings below are redundant due to how the Hotel class is defined, but // we included them anyway to show the syntax var indexer = new SearchIndexer("serviceorder-sql-idxr", dataSource.Name, searchIndex.Name) { Description = "Service Order indexer", Schedule = new IndexingSchedule(TimeSpan.FromMinutes(5)), Parameters = parameters, }; indexerClient.CreateOrUpdateIndexerAsync(indexer); Console.WriteLine("Running Azure SQL indexer..."); try { indexerClient.RunIndexerAsync(indexer.Name); } catch (CloudException e) when(e.Response.StatusCode == (HttpStatusCode)429) { Console.WriteLine("Failed to run indexer: {0}", e.Response.Content); } // Wait 5 seconds for indexing to complete before checking status Console.WriteLine("Waiting for indexing...\n"); System.Threading.Thread.Sleep(5000); }
static void Main(string[] args) { string serviceName = "lynx-searchengine-jsancho"; string indexName = "hotels-quickstart-v11"; string apiKey = "6C88A8613367F73135756A4CCFE1C24C"; // Create a SearchIndexClient to send create/delete index commands Uri serviceEndpoint = new Uri($"https://{serviceName}.search.windows.net/"); AzureKeyCredential credential = new AzureKeyCredential(apiKey); SearchIndexClient idxclient = new SearchIndexClient(serviceEndpoint, credential); // Create a SearchClient to load and query documents SearchClient srchclient = new SearchClient(serviceEndpoint, indexName, credential); // Delete index if it exists Console.WriteLine("{0}", "Deleting index...\n"); DeleteIndexIfExists(indexName, idxclient); var searchClientOptions = new SearchClientOptions { Serializer = new JsonObjectSerializer( new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }) }; var builder = new FieldBuilder { Serializer = searchClientOptions.Serializer }; var index = new SearchIndex(indexName) { Fields = builder.Build(typeof(Hotel)) }; Console.WriteLine("{0}", "Creating index...\n"); idxclient.CreateIndex(index); // Load documents (using a subset of fields for brevity) IndexDocumentsBatch <Hotel> batch = IndexDocumentsBatch.Create( IndexDocumentsAction.Upload(new Hotel { Id = "78", Name = "Upload Inn", Category = "hotel", Rate = 279, Updated = new DateTime(2018, 3, 1, 7, 0, 0) }), IndexDocumentsAction.Upload(new Hotel { Id = "54", Name = "Breakpoint by the Sea", Category = "motel", Rate = 162, Updated = new DateTime(2015, 9, 12, 7, 0, 0) }), IndexDocumentsAction.Upload(new Hotel { Id = "39", Name = "Debug Motel", Category = "motel", Rate = 159, Updated = new DateTime(2016, 11, 11, 7, 0, 0) }), IndexDocumentsAction.Upload(new Hotel { Id = "48", Name = "NuGet Hotel", Category = "hotel", Rate = 238, Updated = new DateTime(2016, 5, 30, 7, 0, 0) }), IndexDocumentsAction.Upload(new Hotel { Id = "12", Name = "Renovated Ranch", Category = "motel", Rate = 149, Updated = new DateTime(2020, 1, 24, 7, 0, 0) })); IndexDocumentsOptions idxoptions = new IndexDocumentsOptions { ThrowOnAnyError = true }; Console.WriteLine("{0}", "Loading index...\n"); srchclient.IndexDocuments(batch, idxoptions); // Wait 2 secondsfor indexing to complete before starting queries (for demo and console-app purposes only) Console.WriteLine("Waiting for indexing...\n"); System.Threading.Thread.Sleep(2000); // Call the RunQueries method to invoke a series of queries Console.WriteLine("Starting queries...\n"); RunQueries(srchclient); // End the program Console.WriteLine("{0}", "Complete. Press any key to end this program...\n"); Console.ReadKey(); }
public static async Task Main(string[] args) { IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json"); IConfigurationRoot configuration = builder.Build(); if (configuration["SearchServiceEndPoint"] == "Put your search service endpoint here") { Console.Error.WriteLine("Specify SearchServiceEndPoint in appsettings.json"); Environment.Exit(-1); } if (configuration["SearchServiceAdminApiKey"] == "Put your search service admin API key here") { Console.Error.WriteLine("Specify SearchServiceAdminApiKey in appsettings.json"); Environment.Exit(-1); } if (configuration["AzureSQLConnectionString"] == "Put your Azure SQL database connection string here") { Console.Error.WriteLine("Specify AzureSQLConnectionString in appsettings.json"); Environment.Exit(-1); } SearchIndexClient indexClient = new SearchIndexClient(new Uri(configuration["SearchServiceEndPoint"]), new AzureKeyCredential(configuration["SearchServiceAdminApiKey"])); SearchIndexerClient indexerClient = new SearchIndexerClient(new Uri(configuration["SearchServiceEndPoint"]), new AzureKeyCredential(configuration["SearchServiceAdminApiKey"])); Console.WriteLine("Creating index..."); FieldBuilder fieldBuilder = new FieldBuilder(); var searchFields = fieldBuilder.Build(typeof(Hotel)); var searchIndex = new SearchIndex("hotels-sql-idx", searchFields); // If we have run the sample before, this index will be populated // We can clear the index by deleting it if it exists and creating // it again CleanupSearchIndexClientResources(indexClient, searchIndex); indexClient.CreateOrUpdateIndex(searchIndex); Console.WriteLine("Creating data source..."); // The sample data set has a table name of "hotels" // The sample data set table has a "soft delete" column named IsDeleted // When this column is set to true and the indexer sees it, it will remove the // corresponding document from the search service // See this link for more information // https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.search.models.softdeletecolumndeletiondetectionpolicy // The sample data set uses SQL integrated change tracking for change detection // This means that when the indexer runs, it will be able to detect which data has // changed since the last run using built in change tracking // See this link for more information // https://docs.microsoft.com/en-us/sql/relational-databases/track-changes/about-change-tracking-sql-server var dataSource = new SearchIndexerDataSourceConnection( "hotels-sql-ds", SearchIndexerDataSourceType.AzureSql, configuration["AzureSQLConnectionString"], new SearchIndexerDataContainer("hotels")); // The data source does not need to be deleted if it was already created, // but the connection string may need to be updated if it was changed indexerClient.CreateOrUpdateDataSourceConnection(dataSource); Console.WriteLine("Creating Azure SQL indexer..."); var schedule = new IndexingSchedule(TimeSpan.FromDays(1)) { StartTime = DateTimeOffset.Now }; var parameters = new IndexingParameters() { BatchSize = 100, MaxFailedItems = 0, MaxFailedItemsPerBatch = 0 }; // Indexer declarations require a data source and search index. // Common optional properties include a schedule, parameters, and field mappings // The field mappings below are redundant due to how the Hotel class is defined, but // we included them anyway to show the syntax var indexer = new SearchIndexer("hotels-sql-idxr", dataSource.Name, searchIndex.Name) { Description = "Data indexer", Schedule = schedule, Parameters = parameters, FieldMappings = { new FieldMapping("_id") { TargetFieldName = "HotelId" }, new FieldMapping("Amenities") { TargetFieldName = "Tags" } } }; // Indexers contain metadata about how much they have already indexed // If we already ran the sample, the indexer will remember that it already // indexed the sample data and not run again // To avoid this, reset the indexer if it exists CleanupSearchIndexerClientResources(indexerClient, indexer); await indexerClient.CreateOrUpdateIndexerAsync(indexer); // We created the indexer with a schedule, but we also // want to run it immediately Console.WriteLine("Running Azure SQL indexer..."); try { await indexerClient.RunIndexerAsync(indexer.Name); } catch (CloudException e) when(e.Response.StatusCode == (HttpStatusCode)429) { Console.WriteLine("Failed to run indexer: {0}", e.Response.Content); } // Wait 5 seconds for indexing to complete before checking status Console.WriteLine("Waiting for indexing...\n"); System.Threading.Thread.Sleep(5000); // After an indexer run, you can retrieve status. CheckIndexerStatus(indexerClient, indexer); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); Environment.Exit(0); }
public void BuildThrowsTypeNull() { ArgumentNullException ex = Assert.Throws <ArgumentNullException>(() => FieldBuilder.Build(null)); Assert.AreEqual("type", ex.ParamName); }