diff --git a/clients/algoliasearch-client-csharp/algoliasearch/Transport/HttpTransport.cs b/clients/algoliasearch-client-csharp/algoliasearch/Transport/HttpTransport.cs index aa81d22eb7..0b8d8167c1 100644 --- a/clients/algoliasearch-client-csharp/algoliasearch/Transport/HttpTransport.cs +++ b/clients/algoliasearch-client-csharp/algoliasearch/Transport/HttpTransport.cs @@ -190,9 +190,9 @@ private async Task ExecuteRequestAsync(HttpMethod metho } } - if (_logger.IsEnabled(LogLevel.Debug)) + if (_logger.IsEnabled(LogLevel.Error)) { - _logger.LogDebug("Retry strategy failed: {ErrorMessage}", _errorMessage); + _logger.LogError("Retry strategy failed: {ErrorMessage}", _errorMessage); } throw new AlgoliaUnreachableHostException("RetryStrategy failed to connect to Algolia. Reason: " + _errorMessage); diff --git a/playground/csharp/Playground/.env.example b/playground/csharp/Playground/.env.example deleted file mode 100644 index de6c6707e8..0000000000 --- a/playground/csharp/Playground/.env.example +++ /dev/null @@ -1,2 +0,0 @@ -ALGOLIA_METIS_APPLICATION_ID=XXXX -ALGOLIA_METIS_API_KEY=XXXX diff --git a/playground/csharp/Playground/Model/Configuration.cs b/playground/csharp/Playground/Model/Configuration.cs index 5528aa24e6..4bbab5ebc7 100644 --- a/playground/csharp/Playground/Model/Configuration.cs +++ b/playground/csharp/Playground/Model/Configuration.cs @@ -4,7 +4,6 @@ public class Configuration public string AdminApiKey { get; set; } public string SearchApiKey { get; set; } public string MonitoringApiKey { get; set; } - public string MetisAppId { get; set; } - public string MetisApiKey { get; set; } + public string DefaultIndexName { get; set; } } diff --git a/playground/csharp/Playground/Playground.csproj b/playground/csharp/Playground/Playground.csproj index 3365cbed95..d4abacb828 100644 --- a/playground/csharp/Playground/Playground.csproj +++ b/playground/csharp/Playground/Playground.csproj @@ -19,10 +19,4 @@ - - - Always - - - diff --git a/playground/csharp/Playground/Playgrounds/ABTesting.cs b/playground/csharp/Playground/Playgrounds/ABTesting.cs index ae2da32d19..ae8a8b7f6f 100644 --- a/playground/csharp/Playground/Playgrounds/ABTesting.cs +++ b/playground/csharp/Playground/Playgrounds/ABTesting.cs @@ -1,22 +1,44 @@ using System.Globalization; using Algolia.Search.Clients; using Algolia.Search.Models.Abtesting; +using Algolia.Utils; +using Microsoft.Extensions.Logging; namespace Algolia.Playgrounds; -public static class ABTesting +public class ABTestingPlayground : IPlayground { - public static async Task Run(Configuration configuration) + const string DefaultIndex = "test-csharp-new-client"; + private readonly AbtestingClient _client; + private readonly Configuration _configuration; + + public ABTestingPlayground(Configuration configuration) + { + var loggerFactory = LoggerFactory.Create(i => i.AddFilter("Algolia", LogLevel.Information) + .AddConsole()); + var config = new AbtestingConfig(configuration.AppId, configuration.AdminApiKey); + _client = new AbtestingClient(config, loggerFactory); + _configuration = configuration; + } + + public async Task Run() { - Console.WriteLine("------------------------------------"); - Console.WriteLine("Starting ABTesting API playground"); - Console.WriteLine("------------------------------------"); - var client = new AbtestingClient(new AbtestingConfig(configuration.AppId, configuration.AdminApiKey)); + PlaygroundHelper.Hello("Starting ABTesting API playground"); - var newABTest = await client.AddABTestsAsync(new AddABTestsRequest("A simple A/B Test", - new List { new(new AbTestsVariant("test-index", 50)), new(new AbTestsVariant("test-index2", 50)) }, - DateTime.UtcNow.AddDays(1d).ToString("o", CultureInfo.InvariantCulture))); + try + { + var newABTest = await _client.AddABTestsAsync(new AddABTestsRequest("A simple A/B Test", + [ + new AddABTestsVariant(new AbTestsVariant("test-index", 50)), + new AddABTestsVariant(new AbTestsVariant("test-index2", 50)) + ], + DateTime.UtcNow.AddDays(1d).ToString("o", CultureInfo.InvariantCulture))); - Console.WriteLine(newABTest.AbTestID); + Console.WriteLine(newABTest.AbTestID); + } + catch (Exception e) + { + Console.WriteLine(e); + } } } diff --git a/playground/csharp/Playground/Playgrounds/Analytics.cs b/playground/csharp/Playground/Playgrounds/Analytics.cs index c88be441e5..9c95fe6cd1 100644 --- a/playground/csharp/Playground/Playgrounds/Analytics.cs +++ b/playground/csharp/Playground/Playgrounds/Analytics.cs @@ -1,19 +1,36 @@ using Algolia.Search.Clients; +using Algolia.Utils; +using Microsoft.Extensions.Logging; namespace Algolia.Playgrounds; -public static class Analytics +public class AnalyticsPlayground : IPlayground { - public static async Task Run(Configuration configuration) + private readonly AnalyticsClient _client; + private readonly Configuration _configuration; + + public AnalyticsPlayground(Configuration configuration) { - Console.WriteLine("------------------------------------"); - Console.WriteLine("Starting Analytics API playground"); - Console.WriteLine("------------------------------------"); - var client = new AnalyticsClient(new AnalyticsConfig(configuration.AppId, configuration.AdminApiKey)); + var loggerFactory = LoggerFactory.Create(i => i.AddFilter("Algolia", LogLevel.Information) + .AddConsole()); + var config = new AnalyticsConfig(configuration.AppId, configuration.AdminApiKey); + _client = new AnalyticsClient(config, loggerFactory); + _configuration = configuration; + } - var shortDateString = DateTime.UtcNow.AddDays(-1).ToString("YYYY-MM-DD"); - Console.WriteLine(shortDateString); - var getSearchesCountResponse = await client.GetSearchesCountAsync("test-index", shortDateString); - Console.WriteLine(getSearchesCountResponse.Count); + public async Task Run() + { + PlaygroundHelper.Hello("Starting Analytics API playground"); + try + { + var shortDateString = DateTime.UtcNow.AddDays(-1).ToString("YYYY-MM-DD"); + Console.WriteLine(shortDateString); + var getSearchesCountResponse = await _client.GetSearchesCountAsync("test-index", shortDateString); + Console.WriteLine(getSearchesCountResponse.Count); + } + catch (Exception) + { + // ignored + } } } diff --git a/playground/csharp/Playground/Playgrounds/Ingestion.cs b/playground/csharp/Playground/Playgrounds/Ingestion.cs index dc887892d0..39a3b10854 100644 --- a/playground/csharp/Playground/Playgrounds/Ingestion.cs +++ b/playground/csharp/Playground/Playgrounds/Ingestion.cs @@ -1,40 +1,60 @@ using Algolia.Search.Clients; using Algolia.Search.Models.Ingestion; +using Algolia.Search.Models.Monitoring; +using Algolia.Utils; +using Microsoft.Extensions.Logging; namespace Algolia.Playgrounds; -public static class Ingestion +public class IngestionPlayground : IPlayground { - public static async Task Run(Configuration configuration) - { - Console.WriteLine("------------------------------------"); - Console.WriteLine("Starting Ingestion API playground"); - Console.WriteLine("------------------------------------"); - var client = new IngestionClient(new IngestionConfig(configuration.AppId, configuration.AdminApiKey, "us")); + private readonly IngestionClient _client; + private readonly Configuration _configuration; - // Get existing JSON source - Console.WriteLine("--- Get existing JSON source `GetSourcesAsync` ---"); - var jsonSources = await client.GetSourcesAsync(type: new List { SourceType.Json }).ConfigureAwait(false); - Console.WriteLine(jsonSources.Sources.Count == 0 ? "There is no JSON Source !" : $"There is {jsonSources.Sources.Count} JSON source(s)"); + public IngestionPlayground(Configuration configuration) + { + var loggerFactory = LoggerFactory.Create(i => i.AddFilter("Algolia", LogLevel.Information) + .AddConsole()); + var config = new IngestionConfig(configuration.AppId, configuration.AdminApiKey, "us"); + _client = new IngestionClient(config, loggerFactory); + _configuration = configuration; + } - // Deleting existing JSON source - Console.WriteLine("--- Deleting existing JSON source `DeleteSourceAsync` ---"); - foreach (var source in jsonSources.Sources) + public async Task Run() + { + PlaygroundHelper.Hello("Starting Ingestion API playground"); + try { - Console.WriteLine($"Deleting source {source.SourceID}"); - var response = await client.DeleteSourceAsync(source.SourceID).ConfigureAwait(false); - Console.WriteLine(response.DeletedAt); - } + // Get existing JSON source + Console.WriteLine("--- Get existing JSON source `GetSourcesAsync` ---"); + var jsonSources = await _client.GetSourcesAsync(type: [SourceType.Json]).ConfigureAwait(false); + Console.WriteLine(jsonSources.Sources.Count == 0 + ? "There is no JSON Source !" + : $"There is {jsonSources.Sources.Count} JSON source(s)"); - // Create a new JSON source - Console.WriteLine("--- Create a new source `CreateSourceAsync` ---"); - var saved = await client.CreateSourceAsync(new SourceCreate - { - Name = "test-csharp-new-client", - Type = SourceType.Json, - Input = new SourceInput(new SourceJSON("https://test.com/test.json")) - }).ConfigureAwait(false); + // Deleting existing JSON source + Console.WriteLine("--- Deleting existing JSON source `DeleteSourceAsync` ---"); + foreach (var source in jsonSources.Sources) + { + Console.WriteLine($"Deleting source {source.SourceID}"); + var response = await _client.DeleteSourceAsync(source.SourceID).ConfigureAwait(false); + Console.WriteLine(response.DeletedAt); + } + + // Create a new JSON source + Console.WriteLine("--- Create a new source `CreateSourceAsync` ---"); + var saved = await _client.CreateSourceAsync(new SourceCreate + { + Name = "test-csharp-new-client", + Type = SourceType.Json, + Input = new SourceInput(new SourceJSON("https://test.com/test.json")) + }).ConfigureAwait(false); - Console.WriteLine(saved.SourceID); + Console.WriteLine(saved.SourceID); + } + catch (Exception) + { + // ignored + } } } diff --git a/playground/csharp/Playground/Playgrounds/Insights.cs b/playground/csharp/Playground/Playgrounds/Insights.cs index a100e1dca3..3cb729f0ca 100644 --- a/playground/csharp/Playground/Playgrounds/Insights.cs +++ b/playground/csharp/Playground/Playgrounds/Insights.cs @@ -1,26 +1,41 @@ using Algolia.Search.Clients; using Algolia.Search.Models.Insights; +using Algolia.Utils; +using Microsoft.Extensions.Logging; namespace Algolia.Playgrounds; -public static class Insights +public class InsightsPlayground : IPlayground { - public static async Task Run(Configuration configuration) + private readonly InsightsClient _client; + private readonly Configuration _configuration; + + public InsightsPlayground(Configuration configuration) + { + var loggerFactory = LoggerFactory.Create(i => i.AddFilter("Algolia", LogLevel.Information) + .AddConsole()); + var config = new InsightsConfig(configuration.AppId, configuration.AdminApiKey); + _client = new InsightsClient(config, loggerFactory); + _configuration = configuration; + } + + public async Task Run() { - Console.WriteLine("------------------------------------"); - Console.WriteLine("Starting Insights API playground"); - Console.WriteLine("------------------------------------"); - var client = new InsightsClient(new InsightsConfig(configuration.AppId, configuration.AdminApiKey)); + PlaygroundHelper.Hello("Starting Insights API playground"); - Console.WriteLine("--- Push new events `PushEventsAsync` ---"); - var response = await client.PushEventsAsync(new InsightsEvents(new List() + try { - new(new ConvertedObjectIDs("Buy event", ConversionEvent.Conversion, "test", - new List { "iphone_7", "iphone_8" }, "me")) - })).ConfigureAwait(false); + Console.WriteLine("--- Push new events `PushEventsAsync` ---"); + var response = await _client.PushEventsAsync(new InsightsEvents([ + new EventsItems(new ConvertedObjectIDs("Buy event", ConversionEvent.Conversion, "test", + ["iphone_7", "iphone_8"], "me")) + ])).ConfigureAwait(false); - Console.WriteLine(response); + Console.WriteLine(response); + } + catch (Exception e) + { + Console.WriteLine(e); + } } - - } diff --git a/playground/csharp/Playground/Playgrounds/Monitoring.cs b/playground/csharp/Playground/Playgrounds/Monitoring.cs index 6c9575e32a..d663cd5d56 100644 --- a/playground/csharp/Playground/Playgrounds/Monitoring.cs +++ b/playground/csharp/Playground/Playgrounds/Monitoring.cs @@ -1,28 +1,46 @@ using System.Globalization; using Algolia.Search.Clients; +using Algolia.Utils; +using Microsoft.Extensions.Logging; namespace Algolia.Playgrounds; -public static class Monitoring +public class MonitoringPlayground : IPlayground { - public static async Task Run(Configuration configuration) + private readonly MonitoringClient _client; + private readonly Configuration _configuration; + + public MonitoringPlayground(Configuration configuration) + { + var loggerFactory = LoggerFactory.Create(i => i.AddFilter("Algolia", LogLevel.Information) + .AddConsole()); + var config = new MonitoringConfig(configuration.AppId, configuration.AdminApiKey); + _client = new MonitoringClient(config, loggerFactory); + _configuration = configuration; + } + + public async Task Run() { - Console.WriteLine("------------------------------------"); - Console.WriteLine("Starting Monitoring API playground"); - Console.WriteLine("------------------------------------"); - var client = new MonitoringClient(new MonitoringConfig(configuration.AppId, configuration.MonitoringApiKey)); + PlaygroundHelper.Hello("Starting Monitoring API playground"); - Console.WriteLine("--- Get clusters status `GetStatusAsync` ---"); - var response = await client.GetStatusAsync(); - Console.WriteLine(string.Join(',', response.Status.Select((x, y) => $"Host: {x.Key} is {(x.Value)}"))); + try + { + Console.WriteLine("--- Get clusters status `GetStatusAsync` ---"); + var response = await _client.GetStatusAsync(); + Console.WriteLine(string.Join(',', response.Status.Select((x, y) => $"Host: {x.Key} is {(x.Value)}"))); - Console.WriteLine("--- Get incidents list `GetIncidentsAsync` ---"); - var incidentsResponse = await client.GetIncidentsAsync(); + Console.WriteLine("--- Get incidents list `GetIncidentsAsync` ---"); + var incidentsResponse = await _client.GetIncidentsAsync(); - foreach (var incident in incidentsResponse.Incidents) + foreach (var incident in incidentsResponse.Incidents) + { + Console.WriteLine( + $"{incident.Key}: {Environment.NewLine}- {string.Join($"{Environment.NewLine} -", incident.Value.Select(inner => $" {DateTimeOffset.FromUnixTimeMilliseconds(inner.T.Value).ToString(CultureInfo.InvariantCulture)} - {inner.V.Title}"))} {Environment.NewLine}"); + } + } + catch (Exception e) { - Console.WriteLine( - $"{incident.Key}: {Environment.NewLine}- {string.Join($"{Environment.NewLine} -", incident.Value.Select(inner => $" {DateTimeOffset.FromUnixTimeMilliseconds(inner.T.Value).ToString(CultureInfo.InvariantCulture)} - {inner.V.Title}"))} {Environment.NewLine}"); + Console.WriteLine(e); } } } diff --git a/playground/csharp/Playground/Playgrounds/Personalization.cs b/playground/csharp/Playground/Playgrounds/Personalization.cs index f2d328b001..f15ee21ade 100644 --- a/playground/csharp/Playground/Playgrounds/Personalization.cs +++ b/playground/csharp/Playground/Playgrounds/Personalization.cs @@ -1,14 +1,33 @@ using Algolia.Search.Clients; +using Algolia.Utils; +using Microsoft.Extensions.Logging; namespace Algolia.Playgrounds; -public static class Personalization +public class PersonalizationPlayground : IPlayground { - public static async Task Run(Configuration configuration) + private readonly PersonalizationClient _client; + private readonly Configuration _configuration; + + public PersonalizationPlayground(Configuration configuration) { - Console.WriteLine("------------------------------------"); - Console.WriteLine("Starting Personalization API playground"); - Console.WriteLine("------------------------------------"); - var client = new PersonalizationClient(new PersonalizationConfig(configuration.AppId, configuration.AdminApiKey, "us")); + var loggerFactory = LoggerFactory.Create(i => i.AddFilter("Algolia", LogLevel.Information) + .AddConsole()); + var config = new PersonalizationConfig(configuration.AppId, configuration.AdminApiKey, "us"); + _client = new PersonalizationClient(config, loggerFactory); + _configuration = configuration; + } + + public async Task Run() + { + PlaygroundHelper.Hello("Starting Personalization API playground"); + + try + { + } + catch (Exception e) + { + Console.WriteLine(e); + } } } diff --git a/playground/csharp/Playground/Playgrounds/QuerySuggestions.cs b/playground/csharp/Playground/Playgrounds/QuerySuggestions.cs index 37a5c62768..0a22e00740 100644 --- a/playground/csharp/Playground/Playgrounds/QuerySuggestions.cs +++ b/playground/csharp/Playground/Playgrounds/QuerySuggestions.cs @@ -1,14 +1,35 @@ +using System.Globalization; using Algolia.Search.Clients; +using Algolia.Search.Models.Abtesting; +using Algolia.Utils; +using Microsoft.Extensions.Logging; namespace Algolia.Playgrounds; -public static class QuerySuggestions +public class QuerySuggestionsPlayground : IPlayground { - public static async Task Run(Configuration configuration) + private readonly QuerySuggestionsClient _client; + private readonly Configuration _configuration; + + public QuerySuggestionsPlayground(Configuration configuration) { - Console.WriteLine("------------------------------------"); - Console.WriteLine("Starting QuerySuggestions API playground"); - Console.WriteLine("------------------------------------"); - var client = new QuerySuggestionsClient(new QuerySuggestionsConfig(configuration.AppId, configuration.AdminApiKey, "us")); + var loggerFactory = LoggerFactory.Create(i => i.AddFilter("Algolia", LogLevel.Information) + .AddConsole()); + var config = new QuerySuggestionsConfig(configuration.AppId, configuration.AdminApiKey, "us"); + _client = new QuerySuggestionsClient(config, loggerFactory); + _configuration = configuration; + } + + public async Task Run() + { + PlaygroundHelper.Hello("Starting QuerySuggestions API playground"); + + try + { + } + catch (Exception) + { + // ignored + } } } diff --git a/playground/csharp/Playground/Playgrounds/Recommend.cs b/playground/csharp/Playground/Playgrounds/Recommend.cs index 2518025d3b..b09e8264ae 100644 --- a/playground/csharp/Playground/Playgrounds/Recommend.cs +++ b/playground/csharp/Playground/Playgrounds/Recommend.cs @@ -1,14 +1,33 @@ using Algolia.Search.Clients; +using Algolia.Utils; +using Microsoft.Extensions.Logging; namespace Algolia.Playgrounds; -public static class Recommend +public class RecommendPlayground : IPlayground { - public static async Task Run(Configuration configuration) + private readonly RecommendClient _client; + private readonly Configuration _configuration; + + public RecommendPlayground(Configuration configuration) { - Console.WriteLine("------------------------------------"); - Console.WriteLine("Starting Recommend API playground"); - Console.WriteLine("------------------------------------"); - var client = new RecommendClient(new RecommendConfig(configuration.AppId, configuration.AdminApiKey)); + var loggerFactory = LoggerFactory.Create(i => i.AddFilter("Algolia", LogLevel.Information) + .AddConsole()); + var config = new RecommendConfig(configuration.AppId, configuration.AdminApiKey); + _client = new RecommendClient(config, loggerFactory); + _configuration = configuration; + } + + public async Task Run() + { + PlaygroundHelper.Hello("Starting Recommend API playground"); + + try + { + } + catch (Exception) + { + // ignored + } } } diff --git a/playground/csharp/Playground/Playgrounds/Search.cs b/playground/csharp/Playground/Playgrounds/Search.cs index e5cd2df396..004d9ee23b 100644 --- a/playground/csharp/Playground/Playgrounds/Search.cs +++ b/playground/csharp/Playground/Playgrounds/Search.cs @@ -9,50 +9,48 @@ namespace Algolia.Playgrounds; -public static class SearchPlayground +public class SearchPlayground : IPlayground { - public static async Task Run(Configuration configuration) - { - const string defaultIndex = "test-csharp-new-client"; - - Console.WriteLine("------------------------------------"); - Console.WriteLine("Starting Search API playground"); - Console.WriteLine("------------------------------------"); - - var searchConfig = new SearchConfig(configuration.AppId, configuration.AdminApiKey) - { - Compression = CompressionType.None - }; + const string DefaultIndex = "test-csharp-new-client"; + private readonly SearchClient _client; + private readonly Configuration _configuration; + public SearchPlayground(Configuration configuration) + { + var searchConfig = new SearchConfig(configuration.AppId, configuration.AdminApiKey); var loggerFactory = LoggerFactory.Create(i => i.AddFilter("Algolia", LogLevel.Information) .AddConsole()); - var client = new SearchClient(searchConfig, loggerFactory); + _client = new SearchClient(searchConfig, loggerFactory); + _configuration = configuration; + } - var metisClient = new SearchClient(new SearchConfig(configuration.MetisAppId, configuration.MetisApiKey) + public async Task Run() + { + PlaygroundHelper.Hello("Starting Search API playground"); + try { - Compression = CompressionType.None - }); + await Search(); + await Index(); + await ApiKey(); + await Synonym(); + await Rule(); + } + catch (Exception e) + { + Console.WriteLine(e); + } + } + private async Task Search() + { // Save a single object Console.WriteLine("--- Save a single object `SaveObjectAsync` ---"); - var saved = await client.SaveObjectAsync(defaultIndex, + var saved = await _client.SaveObjectAsync(DefaultIndex, new { ObjectID = "test2", value = "test", otherValue = "otherValue" }); await PlaygroundHelper.Start($"Saving record ObjectID=`{saved.ObjectID}` - Async TaskID: `{saved.TaskID}`", - () => client.WaitForTaskAsync(defaultIndex, saved.TaskID), $"Record ObjectID=`{saved.ObjectID}` saved !"); - - // Set settings on index - Console.WriteLine("--- Set setting on index `SetSettingsAsync` ---"); - var updatedAtResponse = await client.SetSettingsAsync(defaultIndex, new IndexSettings() - { - AttributesForFaceting = ["searchable(value)", "searchable(otherValue)"], - SearchableAttributes = ["value", "otherValue"] - }); - - await PlaygroundHelper.Start( - $"Saving new settings on index `{defaultIndex}` - Async TaskID: `{updatedAtResponse.TaskID}`", - () => client.WaitForTaskAsync(defaultIndex, updatedAtResponse.TaskID), "New settings applied !"); + () => _client.WaitForTaskAsync(DefaultIndex, saved.TaskID), $"Record ObjectID=`{saved.ObjectID}` saved !"); // Save multiple objects Console.WriteLine("--- Save a multiple objects `BatchAsync` ---"); @@ -62,23 +60,22 @@ await PlaygroundHelper.Start( new(Action.AddObject, new { ObjectID = "test4", value = "batch2", otherValue = "otherValue2" }), new(Action.AddObject, new { ObjectID = "test5", value = "batch3", otherValue = "otherValue3" }), }; - var batch = await client.BatchAsync(defaultIndex, new BatchWriteParams(requests)); + var batch = await _client.BatchAsync(DefaultIndex, new BatchWriteParams(requests)); await PlaygroundHelper.Start( $"Saving new records - Async TaskID: `{batch.TaskID}`", - () => client.WaitForTaskAsync(defaultIndex, batch.TaskID), "Records saved !"); + () => _client.WaitForTaskAsync(DefaultIndex, batch.TaskID), "Records saved !"); // Browse all objects Console.WriteLine("--- Browse all objects, one page `BrowseAsync` ---"); - var r = await client.BrowseAsync(defaultIndex, + var r = await _client.BrowseAsync(DefaultIndex, new BrowseParams(new BrowseParamsObject { HitsPerPage = 100 })); r.Hits.ForEach(h => Console.WriteLine($" - Record ObjectID: {h.ObjectID}, {h.Value} {h.OtherValue} {h.AdditionalProperties.Count}")); - // Browse Helper, to fetch all pages Console.WriteLine("--- Browse all objects, all pages `BrowseObjectsAsync` ---"); - var results = await client.BrowseObjectsAsync(defaultIndex, new BrowseParamsObject + var results = await _client.BrowseObjectsAsync(DefaultIndex, new BrowseParamsObject { HitsPerPage = 1 }); @@ -89,33 +86,33 @@ await PlaygroundHelper.Start( Console.WriteLine("--- Get Objects, with specific attributes `GetObjectsAsync` ---"); var getObjRequests = new List { - new("test2", defaultIndex) + new("test2", DefaultIndex) { AttributesToRetrieve = ["otherValue"] }, - new("test3", defaultIndex) + new("test3", DefaultIndex) { AttributesToRetrieve = ["otherValue"] }, }; - var getObjResults = await client.GetObjectsAsync(new GetObjectsParams(getObjRequests)); + var getObjResults = await _client.GetObjectsAsync(new GetObjectsParams(getObjRequests)); getObjResults.Results.ForEach(t => Console.WriteLine($" - Record ObjectID: {t.ObjectID} - Property `otherValue`: {t.OtherValue}")); // Search single index Console.WriteLine("--- Search single index `SearchSingleIndexAsync` ---"); - var t = await client.SearchSingleIndexAsync(defaultIndex); + var t = await _client.SearchSingleIndexAsync(DefaultIndex); t.Hits.ForEach(h => Console.WriteLine($" - Record ObjectID: {h.ObjectID}")); Console.WriteLine("--- Search multiple indices `SearchAsync` ---"); var searchQueries = new List { - new(new SearchForHits(defaultIndex)), - new(new SearchForHits(defaultIndex)), - new(new SearchForFacets("otherValue", defaultIndex, SearchTypeFacet.Facet)), + new(new SearchForHits(DefaultIndex)), + new(new SearchForHits(DefaultIndex)), + new(new SearchForFacets("otherValue", DefaultIndex, SearchTypeFacet.Facet)), }; - var search = await client.SearchAsync(new SearchMethodParams(searchQueries)); + var search = await _client.SearchAsync(new SearchMethodParams(searchQueries)); search.Results.ForEach(result => { if (result.IsSearchResponse()) @@ -134,42 +131,105 @@ await PlaygroundHelper.Start( } }); - // Search with Metis Additional properties - Console.WriteLine("--- Search single index `SearchSingleIndexAsync`, with additional properties ---"); - var tMetis = await metisClient.SearchSingleIndexAsync("008_jobs_v2_nosplit__contents__default"); - foreach (var tMetisAdditionalProperty in tMetis.AdditionalProperties) + Console.WriteLine("--- Error Handling ---"); + try { - Console.WriteLine( - $" - Additional property found {tMetisAdditionalProperty.Key} : {tMetisAdditionalProperty.Value}"); + await _client.SaveRulesAsync(DefaultIndex, + [ + new Rule + { + ObjectID = "TestRule1", + Description = "Test", + Consequence = new Consequence { Promote = [new Promote(new PromoteObjectID("test3", 1))] }, + Conditions = [new Condition { Anchoring = Anchoring.Contains, Context = "shoes" }] + } + ]).ConfigureAwait(false); + } + catch (AlgoliaApiException e) + { + Console.WriteLine($"Message: {e.Message} - Status {e.HttpErrorCode}"); } + Console.WriteLine("--- Replace all objects `` ---"); + var replaceAllResponse = await _client.ReplaceAllObjectsAsync(DefaultIndex, + new List { new TestObject { Value = "hello2", OtherValue = "world" } }); + Console.WriteLine($"Replace all objects - Async TaskID: `{string.Join(",", replaceAllResponse)}`"); + + Console.WriteLine("Search API playground has ended"); + } + + private async Task Index() + { + // Set settings on index + Console.WriteLine("--- Set setting on index `SetSettingsAsync` ---"); + var updatedAtResponse = await _client.SetSettingsAsync(DefaultIndex, new IndexSettings() + { + AttributesForFaceting = ["searchable(value)", "searchable(otherValue)"], + SearchableAttributes = ["value", "otherValue"] + }); + + await PlaygroundHelper.Start( + $"Saving new settings on index `{DefaultIndex}` - Async TaskID: `{updatedAtResponse.TaskID}`", + () => _client.WaitForTaskAsync(DefaultIndex, updatedAtResponse.TaskID), "New settings applied !"); + } + + private async Task ApiKey() + { // API Key Console.WriteLine("--- Add new api key `AddApiKeyAsync` ---"); - var addApiKeyResponse = await client.AddApiKeyAsync(new ApiKey() + var addApiKeyResponse = await _client.AddApiKeyAsync(new ApiKey() { Acl = [Acl.Browse, Acl.Search], Description = "A test key", - Indexes = [defaultIndex] + Indexes = [DefaultIndex] }); var createdApiKey = await PlaygroundHelper.Start($"Saving new API Key", async () => - await client.WaitForApiKeyAsync(ApiKeyOperation.Add, addApiKeyResponse.Key), "New key has been created !"); + await _client.WaitForApiKeyAsync(ApiKeyOperation.Add, addApiKeyResponse.Key), "New key has been created !"); Console.WriteLine("--- Update api key `UpdateApiKeyAsync` ---"); var modifiedApiKey = createdApiKey.ToApiKey(); modifiedApiKey.Description = "Updated description"; - var updateApiKey = await client.UpdateApiKeyAsync(addApiKeyResponse.Key, modifiedApiKey); + var updateApiKey = await _client.UpdateApiKeyAsync(addApiKeyResponse.Key, modifiedApiKey); await PlaygroundHelper.Start("Updating API Key`", async () => - await client.WaitForApiKeyAsync(ApiKeyOperation.Update, updateApiKey.Key, modifiedApiKey), "Key updated !"); + await _client.WaitForApiKeyAsync(ApiKeyOperation.Update, updateApiKey.Key, modifiedApiKey), "Key updated !"); Console.WriteLine("--- Delete api key `UpdateApiKeyAsync` ---"); - await client.DeleteApiKeyAsync(addApiKeyResponse.Key); + await _client.DeleteApiKeyAsync(addApiKeyResponse.Key); await PlaygroundHelper.Start("Deleting API Key", async () => - await client.WaitForApiKeyAsync(ApiKeyOperation.Delete, updateApiKey.Key), "Key deleted !"); + await _client.WaitForApiKeyAsync(ApiKeyOperation.Delete, updateApiKey.Key), "Key deleted !"); + + Console.WriteLine("--- Generate Secured API Keys `GenerateSecuredApiKeys` ---"); + var generateSecuredApiKeys = _client.GenerateSecuredApiKey(_configuration.SearchApiKey, + new SecuredApiKeyRestriction + { + RestrictIndices = [DefaultIndex], + }); + + Console.WriteLine("Calling SearchSingleIndexAsync with generated secured API keys"); + var searchClient = new SearchClient(_configuration.AppId, generateSecuredApiKeys); + await searchClient.SearchSingleIndexAsync(DefaultIndex); + + Console.WriteLine("Success, this index is authorized"); + + Console.WriteLine("Calling SearchSingleIndexAsync with not authorized index"); + + try + { + await searchClient.SearchSingleIndexAsync("not_authorized_index"); + } + catch (AlgoliaApiException e) + { + Console.WriteLine($"Error received (It's expected !) - {e.HttpErrorCode} {e.Message}"); + } + } + + private async Task Synonym() + { // Add Synonyms Console.WriteLine("--- Add Synonyms `SaveSynonymsAsync` ---"); - var synonymsResponse = await client.SaveSynonymsAsync(defaultIndex, + var synonymsResponse = await _client.SaveSynonymsAsync(DefaultIndex, [ new SynonymHit { @@ -195,12 +255,12 @@ await PlaygroundHelper.Start("Deleting API Key", async () => ]).ConfigureAwait(false); await PlaygroundHelper.Start($"Creating new Synonyms - Async TaskID: `{synonymsResponse.TaskID}`", async () => - await client.WaitForTaskAsync(defaultIndex, synonymsResponse.TaskID), "New Synonyms has been created !"); + await _client.WaitForTaskAsync(DefaultIndex, synonymsResponse.TaskID), "New Synonyms has been created !"); // Search Synonyms Console.WriteLine("--- Search Synonyms `SearchSynonymsAsync` ---"); - var searchSynonymsAsync = await client - .SearchSynonymsAsync(defaultIndex, + var searchSynonymsAsync = await _client + .SearchSynonymsAsync(DefaultIndex, new SearchSynonymsParams { Query = "", Type = SynonymType.Onewaysynonym, HitsPerPage = 1 }) .ConfigureAwait(false); @@ -208,15 +268,17 @@ await PlaygroundHelper.Start("Deleting API Key", async () => // Browse Synonyms Console.WriteLine("--- Browse Synonyms `BrowseSynonymsAsync` ---"); - var configuredTaskAwaitable = await client + var configuredTaskAwaitable = await _client .BrowseSynonymsAsync("test-csharp-new-client", new SearchSynonymsParams { Query = "", Type = SynonymType.Onewaysynonym }) .ConfigureAwait(false); configuredTaskAwaitable.ToList().ForEach(s => Console.WriteLine("Found :" + string.Join(',', s.Synonyms))); + } - // Add Rule + private async Task Rule() + { Console.WriteLine("--- Create new Rule `SaveRulesAsync` ---"); - var saveRulesAsync = await client.SaveRulesAsync(defaultIndex, + var saveRulesAsync = await _client.SaveRulesAsync(DefaultIndex, [ new Rule { @@ -242,57 +304,11 @@ await PlaygroundHelper.Start("Deleting API Key", async () => ]).ConfigureAwait(false); await PlaygroundHelper.Start($"Saving new Rule - Async TaskID: `{saveRulesAsync.TaskID}`", - async () => await client.WaitForTaskAsync(defaultIndex, saveRulesAsync.TaskID), "New Rule has been created !"); - - Console.WriteLine("--- Error Handling ---"); - try - { - await client.SaveRulesAsync(defaultIndex, - [ - new Rule - { - ObjectID = "TestRule1", - Description = "Test", - Consequence = new Consequence { Promote = [new Promote(new PromoteObjectID("test3", 1))] }, - Conditions = [new Condition { Anchoring = Anchoring.Contains, Context = "shoes" }] - } - ]).ConfigureAwait(false); - } - catch (AlgoliaApiException e) - { - Console.WriteLine($"Message: {e.Message} - Status {e.HttpErrorCode}"); - } - - Console.WriteLine("--- Generate Secured API Keys `GenerateSecuredApiKeys` ---"); - var generateSecuredApiKeys = client.GenerateSecuredApiKey(configuration.SearchApiKey, - new SecuredApiKeyRestriction - { - RestrictIndices = [defaultIndex], - }); - - Console.WriteLine("Calling SearchSingleIndexAsync with generated secured API keys"); - - var searchClient = new SearchClient(configuration.AppId, generateSecuredApiKeys); - await searchClient.SearchSingleIndexAsync(defaultIndex); - - Console.WriteLine("Success, this index is authorized"); - - Console.WriteLine("Calling SearchSingleIndexAsync with not authorized index"); - - try - { - await searchClient.SearchSingleIndexAsync("not_authorized_index"); - } - catch (AlgoliaApiException e) - { - Console.WriteLine($"Error received (It's expected !) - {e.HttpErrorCode} {e.Message}"); - } - - Console.WriteLine("--- Replace all objects `` ---"); - var replaceAllResponse = await client.ReplaceAllObjectsAsync(defaultIndex, - new List() { new TestObject() { Value = "hello2", OtherValue = "world" } }); - Console.WriteLine($"Replace all objects - Async TaskID: `{string.Join(",", replaceAllResponse)}`"); - - Console.WriteLine("Search API playground has ended"); + async () => await _client.WaitForTaskAsync(DefaultIndex, saveRulesAsync.TaskID), "New Rule has been created !"); } } + +public interface IPlayground +{ + Task Run(); +} diff --git a/playground/csharp/Playground/Program.cs b/playground/csharp/Playground/Program.cs index 36d65b01bf..0855389aeb 100644 --- a/playground/csharp/Playground/Program.cs +++ b/playground/csharp/Playground/Program.cs @@ -11,47 +11,60 @@ : "Running playground for Algolia client: " + client); Console.WriteLine("------------------------------------"); - var config = Config.Load(); -switch (client) +await StartPlayground(client, config); + +async Task StartPlayground(string s, Configuration configuration) { - case "abtesting": - await ABTesting.Run(config); - break; - case "analytics": - await Analytics.Run(config); - break; - case "insights": - await Insights.Run(config); - break; - case "monitoring": - await Monitoring.Run(config); - break; - case "personalization": - await Personalization.Run(config); - break; - case "query-suggestions": - await QuerySuggestions.Run(config); - break; - case "recommend": - await Recommend.Run(config); - break; - case "search": - await SearchPlayground.Run(config); - break; - case "ingestion": - await Ingestion.Run(config); - break; - case "all": - await SearchPlayground.Run(config); - await ABTesting.Run(config); - await Analytics.Run(config); - await Insights.Run(config); - await Monitoring.Run(config); - await Personalization.Run(config); - await QuerySuggestions.Run(config); - await Recommend.Run(config); - await Ingestion.Run(config); - break; + switch (s) + { + case "abtesting": + var abTesting = new ABTestingPlayground(configuration); + await abTesting.Run(); + break; + case "analytics": + var analytics = new AnalyticsPlayground(configuration); + await analytics.Run(); + break; + case "insights": + var insights = new InsightsPlayground(configuration); + await insights.Run(); + break; + case "monitoring": + var monitoring = new MonitoringPlayground(configuration); + await monitoring.Run(); + break; + case "personalization": + var personalization = new PersonalizationPlayground(configuration); + await personalization.Run(); + break; + case "query-suggestions": + var querySuggestions = new QuerySuggestionsPlayground(configuration); + await querySuggestions.Run(); + break; + case "recommend": + var recommend = new RecommendPlayground(configuration); + await recommend.Run(); + break; + case "search": + var searchPlayground = new SearchPlayground(configuration); + await searchPlayground.Run(); + break; + case "ingestion": + var ingestion = new IngestionPlayground(configuration); + await ingestion.Run(); + break; + case "all": + await StartPlayground("abtesting", configuration); + await StartPlayground("analytics", configuration); + await StartPlayground("insights", configuration); + await StartPlayground("monitoring", configuration); + await StartPlayground("personalization", configuration); + await StartPlayground("query-suggestions", configuration); + await StartPlayground("recommend", configuration); + await StartPlayground("search", configuration); + await StartPlayground("ingestion", configuration); + break; + } } diff --git a/playground/csharp/Playground/Utils/Configuration.cs b/playground/csharp/Playground/Utils/Configuration.cs index e1b947191b..466b953c7a 100644 --- a/playground/csharp/Playground/Utils/Configuration.cs +++ b/playground/csharp/Playground/Utils/Configuration.cs @@ -6,14 +6,12 @@ public static class Config { public static Configuration Load() { - DotEnv.Load(options: new DotEnvOptions(ignoreExceptions: false, probeForEnv: true, envFilePaths: new[] { "../.env", "./Playground/.env" })); + DotEnv.Load(options: new DotEnvOptions(ignoreExceptions: false, probeForEnv: true, probeLevelsToSearch: 6)); return new Configuration { AppId = GetEnvVariable("ALGOLIA_APPLICATION_ID"), AdminApiKey = GetEnvVariable("ALGOLIA_ADMIN_KEY"), SearchApiKey = GetEnvVariable("ALGOLIA_SEARCH_KEY"), - MetisAppId = GetEnvVariable("ALGOLIA_METIS_APPLICATION_ID"), - MetisApiKey = GetEnvVariable("ALGOLIA_METIS_API_KEY"), MonitoringApiKey = GetEnvVariable("MONITORING_KEY"), }; } diff --git a/playground/csharp/Playground/Utils/PlaygroundHelper.cs b/playground/csharp/Playground/Utils/PlaygroundHelper.cs index cfc5e2286c..309ad74666 100644 --- a/playground/csharp/Playground/Utils/PlaygroundHelper.cs +++ b/playground/csharp/Playground/Utils/PlaygroundHelper.cs @@ -15,4 +15,15 @@ public static async Task Start(string startMessage, Func> ac, stri Console.WriteLine(endMessage); return waitResult; } + + public static void Hello(string startMessage) + { + var currentForegroundColor = Console.ForegroundColor; + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("------------------------------------"); + Console.WriteLine($"| {startMessage} |"); + Console.WriteLine("------------------------------------"); + Console.ForegroundColor = currentForegroundColor; + } + }