Skip to content

Commit

Permalink
refactor(csharp): Playground (#2744)
Browse files Browse the repository at this point in the history
  • Loading branch information
morganleroi authored Feb 20, 2024
1 parent 360eb00 commit 68551ff
Show file tree
Hide file tree
Showing 16 changed files with 444 additions and 264 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -190,9 +190,9 @@ private async Task<TResult> ExecuteRequestAsync<TResult, TData>(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);
Expand Down
2 changes: 0 additions & 2 deletions playground/csharp/Playground/.env.example

This file was deleted.

3 changes: 1 addition & 2 deletions playground/csharp/Playground/Model/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
}
6 changes: 0 additions & 6 deletions playground/csharp/Playground/Playground.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,4 @@
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0"/>
</ItemGroup>

<ItemGroup>
<None Update=".env">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
42 changes: 32 additions & 10 deletions playground/csharp/Playground/Playgrounds/ABTesting.cs
Original file line number Diff line number Diff line change
@@ -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<AddABTestsVariant> { 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);
}
}
}
37 changes: 27 additions & 10 deletions playground/csharp/Playground/Playgrounds/Analytics.cs
Original file line number Diff line number Diff line change
@@ -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
}
}
}
74 changes: 47 additions & 27 deletions playground/csharp/Playground/Playgrounds/Ingestion.cs
Original file line number Diff line number Diff line change
@@ -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> { 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
}
}
}
43 changes: 29 additions & 14 deletions playground/csharp/Playground/Playgrounds/Insights.cs
Original file line number Diff line number Diff line change
@@ -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<EventsItems>()
try
{
new(new ConvertedObjectIDs("Buy event", ConversionEvent.Conversion, "test",
new List<string> { "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);
}
}


}
46 changes: 32 additions & 14 deletions playground/csharp/Playground/Playgrounds/Monitoring.cs
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
31 changes: 25 additions & 6 deletions playground/csharp/Playground/Playgrounds/Personalization.cs
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
Loading

0 comments on commit 68551ff

Please sign in to comment.