diff --git a/cli/Squidex.CLI/Directory.Build.props b/cli/Squidex.CLI/Directory.Build.props
index 836ab765..472b1be7 100644
--- a/cli/Squidex.CLI/Directory.Build.props
+++ b/cli/Squidex.CLI/Directory.Build.props
@@ -15,6 +15,6 @@
Squidex HeadlessCMS
true
snupkg
- 9.6
+ 10.0
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/ISession.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/ISession.cs
index 6a16d9e7..5519e848 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/ISession.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/ISession.cs
@@ -6,7 +6,6 @@
// ==========================================================================
using Squidex.ClientLibrary;
-using Squidex.ClientLibrary.Management;
namespace Squidex.CLI.Commands.Implementation;
@@ -22,17 +21,5 @@ public interface ISession
DirectoryInfo WorkingDirectory { get; }
- IAppsClient Apps { get; }
-
- IAssetsClient Assets { get; }
-
- IBackupsClient Backups { get; }
-
- ISchemasClient Schemas { get; }
-
- IExtendableRulesClient Rules { get; }
-
- IContentsClient Contents(string schemaName) where TEntity : Content where TData : class, new();
-
- IContentsClient Contents(string schemaName);
+ ISquidexClient Client { get; }
}
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/ImExport/ExportHelper.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/ImExport/ExportHelper.cs
index b351ce49..d63520e7 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/ImExport/ExportHelper.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/ImExport/ExportHelper.cs
@@ -15,7 +15,7 @@ public static async Task ExportAsync(this ISession session, IExportSettings sett
{
var ctx = QueryContext.Default.Unpublished(settings.Unpublished);
- var contents = session.Contents(settings.Schema);
+ var contents = session.Client.DynamicContents(settings.Schema);
var total = 0L;
var totalRead = 0;
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/ImExport/ImportHelper.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/ImExport/ImportHelper.cs
index c1f56bce..505c4af1 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/ImExport/ImportHelper.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/ImExport/ImportHelper.cs
@@ -21,7 +21,7 @@ public static class ImportHelper
{
public static async Task ImportAsync(this ISession session, IImportSettings setting, ILogger log, IEnumerable datas)
{
- var contents = session.Contents(setting.Schema);
+ var contents = session.Client.DynamicContents(setting.Schema);
var totalWritten = 0;
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/App/AppSynchronizer.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/App/AppSynchronizer.cs
index 10856e4d..878a1d16 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/App/AppSynchronizer.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/App/AppSynchronizer.cs
@@ -39,7 +39,7 @@ public async Task ExportAsync(ISyncService sync, SyncOptions options, ISession s
await log.DoSafeAsync("Exporting clients", async () =>
{
- var clients = await session.Apps.GetClientsAsync(session.App);
+ var clients = await session.Client.Apps.GetClientsAsync();
model.Clients = new Dictionary();
@@ -51,7 +51,7 @@ await log.DoSafeAsync("Exporting clients", async () =>
await log.DoSafeAsync("Exporting languages", async () =>
{
- var languages = await session.Apps.GetLanguagesAsync(session.App);
+ var languages = await session.Client.Apps.GetLanguagesAsync();
model.Languages = new Dictionary();
@@ -63,7 +63,7 @@ await log.DoSafeAsync("Exporting languages", async () =>
await log.DoSafeAsync("Exporting Roles", async () =>
{
- var roles = await session.Apps.GetRolesAsync(session.App);
+ var roles = await session.Client.Apps.GetRolesAsync();
model.Roles = new Dictionary();
@@ -75,7 +75,7 @@ await log.DoSafeAsync("Exporting Roles", async () =>
await log.DoSafeAsync("Exporting asset scripts", async () =>
{
- var assetScripts = await session.Apps.GetAssetScriptsAsync(session.App);
+ var assetScripts = await session.Client.Apps.GetAssetScriptsAsync();
model.AssetScripts = assetScripts.ToModel();
});
@@ -160,14 +160,14 @@ await log.DoSafeAsync($"Contributor '{email}' creating", async () =>
{
var request = new AssignContributorDto { ContributorId = email, Role = value.Role, Invite = true };
- await session.Apps.PostContributorAsync(session.App, request);
+ await session.Client.Apps.PostContributorAsync(request);
});
}
}
private async Task SynchronizeClientsAsync(AppModel model, SyncOptions options, ISession session)
{
- var current = await session.Apps.GetClientsAsync(session.App);
+ var current = await session.Client.Apps.GetClientsAsync();
if (options.Delete)
{
@@ -182,7 +182,7 @@ private async Task SynchronizeClientsAsync(AppModel model, SyncOptions options,
await log.DoSafeAsync($"Client '{client.Id}' deleting", async () =>
{
- await session.Apps.DeleteClientAsync(session.App, client.Id);
+ await session.Client.Apps.DeleteClientAsync(client.Id);
});
}
}
@@ -200,7 +200,7 @@ await log.DoSafeAsync($"Client '{clientId}' creating", async () =>
{
var request = new CreateClientDto { Id = clientId };
- current = await session.Apps.PostClientAsync(session.App, request);
+ current = await session.Client.Apps.PostClientAsync(request);
});
}
@@ -222,14 +222,14 @@ await log.DoSafeAsync($"Client '{clientId}' updating", async () =>
{
var request = client.ToUpdate();
- await session.Apps.PutClientAsync(session.App, clientId, request);
+ await session.Client.Apps.PutClientAsync(clientId, request);
});
}
}
private async Task SynchronizeLanguagesAsync(AppModel model, SyncOptions options, ISession session)
{
- var current = await session.Apps.GetLanguagesAsync(session.App);
+ var current = await session.Client.Apps.GetLanguagesAsync();
if (options.Delete)
{
@@ -242,7 +242,7 @@ private async Task SynchronizeLanguagesAsync(AppModel model, SyncOptions options
await log.DoSafeAsync($"Language '{language.Iso2Code}' deleting", async () =>
{
- await session.Apps.DeleteLanguageAsync(session.App, language.Iso2Code);
+ await session.Client.Apps.DeleteLanguageAsync(language.Iso2Code);
});
}
}
@@ -260,7 +260,7 @@ await log.DoSafeAsync($"Language '{isoCode}' creating", async () =>
{
var request = new AddLanguageDto { Language = isoCode };
- current = await session.Apps.PostLanguageAsync(session.App, request);
+ current = await session.Client.Apps.PostLanguageAsync(request);
});
}
@@ -275,14 +275,14 @@ await log.DoSafeAsync($"Language '{isoCode}' creating", async () =>
await log.DoSafeAsync($"Language '{isoCode}' updating", async () =>
{
- await session.Apps.PutLanguageAsync(session.App, isoCode, language);
+ await session.Client.Apps.PutLanguageAsync(isoCode, language);
});
}
}
private async Task SynchronizeRolesAsync(AppModel model, SyncOptions options, ISession session)
{
- var current = await session.Apps.GetRolesAsync(session.App);
+ var current = await session.Client.Apps.GetRolesAsync();
if (options.Delete)
{
@@ -298,7 +298,7 @@ private async Task SynchronizeRolesAsync(AppModel model, SyncOptions options, IS
await log.DoSafeAsync($"Role '{role.Name}' deleting", async () =>
{
- await session.Apps.DeleteRoleAsync(session.App, role.Name);
+ await session.Client.Apps.DeleteRoleAsync(role.Name);
});
}
}
@@ -316,7 +316,7 @@ await log.DoSafeAsync($"Role '{roleName}' creating", async () =>
{
var request = new AddRoleDto { Name = roleName };
- current = await session.Apps.PostRoleAsync(session.App, request);
+ current = await session.Client.Apps.PostRoleAsync(request);
});
}
@@ -333,7 +333,7 @@ await log.DoSafeAsync($"Role '{roleName}' updating", async () =>
{
var request = role.ToUpdate();
- await session.Apps.PutRoleAsync(session.App, roleName, request);
+ await session.Client.Apps.PutRoleAsync(roleName, request);
});
}
}
@@ -349,7 +349,7 @@ await log.DoSafeAsync("Asset scripts updating", async () =>
{
var request = model.AssetScripts?.ToUpdate() ?? new UpdateAssetScriptsDto();
- await session.Apps.PutAssetScriptsAsync(session.App, request);
+ await session.Client.Apps.PutAssetScriptsAsync(request);
});
}
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Assets/AssetsSynchronizer.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Assets/AssetsSynchronizer.cs
index d4800de5..3362e5ff 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Assets/AssetsSynchronizer.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Assets/AssetsSynchronizer.cs
@@ -61,7 +61,7 @@ await log.DoSafeAsync($"Exporting Assets ({assetBatch})", async () =>
});
}
- await session.Assets.GetAllAsync(session.App, async asset =>
+ await session.Client.Assets.GetAllAsync(async asset =>
{
var model = asset.ToModel();
@@ -143,7 +143,7 @@ public async Task ImportAsync(ISyncService sync, SyncOptions options, ISession s
var assetIndex = 0;
- var results = await session.Assets.BulkUpdateAssetsAsync(session.App, request);
+ var results = await session.Client.Assets.BulkUpdateAssetsAsync(request);
foreach (var asset in model.Assets)
{
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Assets/DownloadPipeline.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Assets/DownloadPipeline.cs
index cfde2c16..1b60341f 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Assets/DownloadPipeline.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Assets/DownloadPipeline.cs
@@ -64,7 +64,7 @@ public DownloadPipeline(ISession session, ILogger log, IFileSystem fs)
if (assetHash == null || !string.Equals(asset.FileHash, assetHash, StringComparison.Ordinal))
{
- var response = await session.Assets.GetAssetContentBySlugAsync(session.App, asset.Id, string.Empty);
+ var response = await session.Client.Assets.GetAssetContentBySlugAsync(asset.Id, string.Empty);
await using (response.Stream)
{
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Assets/UploadPipeline.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Assets/UploadPipeline.cs
index 9eda2fd4..579e77b3 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Assets/UploadPipeline.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Assets/UploadPipeline.cs
@@ -24,7 +24,7 @@ internal sealed class UploadPipeline
public UploadPipeline(ISession session, ILogger log, IFileSystem fs)
{
- var tree = new AssetFolderTree(session.Assets, session.App);
+ var tree = new AssetFolderTree(session.Client.Assets);
var fileNameStep = new TransformBlock(async asset =>
{
@@ -68,7 +68,7 @@ public UploadPipeline(ISession session, ILogger log, IFileSystem fs)
{
var file = new FileParameter(stream, asset.FileName, asset.MimeType);
- var result = await session.Assets.PostUpsertAssetAsync(session.App, asset.Id, null, true, file);
+ var result = await session.Client.Assets.PostUpsertAssetAsync(asset.Id, null, true, file);
log.ProcessCompleted(process);
}
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Contents/ContentsSynchronizer.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Contents/ContentsSynchronizer.cs
index e7770635..ba1af65b 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Contents/ContentsSynchronizer.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Contents/ContentsSynchronizer.cs
@@ -37,14 +37,14 @@ public Task CleanupAsync(IFileSystem fs)
public async Task ExportAsync(ISyncService sync, SyncOptions options, ISession session)
{
- var schemas = await session.Schemas.GetSchemasAsync(session.App);
+ var schemas = await session.Client.Schemas.GetSchemasAsync();
var schemaMap = schemas.Items.ToDictionary(x => x.Id, x => x.Name);
var context = QueryContext.Default.Unpublished().IgnoreFallback();
foreach (var schema in schemas.Items)
{
- var client = session.Contents(schema.Name);
+ var client = session.Client.DynamicContents(schema.Name);
var contents = new List();
var contentBatch = 0;
@@ -114,7 +114,7 @@ public async Task ImportAsync(ISyncService sync, SyncOptions options, ISession s
GetFiles(sync.FileSystem)
.Select(x => (x, sync.Read(x, log)));
- var schemas = await session.Schemas.GetSchemasAsync(session.App);
+ var schemas = await session.Client.Schemas.GetSchemasAsync();
var schemaMap = schemas.Items.ToDictionary(x => x.Name, x => x.Id);
var mapper = new Extensions.Mapper(session.Url, session.App, options.Languages);
@@ -125,7 +125,7 @@ public async Task ImportAsync(ISyncService sync, SyncOptions options, ISession s
{
mapper.Map(model);
- var client = session.Contents(model.Contents[0].Schema);
+ var client = session.Client.DynamicContents(model.Contents[0].Schema);
var request = new BulkUpdate
{
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Rules/RulesSynchronizer.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Rules/RulesSynchronizer.cs
index 5494ab72..cf424702 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Rules/RulesSynchronizer.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Rules/RulesSynchronizer.cs
@@ -38,7 +38,7 @@ public Task CleanupAsync(IFileSystem fs)
public async Task ExportAsync(ISyncService sync, SyncOptions options, ISession session)
{
- var current = await session.Rules.GetRulesAsync();
+ var current = await session.Client.ExtendableRules.GetRulesAsync();
await MapSchemaIdsToNamesAsync(session, current);
@@ -90,7 +90,7 @@ public async Task ImportAsync(ISyncService sync, SyncOptions options, ISession s
return;
}
- var current = await session.Rules.GetRulesAsync();
+ var current = await session.Client.ExtendableRules.GetRulesAsync();
if (!current.Items.HasDistinctNames(x => x.Name))
{
@@ -108,7 +108,7 @@ public async Task ImportAsync(ISyncService sync, SyncOptions options, ISession s
{
await log.DoSafeAsync($"Rule '{name}' deleting", async () =>
{
- await session.Rules.DeleteRuleAsync(rule.Id);
+ await session.Client.ExtendableRules.DeleteRuleAsync(rule.Id);
rulesByName.Remove(name);
});
@@ -134,7 +134,7 @@ await log.DoSafeAsync($"Rule '{newRule.Name}' creating", async () =>
var request = newRule.ToCreate();
- var created = await session.Rules.CreateRuleAsync(request);
+ var created = await session.Client.ExtendableRules.CreateRuleAsync(request);
rulesByName[newRule.Name] = created;
});
@@ -153,7 +153,7 @@ await log.DoVersionedAsync($"Rule '{newRule.Name}' updating", rule.Version, asyn
{
var request = newRule.ToUpdate();
- rule = await session.Rules.UpdateRuleAsync(rule.Id, request);
+ rule = await session.Client.ExtendableRules.UpdateRuleAsync(rule.Id, request);
return rule.Version;
});
@@ -164,7 +164,7 @@ await log.DoVersionedAsync($"Rule '{newRule.Name}' updating", rule.Version, asyn
{
await log.DoVersionedAsync($"Rule '{newRule.Name}' enabling", rule.Version, async () =>
{
- var result = await session.Rules.EnableRuleAsync(rule.Id);
+ var result = await session.Client.ExtendableRules.EnableRuleAsync(rule.Id);
return result.Version;
});
@@ -173,7 +173,7 @@ await log.DoVersionedAsync($"Rule '{newRule.Name}' enabling", rule.Version, asyn
{
await log.DoVersionedAsync($"Rule '{newRule.Name}' disabling", rule.Version, async () =>
{
- var result = await session.Rules.DisableRuleAsync(rule.Id);
+ var result = await session.Client.ExtendableRules.DisableRuleAsync(rule.Id);
return result.Version;
});
@@ -184,7 +184,7 @@ await log.DoVersionedAsync($"Rule '{newRule.Name}' disabling", rule.Version, asy
private async Task MapSchemaIdsToNamesAsync(ISession session, ExtendableRules current)
{
- var schemas = await session.Schemas.GetSchemasAsync(session.App);
+ var schemas = await session.Client.Schemas.GetSchemasAsync();
var map = schemas.Items.ToDictionary(x => x.Id, x => x.Name);
@@ -200,7 +200,7 @@ private async Task MapSchemaIdsToNamesAsync(ISession session, ExtendableRules cu
private async Task MapSchemaNamesToIdsAsync(ISession session, List models)
{
- var schemas = await session.Schemas.GetSchemasAsync(session.App);
+ var schemas = await session.Client.Schemas.GetSchemasAsync();
var map = schemas.Items.ToDictionary(x => x.Name, x => x.Id);
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Schemas/SchemasSynchronizer.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Schemas/SchemasSynchronizer.cs
index e83afe17..c0f1241b 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Schemas/SchemasSynchronizer.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Schemas/SchemasSynchronizer.cs
@@ -60,7 +60,7 @@ public Task DescribeAsync(ISyncService sync, MarkdownWriter writer)
public async Task ExportAsync(ISyncService sync, SyncOptions options, ISession session)
{
- var current = await session.Schemas.GetSchemasAsync(session.App);
+ var current = await session.Client.Schemas.GetSchemasAsync();
var schemaMap = current.Items.ToDictionary(x => x.Id, x => x.Name);
@@ -68,7 +68,7 @@ public async Task ExportAsync(ISyncService sync, SyncOptions options, ISession s
{
await log.DoSafeAsync($"Exporting '{schema.Name}'", async () =>
{
- var details = await session.Schemas.GetSchemaAsync(session.App, schema.Name);
+ var details = await session.Client.Schemas.GetSchemaAsync(schema.Name);
var model = new SchemaModel
{
@@ -99,7 +99,7 @@ public async Task ImportAsync(ISyncService sync, SyncOptions options, ISession s
return;
}
- var current = await session.Schemas.GetSchemasAsync(session.App);
+ var current = await session.Client.Schemas.GetSchemasAsync();
var schemasByName = current.Items.ToDictionary(x => x.Name);
@@ -111,7 +111,7 @@ public async Task ImportAsync(ISyncService sync, SyncOptions options, ISession s
{
await log.DoSafeAsync($"Schema {name} deleting", async () =>
{
- await session.Schemas.DeleteSchemaAsync(session.App, name);
+ await session.Client.Schemas.DeleteSchemaAsync(name);
});
}
}
@@ -126,7 +126,7 @@ await log.DoSafeAsync($"Schema {name} deleting", async () =>
await log.DoSafeAsync($"Schema {model.Name} creating", async () =>
{
- var created = await session.Schemas.PostSchemaAsync(session.App, model.ToCreate());
+ var created = await session.Client.Schemas.PostSchemaAsync(model.ToCreate());
schemasByName[model.Name] = created;
});
@@ -151,7 +151,7 @@ await log.DoSafeAsync($"Schema {model.Name} creating", async () =>
await log.DoVersionedAsync($"Schema {model.Name} updating", version, async () =>
{
- var result = await session.Schemas.PutSchemaSyncAsync(session.App, model.Name, model.Schema);
+ var result = await session.Client.Schemas.PutSchemaSyncAsync(model.Name, model.Schema);
return result.Version;
});
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/SyncService.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/SyncService.cs
index f39d345b..b940bee6 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/SyncService.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/SyncService.cs
@@ -42,7 +42,7 @@ protected override JsonDictionaryContract CreateDictionaryContract(Type objectTy
public SyncService(IFileSystem fileSystem, ISession session)
{
- Folders = new AssetFolderTree(session.Assets, session.App);
+ Folders = new AssetFolderTree(session.Client.Assets);
jsonSerializerSettings = new JsonSerializerSettings
{
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Workflows/WorkflowsSynchronizer.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Workflows/WorkflowsSynchronizer.cs
index 7d296b57..eb329ee5 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Workflows/WorkflowsSynchronizer.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Commands/Implementation/Sync/Workflows/WorkflowsSynchronizer.cs
@@ -37,9 +37,9 @@ public Task CleanupAsync(IFileSystem fs)
public async Task ExportAsync(ISyncService sync, SyncOptions options, ISession session)
{
- var current = await session.Apps.GetWorkflowsAsync(session.App);
+ var current = await session.Client.Apps.GetWorkflowsAsync();
- var schemas = await session.Schemas.GetSchemasAsync(session.App);
+ var schemas = await session.Client.Schemas.GetSchemasAsync();
var schemaMap = schemas.Items.ToDictionary(x => x.Id, x => x.Name);
await current.Items.OrderBy(x => x.Name).Foreach(async (workflow, i) =>
@@ -87,7 +87,7 @@ public async Task ImportAsync(ISyncService sync, SyncOptions options, ISession s
return;
}
- var current = await session.Apps.GetWorkflowsAsync(session.App);
+ var current = await session.Client.Apps.GetWorkflowsAsync();
if (!current.Items.HasDistinctNames(x => x.Name))
{
@@ -105,7 +105,7 @@ public async Task ImportAsync(ISyncService sync, SyncOptions options, ISession s
{
await log.DoSafeAsync($"Workflow '{name}' deleting", async () =>
{
- await session.Apps.DeleteWorkflowAsync(session.App, workflow.Id);
+ await session.Client.Apps.DeleteWorkflowAsync(workflow.Id);
workflowsByName.Remove(name);
});
@@ -132,13 +132,13 @@ await log.DoSafeAsync($"Workflow '{workflow.Name}' creating", async () =>
Name = workflow.Name
};
- var created = await session.Apps.PostWorkflowAsync(session.App, request);
+ var created = await session.Client.Apps.PostWorkflowAsync(request);
workflowsByName[workflow.Name] = created.Items.Find(x => x.Name == workflow.Name);
});
}
- var schemas = await session.Schemas.GetSchemasAsync(session.App);
+ var schemas = await session.Client.Schemas.GetSchemasAsync();
var schemaMap = schemas.Items.ToDictionary(x => x.Name, x => x.Id);
foreach (var workflow in models)
@@ -154,7 +154,7 @@ await log.DoSafeAsync($"Workflow '{workflow.Name}' creating", async () =>
await log.DoSafeAsync($"Workflow '{workflow.Name}' updating", async () =>
{
- await session.Apps.PutWorkflowAsync(session.App, existing.Id, workflow);
+ await session.Client.Apps.PutWorkflowAsync(existing.Id, workflow);
});
}
}
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/ConfigurationService.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/ConfigurationService.cs
index b3882528..3f3953c6 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/ConfigurationService.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/ConfigurationService.cs
@@ -9,7 +9,6 @@
using Squidex.CLI.Commands.Implementation;
using Squidex.CLI.Commands.Implementation.Utils;
using Squidex.ClientLibrary;
-using Squidex.ClientLibrary.Configuration;
namespace Squidex.CLI.Configuration;
@@ -168,14 +167,14 @@ public ISession StartSession(string appName, bool emulate = false)
{
var options = CreateOptions(app, emulate);
- return new Session(app.Name, WorkingDirectory, new SquidexClientManager(options));
+ return new Session(WorkingDirectory, new SquidexClient(options));
}
if (!string.IsNullOrWhiteSpace(configuration.CurrentApp) && configuration.Apps.TryGetValue(configuration.CurrentApp, out app))
{
var options = CreateOptions(app, emulate);
- return new Session(app.Name, WorkingDirectory, new SquidexClientManager(options));
+ return new Session(WorkingDirectory, new SquidexClient(options));
}
throw new CLIException("Cannot find valid configuration.");
@@ -185,21 +184,17 @@ private static SquidexOptions CreateOptions(ConfiguredApp app, bool emulate)
{
var options = new SquidexOptions
{
+ IgnoreSelfSignedCertificates = app.IgnoreSelfSigned,
AppName = app.Name,
ClientId = app.ClientId,
ClientSecret = app.ClientSecret,
Url = app.ServiceUrl,
- HttpClientTimeout = TimeSpan.FromHours(1)
+ Timeout = TimeSpan.FromHours(1)
};
- if (app.IgnoreSelfSigned)
- {
- options.Configurator = AcceptAllCertificatesConfigurator.Instance;
- }
-
if (emulate)
{
- options.ClientFactory = new GetOnlyHttpClientFactory();
+ options.ClientProvider = new GetOnlyHttpClientProvider(options);
}
return options;
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/GetOnlyHttpClient.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/GetOnlyHttpClient.cs
index 324a881a..f0b47d8a 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/GetOnlyHttpClient.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/GetOnlyHttpClient.cs
@@ -9,14 +9,10 @@
namespace Squidex.CLI.Configuration;
-public sealed class GetOnlyHttpClient : HttpClient
+public sealed class GetOnlyHttpMessageHandler : DelegatingHandler
{
- public GetOnlyHttpClient(HttpMessageHandler messageHandler)
- : base(messageHandler)
- {
- }
-
- public override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken)
+ protected override HttpResponseMessage Send(HttpRequestMessage request,
+ CancellationToken cancellationToken)
{
if (request.Method != HttpMethod.Get)
{
@@ -26,7 +22,8 @@ public override HttpResponseMessage Send(HttpRequestMessage request, Cancellatio
return base.Send(request, cancellationToken);
}
- public override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ protected override Task SendAsync(HttpRequestMessage request,
+ CancellationToken cancellationToken)
{
if (request.Method != HttpMethod.Get)
{
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/GetOnlyHttpClientFactory.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/GetOnlyHttpClientFactory.cs
index 7826f7b4..990c8ce0 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/GetOnlyHttpClientFactory.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/GetOnlyHttpClientFactory.cs
@@ -5,19 +5,27 @@
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
+using Google.Protobuf.WellKnownTypes;
+using Squidex.ClientLibrary;
using Squidex.ClientLibrary.Configuration;
+using Squidex.ClientLibrary.Utils;
namespace Squidex.CLI.Configuration;
-public sealed class GetOnlyHttpClientFactory : IHttpClientFactory
+public sealed class GetOnlyHttpClientProvider : StaticHttpClientProvider
{
- public HttpClient? CreateHttpClient(HttpMessageHandler messageHandler)
+ public GetOnlyHttpClientProvider(SquidexOptions options)
+ : base(options)
{
- return new GetOnlyHttpClient(messageHandler);
}
- public HttpMessageHandler? CreateHttpMessageHandler(HttpMessageHandler inner)
+ protected override HttpMessageHandler CreateMessageHandler(SquidexOptions options)
{
- return null;
+ var baseHandler = base.CreateMessageHandler(options);
+
+ return new GetOnlyHttpMessageHandler
+ {
+ InnerHandler = baseHandler
+ };
}
}
diff --git a/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/Session.cs b/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/Session.cs
index bc1ff860..7962091c 100644
--- a/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/Session.cs
+++ b/cli/Squidex.CLI/Squidex.CLI.Core/Configuration/Session.cs
@@ -7,87 +7,27 @@
using Squidex.CLI.Commands.Implementation;
using Squidex.ClientLibrary;
-using Squidex.ClientLibrary.Management;
namespace Squidex.CLI.Configuration;
public sealed class Session : ISession
{
- private readonly SquidexClientManager clientManager;
- private readonly Dictionary> contents = new Dictionary>();
- private IAppsClient apps;
- private IAssetsClient assets;
- private IBackupsClient backups;
- private ISchemasClient schemas;
- private IExtendableRulesClient rules;
-
- public string App { get; }
-
public DirectoryInfo WorkingDirectory { get; }
- public IAppsClient Apps
- {
- get => apps ??= clientManager.CreateAppsClient();
- }
-
- public IAssetsClient Assets
- {
- get => assets ??= clientManager.CreateAssetsClient();
- }
+ public ISquidexClient Client { get; }
- public IBackupsClient Backups
- {
- get => backups ??= clientManager.CreateBackupsClient();
- }
-
- public IExtendableRulesClient Rules
- {
- get => rules ??= clientManager.CreateExtendableRulesClient();
- }
-
- public ISchemasClient Schemas
- {
- get => schemas ??= clientManager.CreateSchemasClient();
- }
+ public string App => Client.Options.AppName;
- public string ClientId
- {
- get => clientManager.Options.ClientId;
- }
+ public string ClientId => Client.Options.ClientId;
- public string ClientSecret
- {
- get => clientManager.Options.ClientSecret;
- }
+ public string ClientSecret => Client.Options.ClientSecret;
- public string Url
- {
- get => clientManager.Options.Url;
- }
+ public string Url => Client.Options.Url;
- public Session(string app, DirectoryInfo workingDirectory, SquidexClientManager clientManager)
+ public Session(DirectoryInfo workingDirectory, ISquidexClient client)
{
- App = app;
-
WorkingDirectory = workingDirectory;
- this.clientManager = clientManager;
- }
-
- public IContentsClient Contents(string schemaName) where TEntity : Content where TData : class, new()
- {
- return clientManager.CreateContentsClient(schemaName);
- }
-
- public IContentsClient Contents(string schemaName)
- {
- if (!contents.TryGetValue(schemaName, out var client))
- {
- client = clientManager.CreateDynamicContentsClient(schemaName);
-
- contents[schemaName] = client;
- }
-
- return client;
+ Client = client;
}
}
diff --git a/cli/Squidex.CLI/Squidex.CLI/Commands/App_Apps.cs b/cli/Squidex.CLI/Squidex.CLI/Commands/App_Apps.cs
index b356b89d..63c5c13f 100644
--- a/cli/Squidex.CLI/Squidex.CLI/Commands/App_Apps.cs
+++ b/cli/Squidex.CLI/Squidex.CLI/Commands/App_Apps.cs
@@ -35,7 +35,7 @@ public async Task List(ListArguments arguments)
{
var session = configuration.StartSession(arguments.App);
- var apps = await session.Apps.GetAppsAsync();
+ var apps = await session.Client.Apps.GetAppsAsync();
if (arguments.Table)
{
@@ -71,7 +71,7 @@ public async Task Create(CreateArguments arguments)
Name = name
};
- await session.Apps.PostAppAsync(request);
+ await session.Client.Apps.PostAppAsync(request);
log.WriteLine("> App created.");
}
@@ -93,7 +93,7 @@ public async Task Delete(DeleteArguments arguments)
throw new CLIException("Confirmed app name does not match.");
}
- await session.Apps.DeleteAppAsync(name);
+ await session.Client.Apps.DeleteAppAsync();
log.WriteLine("> App deleted.");
}
diff --git a/cli/Squidex.CLI/Squidex.CLI/Commands/App_Assets.cs b/cli/Squidex.CLI/Squidex.CLI/Commands/App_Assets.cs
index e8626c40..14f14b67 100644
--- a/cli/Squidex.CLI/Squidex.CLI/Commands/App_Assets.cs
+++ b/cli/Squidex.CLI/Squidex.CLI/Commands/App_Assets.cs
@@ -38,11 +38,9 @@ public async Task Import(ImportArguments arguments)
{
var session = configuration.StartSession(arguments.App);
- var assets = session.Assets;
-
using (var fs = await FileSystems.CreateAsync(arguments.Path))
{
- var folders = new AssetFolderTree(session.Assets, session.App);
+ var folders = new AssetFolderTree(session.Client.Assets);
var assetQuery = new AssetQuery();
@@ -58,7 +56,7 @@ public async Task Import(ImportArguments arguments)
assetQuery.ParentId = await folders.GetIdAsync(targetFolder);
assetQuery.Filter = $"fileName eq '{file.Name}'";
- var existings = await assets.GetAssetsAsync(session.App, assetQuery);
+ var existings = await session.Client.Assets.GetAssetsAsync(assetQuery);
var existing = existings.Items.FirstOrDefault();
var fileHash = file.GetFileHash();
@@ -79,13 +77,13 @@ public async Task Import(ImportArguments arguments)
}
else if (existing != null)
{
- await assets.PutAssetContentAsync(session.App, existing.Id, fileParameter);
+ await session.Client.Assets.PutAssetContentAsync(existing.Id, fileParameter);
log.StepSuccess("Existing Asset");
}
else
{
- var result = await assets.PostAssetAsync(session.App, assetQuery.ParentId, null, arguments.Duplicate, fileParameter);
+ var result = await session.Client.Assets.PostAssetAsync(assetQuery.ParentId, null, arguments.Duplicate, fileParameter);
if (result._meta?.IsDuplicate == "true")
{
@@ -116,11 +114,9 @@ public async Task Export(ImportArguments arguments)
{
var session = configuration.StartSession(arguments.App);
- var assets = session.Assets;
-
using (var fs = await FileSystems.CreateAsync(arguments.Path))
{
- var folderTree = new AssetFolderTree(session.Assets, session.App);
+ var folderTree = new AssetFolderTree(session.Client.Assets);
var folderNames = new HashSet();
var parentId = await folderTree.GetIdAsync(arguments.TargetFolder);
@@ -148,7 +144,7 @@ public async Task Export(ImportArguments arguments)
try
{
- await assets.GetAllByQueryAsync(session.App, async asset =>
+ await session.Client.Assets.GetAllByQueryAsync(async asset =>
{
await downloadPipeline.DownloadAsync(asset);
},
diff --git a/cli/Squidex.CLI/Squidex.CLI/Commands/App_Backup.cs b/cli/Squidex.CLI/Squidex.CLI/Commands/App_Backup.cs
index cdbd3408..bb1dcf31 100644
--- a/cli/Squidex.CLI/Squidex.CLI/Commands/App_Backup.cs
+++ b/cli/Squidex.CLI/Squidex.CLI/Commands/App_Backup.cs
@@ -36,7 +36,7 @@ public async Task Create(CreateArguments arguments)
var backupStarted = DateTime.UtcNow.AddMinutes(-5);
- await session.Backups.PostBackupAsync(session.App);
+ await session.Client.Backups.PostBackupAsync();
log.WriteLine("Backup started, waiting for completion...");
@@ -46,7 +46,7 @@ public async Task Create(CreateArguments arguments)
{
while (!tcs.Token.IsCancellationRequested)
{
- var backups = await session.Backups.GetBackupsAsync(session.App, tcs.Token);
+ var backups = await session.Client.Backups.GetBackupsAsync(tcs.Token);
var backup = backups.Items.Find(x => x.Started >= backupStarted);
if (backup?.Stopped != null)
@@ -69,7 +69,7 @@ public async Task Create(CreateArguments arguments)
await using (var fs = new FileStream(arguments.File, FileMode.CreateNew))
{
- using (var download = await session.Backups.GetBackupContentAsync(session.App, foundBackup.Id))
+ using (var download = await session.Client.Backups.GetBackupContentAsync(foundBackup.Id))
{
await download.Stream.CopyToAsync(fs);
}
@@ -79,7 +79,7 @@ public async Task Create(CreateArguments arguments)
{
log.WriteLine("Removing backup from app...");
- await session.Backups.DeleteBackupAsync(session.App, foundBackup.Id);
+ await session.Client.Backups.DeleteBackupAsync(foundBackup.Id);
}
log.WriteLine("> Backup completed and downloaded");
diff --git a/cli/Squidex.CLI/Squidex.CLI/Commands/App_Content.cs b/cli/Squidex.CLI/Squidex.CLI/Commands/App_Content.cs
index d7b48d06..0190f263 100644
--- a/cli/Squidex.CLI/Squidex.CLI/Commands/App_Content.cs
+++ b/cli/Squidex.CLI/Squidex.CLI/Commands/App_Content.cs
@@ -42,8 +42,8 @@ public async Task TestData(TestDataArguments arguments)
{
var session = configuration.StartSession(arguments.App);
- var taskForSchema = session.Schemas.GetSchemaAsync(session.App, arguments.Schema);
- var taskForLanguages = session.Apps.GetLanguagesAsync(session.App);
+ var taskForSchema = session.Client.Schemas.GetSchemaAsync(arguments.Schema);
+ var taskForLanguages = session.Client.Apps.GetLanguagesAsync();
await Task.WhenAll(
taskForSchema,
diff --git a/cli/Squidex.CLI/Squidex.CLI/Commands/App_Schemas.cs b/cli/Squidex.CLI/Squidex.CLI/Commands/App_Schemas.cs
index d2e12041..c622315e 100644
--- a/cli/Squidex.CLI/Squidex.CLI/Commands/App_Schemas.cs
+++ b/cli/Squidex.CLI/Squidex.CLI/Commands/App_Schemas.cs
@@ -39,7 +39,7 @@ public async Task List(ListArguments arguments)
{
var session = configuration.StartSession(arguments.App);
- var schemas = await session.Schemas.GetSchemasAsync(session.App);
+ var schemas = await session.Client.Schemas.GetSchemasAsync();
if (arguments.Table)
{
@@ -63,11 +63,11 @@ public async Task Get(GetArguments arguments)
{
var session = configuration.StartSession(arguments.App);
- var schema = await session.Schemas.GetSchemaAsync(session.App, arguments.Name);
+ var schema = await session.Client.Schemas.GetSchemaAsync(arguments.Name);
if (arguments.WithReferencedNames)
{
- var allSchemas = await session.Schemas.GetSchemasAsync(session.App);
+ var allSchemas = await session.Client.Schemas.GetSchemasAsync();
var result = new SchemaWithRefs(schema).EnrichSchemaNames(allSchemas.Items);
@@ -118,7 +118,7 @@ public async Task Sync(SyncArguments arguments)
SchemaDto? targetSchema;
try
{
- targetSchema = await session.Schemas.GetSchemaAsync(session.App, schemaName);
+ targetSchema = await session.Client.Schemas.GetSchemaAsync(schemaName);
}
catch
{
@@ -131,14 +131,14 @@ public async Task Sync(SyncArguments arguments)
if (!arguments.NoRefFix && request.ReferencedSchemas.Any())
{
- var allSchemas = await session.Schemas.GetSchemasAsync(session.App);
+ var allSchemas = await session.Client.Schemas.GetSchemasAsync();
request.AdjustReferences(allSchemas.Items);
}
request.Schema.Name = schemaName;
- await session.Schemas.PostSchemaAsync(session.App, request.Schema);
+ await session.Client.Schemas.PostSchemaAsync(request.Schema);
log.WriteLine("> Created schema because it does not exists in the target system.");
}
@@ -148,7 +148,7 @@ public async Task Sync(SyncArguments arguments)
if (!arguments.NoRefFix && request.ReferencedSchemas.Any())
{
- var allSchemas = await session.Schemas.GetSchemasAsync(session.App);
+ var allSchemas = await session.Client.Schemas.GetSchemasAsync();
request.AdjustReferences(allSchemas.Items);
}
@@ -156,7 +156,7 @@ public async Task Sync(SyncArguments arguments)
request.Schema.NoFieldDeletion = arguments.NoFieldDeletion;
request.Schema.NoFieldRecreation = arguments.NoFieldRecreation;
- await session.Schemas.PutSchemaSyncAsync(session.App, schemaName, request.Schema);
+ await session.Client.Schemas.PutSchemaSyncAsync(schemaName, request.Schema);
log.WriteLine("> Synchronized schema");
}
diff --git a/cli/Squidex.CLI/Squidex.CLI/Commands/Implementation/OpenLibrary/AuthorImporter.cs b/cli/Squidex.CLI/Squidex.CLI/Commands/Implementation/OpenLibrary/AuthorImporter.cs
index 0206e5de..e74a46c3 100644
--- a/cli/Squidex.CLI/Squidex.CLI/Commands/Implementation/OpenLibrary/AuthorImporter.cs
+++ b/cli/Squidex.CLI/Squidex.CLI/Commands/Implementation/OpenLibrary/AuthorImporter.cs
@@ -29,7 +29,7 @@ private sealed record AuthorRecord(string Id, AuthorData Author);
public AuthorImporter(ISession session, ILogger log)
{
- client = session.Contents("author");
+ client = session.Client.Contents("author");
this.log = log;
}
diff --git a/csharp/Squidex.ClientLibrary/CodeGeneration/Client.Class.ReadObjectResponse.liquid b/csharp/Squidex.ClientLibrary/CodeGeneration/Client.Class.ReadObjectResponse.liquid
new file mode 100644
index 00000000..de0451c5
--- /dev/null
+++ b/csharp/Squidex.ClientLibrary/CodeGeneration/Client.Class.ReadObjectResponse.liquid
@@ -0,0 +1,58 @@
+protected virtual async System.Threading.Tasks.Task> ReadObjectResponseAsync(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Threading.CancellationToken cancellationToken)
+{
+ if (response == null || response.Content == null)
+ {
+{%- if GenerateNullableReferenceTypes -%}
+ return new ObjectResponseResult(default(T)!, string.Empty);
+{%- else -%}
+ return new ObjectResponseResult(default(T), string.Empty);
+{%- endif -%}
+ }
+
+ if (_options.ReadResponseAsString)
+ {
+ var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
+ try
+ {
+ var typedBody = {% if UseSystemTextJson %}System.Text.Json.JsonSerializer.Deserialize{% else %}Newtonsoft.Json.JsonConvert.DeserializeObject{% endif %}(responseText, {% if UseRequestAndResponseSerializationSettings %}Response{% endif %}JsonSerializerSettings);
+{%- if GenerateNullableReferenceTypes -%}
+ return new ObjectResponseResult(typedBody!, responseText);
+{%- else -%}
+ return new ObjectResponseResult(typedBody, responseText);
+{%- endif -%}
+ }
+ catch ({% if UseSystemTextJson %}System.Text.Json.JsonException{% else %}Newtonsoft.Json.JsonException{% endif %} exception)
+ {
+ var message = "Could not deserialize the response body string as " + typeof(T).FullName + ".";
+ throw new {{ ExceptionClass }}(message, (int)response.StatusCode, responseText, headers, exception);
+ }
+ }
+ else
+ {
+ try
+ {
+ using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
+{%- if UseSystemTextJson -%}
+ {
+ var typedBody = await System.Text.Json.JsonSerializer.DeserializeAsync(responseStream, {% if UseRequestAndResponseSerializationSettings %}Response{% endif %}JsonSerializerSettings, cancellationToken).ConfigureAwait(false);
+{%- else -%}
+ using (var streamReader = new System.IO.StreamReader(responseStream))
+ using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader))
+ {
+ var serializer = Newtonsoft.Json.JsonSerializer.Create({% if UseRequestAndResponseSerializationSettings %}Response{% endif %}JsonSerializerSettings);
+ var typedBody = serializer.Deserialize(jsonTextReader);
+{%- endif -%}
+{%- if GenerateNullableReferenceTypes -%}
+ return new ObjectResponseResult(typedBody!, string.Empty);
+{%- else -%}
+ return new ObjectResponseResult(typedBody, string.Empty);
+{%- endif -%}
+ }
+ }
+ catch ({% if UseSystemTextJson %}System.Text.Json.JsonException{% else %}Newtonsoft.Json.JsonException{% endif %} exception)
+ {
+ var message = "Could not deserialize the response body stream as " + typeof(T).FullName + ".";
+ throw new {{ ExceptionClass }}(message, (int)response.StatusCode, string.Empty, headers, exception);
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/Squidex.ClientLibrary/CodeGeneration/Client.Class.liquid b/csharp/Squidex.ClientLibrary/CodeGeneration/Client.Class.liquid
index 9af69c6f..cb64bdd6 100644
--- a/csharp/Squidex.ClientLibrary/CodeGeneration/Client.Class.liquid
+++ b/csharp/Squidex.ClientLibrary/CodeGeneration/Client.Class.liquid
@@ -5,7 +5,7 @@
{% if UseBaseUrl and GenerateBaseUrlProperty -%}
private string _baseUrl = "{{ BaseUrl }}";
{% endif -%}
- private Squidex.ClientLibrary.Configuration.IHttpClientProvider _httpClientProvider;
+ private Squidex.ClientLibrary.SquidexOptions _options;
{% if UseRequestAndResponseSerializationSettings -%}
private System.Lazy<{{ JsonSerializerSettingsType }}> _requestSettings;
private System.Lazy<{{ JsonSerializerSettingsType }}> _responseSettings;
@@ -13,9 +13,9 @@
private System.Lazy<{{ JsonSerializerSettingsType }}> _settings;
{% endif -%}
- public {{ Class }}(Squidex.ClientLibrary.Configuration.IHttpClientProvider httpClientProvider)
+ public {{ Class }}(Squidex.ClientLibrary.SquidexOptions options)
{
- _httpClientProvider = httpClientProvider;
+ _options = options;
{% if UseRequestAndResponseSerializationSettings -%}
_requestSettings = new System.Lazy<{{ JsonSerializerSettingsType }}>(() => CreateSerializerSettings(true));
_responseSettings = new System.Lazy<{{ JsonSerializerSettingsType }}>(() => CreateSerializerSettings(false));
@@ -119,6 +119,7 @@
{% endif -%}
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append({% if UseBaseUrl %}BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/{% else %}"{% endif %}{{ operation.Path }}{% if operation.HasQueryParameters %}?{% endif %}");
+ urlBuilder_.Replace("{app}", _options.AppName);
{% for parameter in operation.PathParameters -%}
{% if parameter.IsOptional -%}
if ({{ parameter.VariableName }} != null)
@@ -143,7 +144,7 @@
urlBuilder_.Length--;
{% endif -%}
- var client_ = _httpClientProvider.Get();
+ var client_ = _options.ClientProvider.Get();
try
{
{% if UseHttpRequestMessageCreationMethod -%}
@@ -152,12 +153,6 @@
using (var request_ = new System.Net.Http.HttpRequestMessage())
{% endif -%}
{
-{% for parameter in operation.Parameters %}
-{% if parameter.VariableName == "app" %}
- request_.Headers.TryAddWithoutValidation(SpecialHeaders.AppName, app);
-{% endif -%}
-{% endfor -%}
-
{% for parameter in operation.HeaderParameters %}
{% if parameter.IsRequired -%}
if ({{ parameter.VariableName }} == null)
@@ -365,7 +360,6 @@
}
finally
{
- _httpClientProvider.Return(client_);
}
}
diff --git a/csharp/Squidex.ClientLibrary/CodeGeneration/CodeGeneration.csproj b/csharp/Squidex.ClientLibrary/CodeGeneration/CodeGeneration.csproj
index 1393ab7d..bfacfa04 100644
--- a/csharp/Squidex.ClientLibrary/CodeGeneration/CodeGeneration.csproj
+++ b/csharp/Squidex.ClientLibrary/CodeGeneration/CodeGeneration.csproj
@@ -22,6 +22,9 @@
+
+ Always
+
Always
diff --git a/csharp/Squidex.ClientLibrary/CodeGeneration/Program.cs b/csharp/Squidex.ClientLibrary/CodeGeneration/Program.cs
index 49c3dcf2..5a5a70ff 100644
--- a/csharp/Squidex.ClientLibrary/CodeGeneration/Program.cs
+++ b/csharp/Squidex.ClientLibrary/CodeGeneration/Program.cs
@@ -18,9 +18,22 @@ namespace CodeGeneration;
public static class Program
{
- public static void Main()
+ public static async Task Main()
{
- var document = OpenApiDocument.FromUrlAsync("https://localhost:5001/api/swagger/v1/swagger.json").Result;
+ var document = await OpenApiDocument.FromUrlAsync("https://localhost:5001/api/swagger/v1/swagger.json");
+
+ foreach (var operation in document.Operations)
+ {
+ var parameters = operation.Operation.Parameters;
+
+ foreach (var parameter in parameters.ToList())
+ {
+ if (parameter.Kind == OpenApiParameterKind.Path && parameter.Name == "app")
+ {
+ parameters.Remove(parameter);
+ }
+ }
+ }
var generatorSettings = new CSharpClientGeneratorSettings();
generatorSettings.ExceptionClass = "SquidexManagementException";
diff --git a/csharp/Squidex.ClientLibrary/Directory.Build.props b/csharp/Squidex.ClientLibrary/Directory.Build.props
index 803965c8..5fb9305b 100644
--- a/csharp/Squidex.ClientLibrary/Directory.Build.props
+++ b/csharp/Squidex.ClientLibrary/Directory.Build.props
@@ -15,7 +15,7 @@
Squidex HeadlessCMS
true
snupkg
- 14.2.0
+ 15.0.0
diff --git a/csharp/Squidex.ClientLibrary/README.md b/csharp/Squidex.ClientLibrary/README.md
index 8a795357..973d3239 100644
--- a/csharp/Squidex.ClientLibrary/README.md
+++ b/csharp/Squidex.ClientLibrary/README.md
@@ -6,70 +6,4 @@ Also available on [nuget.org](https://www.nuget.org/packages/Squidex.ClientLibra
## How to use it?
-Our recommendation is to have a look to the other samples to see how it works, but here is a short introduction.
-
-The client library uses the following namespace: `Squidex.ClientLibrary`
-
-### 1. Create your model.
-
-For each schema you have to create two classes.
-
-1. The data object:
-
-````
-public sealed class BlogPostData
-{
- // Squidex delivers hash maps for each field, but the
- // InvariantConverter helps to simplify the model.
- [JsonConverter(typeof(InvariantConverter))]
- public string Title { get; set; }
-
- [JsonConverter(typeof(InvariantConverter))]
- public string Slug { get; set; }
-
- // For localizable fields you can use dictionaries.
- public Dictionary Text { get; set; }
-}
-````
-
-2. The entity object
-
-````
-public sealed class BlogPost : Content
-{
-}
-````
-
-
-### 2. Initialize the client manager
-
-````
-var clientManager =
- new SquidexClientManager(
- new SquidexOptions
- {
- AppName = "...",
- ClientId = "...",
- ClientSecret = "...",
- Url = "https://cloud.squidex.io"
- });
-````
-
-### 3. Create a client for your schema
-
-````
-var client = clientManager.CreateContentsClient("posts");
-````
-
-### 4. Use the client
-
-````
-// Read posts pages
-var posts = await client.GetAsync(page * pageSize, pageSize);
-
-// Read post by id.
-var post = client.GetAsync(id);
-
-// Read posts by slug.
-var posts = await client.GetAsync(filter: $"data/slug/iv eq '{slug}'");
-````
\ No newline at end of file
+Go to the documentation for installation and usage instructions: https://docs.squidex.io/02-documentation/software-development-kits/.net-standard
\ No newline at end of file
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/HttpClientProvider.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/HttpClientProvider.cs
index a1f0a299..ac053f56 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/HttpClientProvider.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/HttpClientProvider.cs
@@ -9,36 +9,13 @@
namespace Squidex.ClientLibrary.ServiceExtensions;
-///
-/// Default http client provider, that works as wrapper over .
-///
-public sealed class HttpClientProvider : IHttpClientProvider
+internal sealed class HttpClientProvider : IHttpClientProvider
{
private readonly Func factory;
- ///
- /// Initializes a new instance of the class with the wrapped see.
- ///
- /// The wrapped . Cannot be null.
- /// The logical name of the client to create. Cannot be null.
- /// is null.
- /// is null.
- public HttpClientProvider(System.Net.Http.IHttpClientFactory httpClientFactory, string httpClientName)
+ public HttpClientProvider(Func factory)
{
- if (httpClientFactory == null)
- {
- throw new ArgumentNullException(nameof(httpClientFactory));
- }
-
- if (httpClientName == null)
- {
- throw new ArgumentNullException(nameof(httpClientName));
- }
-
- factory = () =>
- {
- return httpClientFactory.CreateClient(httpClientName);
- };
+ this.factory = factory;
}
///
@@ -46,9 +23,4 @@ public HttpClient Get()
{
return factory();
}
-
- ///
- public void Return(HttpClient httpClient)
- {
- }
}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/ISquidexClientFactory.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/ISquidexClientFactory.cs
new file mode 100644
index 00000000..e94068a2
--- /dev/null
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/ISquidexClientFactory.cs
@@ -0,0 +1,31 @@
+// ==========================================================================
+// Squidex Headless CMS
+// ==========================================================================
+// Copyright (c) Squidex UG (haftungsbeschraenkt)
+// All rights reserved. Licensed under the MIT license.
+// ==========================================================================
+
+namespace Squidex.ClientLibrary.ServiceExtensions;
+
+///
+/// Provides a client.
+///
+public interface ISquidexClientProvider
+{
+ ///
+ /// Gets the default client.
+ ///
+ ///
+ /// The default client.
+ ///
+ ISquidexClient Get();
+
+ ///
+ /// Gets the client with the given name.
+ ///
+ /// The client name.
+ ///
+ /// The client with the given name.
+ ///
+ ISquidexClient Get(string name);
+}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/SquidexClientLibraryServiceExtensions.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/SquidexClientLibraryServiceExtensions.cs
index a9383a05..9d688b26 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/SquidexClientLibraryServiceExtensions.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/SquidexClientLibraryServiceExtensions.cs
@@ -9,7 +9,6 @@
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Options;
-using Squidex.ClientLibrary;
using Squidex.ClientLibrary.ServiceExtensions;
using Squidex.ClientLibrary.Utils;
@@ -21,58 +20,48 @@ namespace Microsoft.Extensions.DependencyInjection;
public static class SquidexClientLibraryServiceExtensions
{
///
- /// The name of the HTTP client.
+ /// Adds the Squidex client manager to the service collection.
///
- public const string ClientName = "SquidexClient";
+ /// The service collection.
+ /// A callback to configure Squidex.
+ /// The service collection that was passed in.
+ public static IServiceCollection AddSquidexClient(this IServiceCollection services, Action? configure = null)
+ {
+ return services.AddSquidexClient(Options.Options.DefaultName, configure);
+ }
///
/// Adds the Squidex client manager to the service collection.
///
/// The service collection.
+ /// The name of the client.
/// A callback to configure Squidex.
/// The service collection that was passed in.
- public static IServiceCollection AddSquidexClient(this IServiceCollection services, Action? configure)
+ public static IServiceCollection AddSquidexClient(this IServiceCollection services, string name, Action? configure = null)
{
if (configure != null)
{
- services.Configure(configure);
+ services.Configure(name, configure);
}
- services.AddOptions()
- .PostConfigure((options, c) =>
+ services.AddOptions(name)
+ .PostConfigure((options, c) =>
{
- options.ClientProvider = new HttpClientProvider(c.GetRequiredService(), ClientName);
+ var clientName = ClientName(name);
+
+ options.ClientProvider = new HttpClientProvider(() => c.CreateClient(clientName));
});
services.TryAddSingleton,
- OptionsValidator>();
-
- AddSquidexHttpClient(services, null);
-
- services.TryAddSingleton(
- c => new SquidexClientManager(c.GetRequiredService>().Value));
-
- services.AddSquidexClient(m => m.CreateAppsClient());
- services.AddSquidexClient(m => m.CreateAssetsClient());
- services.AddSquidexClient(m => m.CreateBackupsClient());
- services.AddSquidexClient(m => m.CreateCommentsClient());
- services.AddSquidexClient(m => m.CreateDiagnosticsClient());
- services.AddSquidexClient(m => m.CreateEventConsumersClient());
- services.AddSquidexClient(m => m.CreateExtendableRulesClient());
- services.AddSquidexClient(m => m.CreateCommentsClient());
- services.AddSquidexClient(m => m.CreateHistoryClient());
- services.AddSquidexClient(m => m.CreateLanguagesClient());
- services.AddSquidexClient(m => m.CreatePingClient());
- services.AddSquidexClient(m => m.CreatePlansClient());
- services.AddSquidexClient(m => m.CreateRulesClient());
- services.AddSquidexClient(m => m.CreateSchemasClient());
- services.AddSquidexClient(m => m.CreateSearchClient());
- services.AddSquidexClient(m => m.CreateStatisticsClient());
- services.AddSquidexClient(m => m.CreateTeamsClient());
- services.AddSquidexClient(m => m.CreateTemplatesClient());
- services.AddSquidexClient(m => m.CreateTranslationsClient());
- services.AddSquidexClient(m => m.CreateUserManagementClient());
- services.AddSquidexClient(m => m.CreateUsersClient());
+ SquidexOptionsValidator>();
+
+ services.TryAddSingleton();
+
+ services.TryAddSingleton(
+ c => c.GetRequiredService().Get());
+
+ services.AddSquidexHttpClient(name);
return services;
}
@@ -80,32 +69,30 @@ public static IServiceCollection AddSquidexClient(this IServiceCollection servic
///
/// Adds the Squidex client to the service collection.
///
- /// The service collection.
- /// A callback to provider the client from the manager.
- /// The service collection that was passed in.
- /// The type of the client to register.
- public static IServiceCollection AddSquidexClient(this IServiceCollection services, Func provider) where TClient : class
+ /// The service collection to configure.
+ /// The callback to configure the HTTP client.
+ /// The http client builder to make more customizatons.
+ public static IHttpClientBuilder AddSquidexHttpClient(this IServiceCollection services, Action? configure = null)
{
- services.TryAddSingleton(c => provider(c.GetRequiredService()));
-
- return services;
+ return services.AddSquidexHttpClient(Options.Options.DefaultName, configure);
}
///
/// Adds the Squidex client to the service collection.
///
/// The service collection to configure.
+ /// The name of the client.
/// The callback to configure the HTTP client.
/// The http client builder to make more customizatons.
- public static IHttpClientBuilder AddSquidexHttpClient(this IServiceCollection services, Action? configure = null)
+ public static IHttpClientBuilder AddSquidexHttpClient(this IServiceCollection services, string name, Action? configure = null)
{
- return services.AddHttpClient(ClientName, (c, httpClient) =>
+ return services.AddHttpClient(ClientName(name), (c, httpClient) =>
{
- var options = c.GetRequiredService>().Value;
+ var options = c.GetRequiredService>().Get(name);
- if (options.ConfigureHttpClientWithTimeout)
+ if (options.ConfigureHttpClientWithTimeout && options.Timeout != null)
{
- httpClient.Timeout = options.HttpClientTimeout;
+ httpClient.Timeout = options.Timeout.Value;
}
if (options.ConfigureHttpClientWithUrl)
@@ -133,7 +120,7 @@ public static void AddSquidexAuthenticatorAsAdditionalHandler(this HttpMessageHa
{
var options = builder.Services.GetRequiredService>().Value;
- builder.AdditionalHandlers.Add(new AuthenticatingHttpMessageHandler(options.Authenticator));
+ builder.AdditionalHandlers.Add(new AuthenticatingHttpMessageHandler(options));
}
///
@@ -144,6 +131,11 @@ public static void SetSquidexAuthenticatorAsPrimaryHandler(this HttpMessageHandl
{
var options = builder.Services.GetRequiredService>().Value;
- builder.PrimaryHandler = new AuthenticatingHttpMessageHandler(options.Authenticator);
+ builder.PrimaryHandler = new AuthenticatingHttpMessageHandler(options);
+ }
+
+ internal static string ClientName(string name)
+ {
+ return $"SquidexHttpClient_{name}";
}
}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/SquidexClientProvider.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/SquidexClientProvider.cs
new file mode 100644
index 00000000..1c94fd49
--- /dev/null
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/SquidexClientProvider.cs
@@ -0,0 +1,37 @@
+// ==========================================================================
+// Squidex Headless CMS
+// ==========================================================================
+// Copyright (c) Squidex UG (haftungsbeschraenkt)
+// All rights reserved. Licensed under the MIT license.
+// ==========================================================================
+
+using System.Collections.Concurrent;
+using Microsoft.Extensions.Options;
+
+namespace Squidex.ClientLibrary.ServiceExtensions;
+
+internal sealed class SquidexClientProvider : ISquidexClientProvider
+{
+ private readonly ConcurrentDictionary clients = new ConcurrentDictionary();
+ private readonly IOptionsMonitor optionsMonitor;
+
+ public SquidexClientProvider(IOptionsMonitor optionsMonitor)
+ {
+ this.optionsMonitor = optionsMonitor;
+ }
+
+ public ISquidexClient Get()
+ {
+ return Get(Options.DefaultName);
+ }
+
+ public ISquidexClient Get(string name)
+ {
+ return clients.GetOrAdd(name, (name, optionsMonitor) =>
+ {
+ var options = optionsMonitor.Get(name);
+
+ return new SquidexClient(options);
+ }, optionsMonitor);
+ }
+}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/OptionsValidator.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/SquidexOptionsValidator.cs
similarity index 90%
rename from csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/OptionsValidator.cs
rename to csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/SquidexOptionsValidator.cs
index c1453099..a57a4436 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/OptionsValidator.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.ServiceExtensions/SquidexOptionsValidator.cs
@@ -9,7 +9,7 @@
namespace Squidex.ClientLibrary.ServiceExtensions;
-internal sealed class OptionsValidator : IValidateOptions
+internal sealed class SquidexOptionsValidator : IValidateOptions
{
public ValidateOptionsResult Validate(string? name, SquidexServiceOptions options)
{
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/AssetFolderTreeTests.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/AssetFolderTreeTests.cs
index b51e18d2..a9052dab 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/AssetFolderTreeTests.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/AssetFolderTreeTests.cs
@@ -19,7 +19,7 @@ public class AssetFolderTreeTests
public AssetFolderTreeTests()
{
- sut = new AssetFolderTree(assets, "my-app");
+ sut = new AssetFolderTree(assets);
}
[Theory]
@@ -54,7 +54,7 @@ public async Task Should_query_for_path_once_for_each_subtree()
FolderName = "folder2"
};
- A.CallTo(() => assets.GetAssetFoldersAsync("my-app", folder1.Id, A._, A._))
+ A.CallTo(() => assets.GetAssetFoldersAsync(folder1.Id, A._, A._))
.Returns(new AssetFoldersDto
{
Items = new List(),
@@ -64,7 +64,7 @@ public async Task Should_query_for_path_once_for_each_subtree()
}
});
- A.CallTo(() => assets.GetAssetFoldersAsync("my-app", folder2.Id, A._, A._))
+ A.CallTo(() => assets.GetAssetFoldersAsync(folder2.Id, A._, A._))
.Returns(new AssetFoldersDto
{
Items = new List(),
@@ -77,7 +77,7 @@ public async Task Should_query_for_path_once_for_each_subtree()
Assert.Equal("folder1", await sut.GetPathAsync(folder1.Id));
Assert.Equal("folder2", await sut.GetPathAsync(folder2.Id));
- A.CallTo(() => assets.GetAssetFoldersAsync("my-app", A._, A._, A._))
+ A.CallTo(() => assets.GetAssetFoldersAsync(A._, A._, A._))
.MustHaveHappenedTwiceExactly();
}
@@ -98,7 +98,7 @@ public async Task Should_not_query_for_path_again_if_child_already_queried()
FolderName = "folder2"
};
- A.CallTo(() => assets.GetAssetFoldersAsync("my-app", folder2.Id, A._, A._))
+ A.CallTo(() => assets.GetAssetFoldersAsync(folder2.Id, A._, A._))
.Returns(new AssetFoldersDto
{
Items = new List(),
@@ -112,7 +112,7 @@ public async Task Should_not_query_for_path_again_if_child_already_queried()
Assert.Equal("folder1/folder2", await sut.GetPathAsync(folder2.Id));
Assert.Equal("folder1", await sut.GetPathAsync(folder1.Id));
- A.CallTo(() => assets.GetAssetFoldersAsync("my-app", A._, A._, A._))
+ A.CallTo(() => assets.GetAssetFoldersAsync(A._, A._, A._))
.MustHaveHappenedOnceExactly();
}
@@ -133,7 +133,7 @@ public async Task Should_not_query_for_path_again_if_parent_already_queried()
FolderName = "folder2"
};
- A.CallTo(() => assets.GetAssetFoldersAsync("my-app", folder1.Id, A._, A._))
+ A.CallTo(() => assets.GetAssetFoldersAsync(folder1.Id, A._, A._))
.Returns(new AssetFoldersDto
{
Items = new List
@@ -149,7 +149,7 @@ public async Task Should_not_query_for_path_again_if_parent_already_queried()
Assert.Equal("folder1", await sut.GetPathAsync(folder1.Id));
Assert.Equal("folder1/folder2", await sut.GetPathAsync(folder2.Id));
- A.CallTo(() => assets.GetAssetFoldersAsync("my-app", A._, A._, A._))
+ A.CallTo(() => assets.GetAssetFoldersAsync(A._, A._, A._))
.MustHaveHappenedOnceExactly();
}
@@ -170,7 +170,7 @@ public async Task Should_query_for_id_once_for_each_tree_item()
FolderName = "folder2"
};
- A.CallTo(() => assets.GetAssetFoldersAsync("my-app", RootId, A._, A._))
+ A.CallTo(() => assets.GetAssetFoldersAsync(RootId, A._, A._))
.Returns(new AssetFoldersDto
{
Items = new List
@@ -184,7 +184,7 @@ public async Task Should_query_for_id_once_for_each_tree_item()
Assert.Equal(folder1.Id, await sut.GetIdAsync("folder1"));
Assert.Equal(folder2.Id, await sut.GetIdAsync("folder2"));
- A.CallTo(() => assets.GetAssetFoldersAsync("my-app", A._, A._, A._))
+ A.CallTo(() => assets.GetAssetFoldersAsync(A._, A._, A._))
.MustHaveHappenedOnceExactly();
}
@@ -205,7 +205,7 @@ public async Task Should_not_query_for_id_again_if_parent_already_queried()
FolderName = "folder2"
};
- A.CallTo(() => assets.GetAssetFoldersAsync("my-app", folder1.Id, A._, A._))
+ A.CallTo(() => assets.GetAssetFoldersAsync(folder1.Id, A._, A._))
.Returns(new AssetFoldersDto
{
Items = new List
@@ -221,7 +221,7 @@ public async Task Should_not_query_for_id_again_if_parent_already_queried()
Assert.Equal("folder1", await sut.GetPathAsync(folder1.Id));
Assert.Equal("folder1/folder2", await sut.GetPathAsync(folder2.Id));
- A.CallTo(() => assets.GetAssetFoldersAsync("my-app", A._, A._, A._))
+ A.CallTo(() => assets.GetAssetFoldersAsync(A._, A._, A._))
.MustHaveHappenedOnceExactly();
}
@@ -242,7 +242,7 @@ public async Task Should_query_for_id_once_and_create_new_folder()
FolderName = "folder2"
};
- A.CallTo(() => assets.GetAssetFoldersAsync("my-app", RootId, A._, A._))
+ A.CallTo(() => assets.GetAssetFoldersAsync(RootId, A._, A._))
.Returns(new AssetFoldersDto
{
Items = new List
@@ -252,7 +252,7 @@ public async Task Should_query_for_id_once_and_create_new_folder()
Path = new List()
});
- A.CallTo(() => assets.PostAssetFolderAsync("my-app",
+ A.CallTo(() => assets.PostAssetFolderAsync(
A.That.Matches(x => x.FolderName == "folder2" && x.ParentId == RootId),
A._))
.Returns(folder2);
@@ -260,7 +260,7 @@ public async Task Should_query_for_id_once_and_create_new_folder()
Assert.Equal(folder1.Id, await sut.GetIdAsync("folder1"));
Assert.Equal(folder2.Id, await sut.GetIdAsync("folder2"));
- A.CallTo(() => assets.GetAssetFoldersAsync("my-app", A._, A._, A._))
+ A.CallTo(() => assets.GetAssetFoldersAsync(A._, A._, A._))
.MustHaveHappenedOnceExactly();
}
}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/BasicClientServiceTests.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/BasicClientServiceTests.cs
index afb69a39..99dfe824 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/BasicClientServiceTests.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/BasicClientServiceTests.cs
@@ -17,22 +17,12 @@ public async Task Should_query_content()
{
var sut = CreateSut();
- var result = await sut.CreateDynamicContentsClient("blog").GetAsync();
+ var result = await sut.DynamicContents("blog").GetAsync();
Assert.NotEmpty(result.Items);
}
- [Fact]
- public async Task Should_query_content_with_overriden_credentials()
- {
- var sut = CreateSutWithOverridenCredentials();
-
- var result = await sut.CreateDynamicContentsClient("blog").GetAsync();
-
- Assert.NotEmpty(result.Items);
- }
-
- private static ISquidexClientManager CreateSut()
+ private static ISquidexClient CreateSut()
{
var sut =
new ServiceCollection()
@@ -44,32 +34,7 @@ private static ISquidexClientManager CreateSut()
options.Url = "https://cloud.squidex.io";
})
.BuildServiceProvider()
- .GetRequiredService();
-
- return sut;
- }
-
- private static ISquidexClientManager CreateSutWithOverridenCredentials()
- {
- var sut =
- new ServiceCollection()
- .AddSquidexClient(options =>
- {
- options.AppName = "squidex-website";
- options.ClientId = "INVALID";
- options.ClientSecret = "INVALID";
- options.AppCredentials = new Dictionary
- {
- ["squidex-website"] = new AppCredentials
- {
- ClientId = "squidex-website:default",
- ClientSecret = "QGgqxd7bDHBTEkpC6fj8sbdPWgZrPrPfr3xzb3LKoec=",
- }
- };
- options.Url = "https://cloud.squidex.io";
- })
- .BuildServiceProvider()
- .GetRequiredService();
+ .GetRequiredService();
return sut;
}
@@ -97,13 +62,13 @@ public async Task Should_not_try_authenticate_again_if_it_failed(int retryHours,
return counts;
}).Services
.BuildServiceProvider()
- .GetRequiredService();
+ .GetRequiredService();
for (var i = 0; i < 10; i++)
{
try
{
- await sut.CreatePingClient().GetAppPingAsync("app");
+ await sut.Ping.GetAppPingAsync();
}
catch
{
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/BasicClientTests.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/BasicClientTests.cs
index 6825696d..fc0a52e8 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/BasicClientTests.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/BasicClientTests.cs
@@ -12,11 +12,11 @@ namespace Squidex.ClientLibrary.Tests;
public class BasicClientTests
{
- private readonly ISquidexClientManager sut;
+ private readonly ISquidexClient sut;
public BasicClientTests()
{
- sut = new SquidexClientManager(new SquidexOptions
+ sut = new SquidexClient(new SquidexOptions
{
AppName = "squidex-website",
ClientId = "squidex-website:reader",
@@ -27,23 +27,19 @@ public BasicClientTests()
[Fact(Skip = "No permissions.")]
public async Task Should_make_ping_api_request()
{
- var pingClient = sut.CreatePingClient();
-
- await pingClient.GetAppPingAsync("squidex-website");
+ await sut.Ping.GetAppPingAsync();
}
[Fact]
public async Task Should_make_ping_request()
{
- var pingClient = sut.CreatePingClient();
-
- await pingClient.GetPingAsync();
+ await sut.Ping.GetPingAsync();
}
[Fact]
public async Task Should_get_content()
{
- var result = await sut.CreateDynamicContentsClient("blog").GetAsync();
+ var result = await sut.DynamicContents("blog").GetAsync();
Assert.NotEmpty(result.Items);
}
@@ -53,7 +49,7 @@ public async Task Should_get_content_with_invalid_token()
{
((CachingAuthenticator)sut.Options.Authenticator).SetToCache(sut.Options.AppName, "TOKEN", DateTime.MaxValue);
- var result = await sut.CreateDynamicContentsClient("blog").GetAsync();
+ var result = await sut.DynamicContents("blog").GetAsync();
Assert.NotEmpty(result.Items);
}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/SquidexClientManagerTests.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/SquidexClientManagerTests.cs
index 24d5993e..9683a486 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/SquidexClientManagerTests.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/SquidexClientManagerTests.cs
@@ -6,16 +6,15 @@
// ==========================================================================
using Microsoft.Extensions.DependencyInjection;
+using Squidex.ClientLibrary.ServiceExtensions;
using Xunit;
namespace Squidex.ClientLibrary.Tests;
public class SquidexClientManagerTests
{
- [Theory]
- [InlineData("https://cloud.squidex.io")]
- [InlineData("https://cloud.squidex.io/")]
- public void Should_build_client_manager_from_service(string url)
+ [Fact]
+ public void Should_build_client_from_service()
{
var sut =
new ServiceCollection()
@@ -23,15 +22,62 @@ public void Should_build_client_manager_from_service(string url)
{
options.AppName = "app";
options.ClientId = "id";
- options.ClientSecret = "secet";
- options.Url = url;
+ options.ClientSecret = "secret";
+ options.Url = "https://custom.squidex.io";
})
.BuildServiceProvider()
- .GetRequiredService();
+ .GetRequiredService();
- var result = sut.GenerateUrl("relative/url");
+ Assert.Equal("https://custom.squidex.io/", sut.Options.Url);
+ }
- Assert.Equal("https://cloud.squidex.io/relative/url", result);
+ [Fact]
+ public void Should_build_client_from_service_with_custom_options()
+ {
+ var sut =
+ new ServiceCollection()
+ .AddSquidexClient(null)
+ .Configure(options =>
+ {
+ options.AppName = "app";
+ options.ClientId = "id";
+ options.ClientSecret = "secret";
+ options.Url = "https://custom.squidex.io";
+ })
+ .BuildServiceProvider()
+ .GetRequiredService();
+
+ Assert.Equal("https://custom.squidex.io/", sut.Options.Url);
+ }
+
+ [Fact]
+ public void Should_build_client_from_named_service()
+ {
+ var provider =
+ new ServiceCollection()
+ .AddSquidexClient(null)
+ .Configure(options =>
+ {
+ options.AppName = "app";
+ options.ClientId = "id";
+ options.ClientSecret = "secret";
+ options.Url = "https://custom1.squidex.io";
+ })
+ .Configure("named", options =>
+ {
+ options.AppName = "app";
+ options.ClientId = "id";
+ options.ClientSecret = "secret";
+ options.Url = "https://custom2.squidex.io";
+ })
+ .BuildServiceProvider()
+ .GetRequiredService();
+
+ var sut1 = provider.Get();
+ var sut2 = provider.Get("named");
+
+ Assert.Equal("https://custom1.squidex.io/", sut1.Options.Url);
+ Assert.Equal("https://custom2.squidex.io/", sut2.Options.Url);
}
[Theory]
@@ -122,19 +168,19 @@ public void Should_throw_exception_if_asset_cdn_not_configured()
Assert.Throws(() => sut.GenerateAssetCDNUrl("relative/url"));
}
- private static SquidexClientManager BuildClientManager(Action? configure = null)
+ private static SquidexClient BuildClientManager(Action? configure = null)
{
var options = new SquidexOptions
{
AppName = "app",
ClientId = "id",
- ClientSecret = "secet",
+ ClientSecret = "secret",
Url = "https://squidex.io"
};
configure?.Invoke(options);
- var sut = new SquidexClientManager(options);
+ var sut = new SquidexClient(options);
return sut;
}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/SquidexOptionsTests.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/SquidexOptionsTests.cs
index fd2f5886..bafc72ff 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/SquidexOptionsTests.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary.Tests/SquidexOptionsTests.cs
@@ -30,10 +30,5 @@ public void Should_bind_to_config()
Assert.Equal("My-App", options.AppName);
Assert.Equal("My-ClientId", options.ClientId);
Assert.Equal("My-ClientSecret", options.ClientSecret);
-
- var appCredentials = options.AppCredentials!["My-App2"];
-
- Assert.Equal("My-ClientId2", appCredentials.ClientId);
- Assert.Equal("My-ClientSecret2", appCredentials.ClientSecret);
}
}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/AppCredentials.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/AppCredentials.cs
deleted file mode 100644
index feea6b3a..00000000
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/AppCredentials.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-// ==========================================================================
-// Squidex Headless CMS
-// ==========================================================================
-// Copyright (c) Squidex UG (haftungsbeschraenkt)
-// All rights reserved. Licensed under the MIT license.
-// ==========================================================================
-
-namespace Squidex.ClientLibrary;
-
-///
-/// Application specific credentials.
-///
-public sealed class AppCredentials : OptionsBase
-{
- private string clientId;
- private string clientSecret;
-
- ///
- /// Gets or sets the client identifier.
- ///
- ///
- /// The client identifier. This is a required option.
- ///
- /// Option is frozen and cannot be changed anymore.
- public string ClientId
- {
- get => clientId;
- set => Set(ref clientId, value);
- }
-
- ///
- /// Gets or sets the client secret.
- ///
- ///
- /// The client secret. This is a required option.
- ///
- /// Option is frozen and cannot be changed anymore.
- public string ClientSecret
- {
- get => clientSecret;
- set => Set(ref clientSecret, value);
- }
-
- ///
- /// Validates the options.
- ///
- public void CheckAndFreeze()
- {
- if (IsFrozen)
- {
- return;
- }
-
-#pragma warning disable MA0015 // Specify the parameter name in ArgumentException
- if (string.IsNullOrWhiteSpace(clientId))
- {
- throw new ArgumentException("Client id is not defined.", nameof(ClientId));
- }
-
- if (string.IsNullOrWhiteSpace(clientSecret))
- {
- throw new ArgumentException("Client secret is not defined.", nameof(ClientSecret));
- }
-
- Freeze();
-#pragma warning restore MA0015 // Specify the parameter name in ArgumentException
- }
-}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/AssetFolderTree.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/AssetFolderTree.cs
index afde1b21..135cc88d 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/AssetFolderTree.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/AssetFolderTree.cs
@@ -20,23 +20,19 @@ public sealed class AssetFolderTree
private static readonly string RootId = Guid.Empty.ToString();
private readonly Dictionary nodes = new Dictionary();
private readonly IAssetsClient assetsClient;
- private readonly string appName;
private readonly AssetFolderNode rootNode = new AssetFolderNode(RootId, string.Empty, string.Empty);
///
/// Initializes a new instance of the class.
///
/// The assets client. Cannot be null.
- /// The app name. Cannot be null.
- public AssetFolderTree(IAssetsClient assetsClient, string appName)
+ public AssetFolderTree(IAssetsClient assetsClient)
{
Guard.NotNull(assetsClient, nameof(assetsClient));
- Guard.NotNull(appName, nameof(appName));
nodes[RootId] = rootNode;
this.assetsClient = assetsClient;
- this.appName = appName;
}
///
@@ -140,7 +136,7 @@ private async Task AddFolderAsync(AssetFolderNode current, stri
ParentId = current.Id
};
- var folder = await assetsClient.PostAssetFolderAsync(appName, request);
+ var folder = await assetsClient.PostAssetFolderAsync(request);
current = TryAdd(current, folder.Id, name);
current.HasBeenQueried = true;
@@ -155,7 +151,7 @@ private async Task QueryAsync(string id, bool needsChildren)
return node;
}
- var folders = await assetsClient.GetAssetFoldersAsync(appName, id);
+ var folders = await assetsClient.GetAssetFoldersAsync(id);
var current = rootNode;
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/AcceptAllCertificatesConfigurator.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/AcceptAllCertificatesConfigurator.cs
deleted file mode 100644
index 6ded8451..00000000
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/AcceptAllCertificatesConfigurator.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-// ==========================================================================
-// Squidex Headless CMS
-// ==========================================================================
-// Copyright (c) Squidex UG (haftungsbeschraenkt)
-// All rights reserved. Licensed under the MIT license.
-// ==========================================================================
-
-namespace Squidex.ClientLibrary.Configuration;
-
-///
-/// Configures the HTTP client to accept all SSL certificates.
-///
-///
-public sealed class AcceptAllCertificatesConfigurator : IHttpConfigurator
-{
- ///
- /// The only instance of this class.
- ///
- public static readonly AcceptAllCertificatesConfigurator Instance = new AcceptAllCertificatesConfigurator();
-
- private AcceptAllCertificatesConfigurator()
- {
- }
-
- ///
- public void Configure(HttpClient httpClient)
- {
- }
-
- ///
- public void Configure(HttpClientHandler httpClientHandler)
- {
- httpClientHandler.ServerCertificateCustomValidationCallback += (message, certificate, chain, errors) => true;
- }
-}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/Authenticator.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/Authenticator.cs
index 7771711b..8ea44652 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/Authenticator.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/Authenticator.cs
@@ -56,43 +56,31 @@ public async Task GetBearerTokenAsync(string appName,
CancellationToken ct)
{
var httpClient = options.ClientProvider.Get();
- try
- {
- var clientId = options.ClientId;
- var clientSecret = options.ClientSecret;
- if (options.AppCredentials != null && options.AppCredentials.TryGetValue(appName, out var credentials))
- {
- clientId = credentials.ClientId;
- clientSecret = credentials.ClientSecret;
- }
+ var clientId = options.ClientId;
+ var clientSecret = options.ClientSecret;
- ThrowFromPreviousAttempt(clientId, clientSecret);
+ ThrowFromPreviousAttempt(clientId, clientSecret);
- var httpRequest = BuildRequest(clientId, clientSecret);
+ var httpRequest = BuildRequest(clientId, clientSecret);
- using (var response = await httpClient.SendAsync(httpRequest, ct))
+ using (var response = await httpClient.SendAsync(httpRequest, ct))
+ {
+ if (!response.IsSuccessStatusCode)
{
- if (!response.IsSuccessStatusCode)
- {
- var exception = new SecurityException($"Failed to retrieve access token for client '{options.ClientId}', got HTTP {response.StatusCode}.");
+ var exception = new SecurityException($"Failed to retrieve access token for client '{options.ClientId}', got HTTP {response.StatusCode}.");
- StorePreviousAttempt(clientId, clientSecret, exception);
- throw exception;
- }
+ StorePreviousAttempt(clientId, clientSecret, exception);
+ throw exception;
+ }
#if NET5_0_OR_GREATER
- var jsonString = await response.Content.ReadAsStringAsync(ct);
+ var jsonString = await response.Content.ReadAsStringAsync(ct);
#else
- var jsonString = await response.Content.ReadAsStringAsync();
+ var jsonString = await response.Content.ReadAsStringAsync();
#endif
- var jsonToken = JToken.Parse(jsonString);
+ var jsonToken = JToken.Parse(jsonString);
- return jsonToken["access_token"]!.ToString();
- }
- }
- finally
- {
- options.ClientProvider.Return(httpClient);
+ return jsonToken["access_token"]!.ToString();
}
}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/GlobalContextClientFactory.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/GlobalContextClientFactory.cs
deleted file mode 100644
index c0b41c00..00000000
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/GlobalContextClientFactory.cs
+++ /dev/null
@@ -1,58 +0,0 @@
-// ==========================================================================
-// Squidex Headless CMS
-// ==========================================================================
-// Copyright (c) Squidex UG (haftungsbeschraenkt)
-// All rights reserved. Licensed under the MIT license.
-// ==========================================================================
-
-namespace Squidex.ClientLibrary.Configuration;
-
-///
-/// A that adds the context options to all requests.
-///
-///
-public sealed class GlobalContextClientFactory : IHttpClientFactory
-{
- private readonly QueryContext context;
-
- private sealed class ApplyHeadersHandler : DelegatingHandler
- {
- private readonly QueryContext context;
-
- public ApplyHeadersHandler(QueryContext context)
- {
- this.context = context;
- }
-
- protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
- {
- context?.AddToHeaders(request.Headers);
-
- return base.SendAsync(request, cancellationToken);
- }
- }
-
- ///
- /// Initializes a new instance of the class with the context to apply.
- ///
- /// The context to apply.
- public GlobalContextClientFactory(QueryContext context)
- {
- this.context = context;
- }
-
- ///
- public HttpMessageHandler? CreateHttpMessageHandler(HttpMessageHandler inner)
- {
- return new ApplyHeadersHandler(context)
- {
- InnerHandler = inner
- };
- }
-
- ///
- public HttpClient? CreateHttpClient(HttpMessageHandler messageHandler)
- {
- return null;
- }
-}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/IHttpClientFactory.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/IHttpClientFactory.cs
deleted file mode 100644
index d81dfd00..00000000
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/IHttpClientFactory.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-// ==========================================================================
-// Squidex Headless CMS
-// ==========================================================================
-// Copyright (c) Squidex UG (haftungsbeschraenkt)
-// All rights reserved. Licensed under the MIT license.
-// ==========================================================================
-
-namespace Squidex.ClientLibrary.Configuration;
-
-///
-/// Optional interface to create new instances.
-///
-///
-/// Implement this class if you have custom requirements how the HTTP requests need to be done.
-///
-public interface IHttpClientFactory
-{
- ///
- /// Creates the HTTP client from the message.
- ///
- /// The message handler.
- ///
- /// The HTTP client.
- ///
- HttpClient? CreateHttpClient(HttpMessageHandler messageHandler);
-
- ///
- /// Creates the HTTP message handler from the inner handler.
- ///
- /// The inner handler.
- ///
- /// The HTTP message handler.
- ///
- HttpMessageHandler? CreateHttpMessageHandler(HttpMessageHandler inner);
-}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/IHttpClientProvider.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/IHttpClientProvider.cs
index 15f40d33..b64b7192 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/IHttpClientProvider.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/IHttpClientProvider.cs
@@ -22,10 +22,4 @@ public interface IHttpClientProvider
/// The HTTP client.
///
HttpClient Get();
-
- ///
- /// Return a HTTP client.
- ///
- /// The HTTP client to release.
- void Return(HttpClient httpClient);
}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/IHttpConfigurator.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/IHttpConfigurator.cs
deleted file mode 100644
index 479fd525..00000000
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/IHttpConfigurator.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-// ==========================================================================
-// Squidex Headless CMS
-// ==========================================================================
-// Copyright (c) Squidex UG (haftungsbeschraenkt)
-// All rights reserved. Licensed under the MIT license.
-// ==========================================================================
-
-namespace Squidex.ClientLibrary.Configuration;
-
-///
-/// Implement this interface to change the behavior of HTTP requests.
-///
-public interface IHttpConfigurator
-{
- ///
- /// Configures the specified HTTP client.
- ///
- /// The HTTP client to configure.
- void Configure(HttpClient httpClient);
-
- ///
- /// Configures the specified HTTP client handler.
- ///
- /// The HTTP client handler to configure.
- void Configure(HttpClientHandler httpClientHandler);
-}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/NoopHttpConfigurator.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/NoopHttpConfigurator.cs
deleted file mode 100644
index 3c1b4f42..00000000
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/NoopHttpConfigurator.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-// ==========================================================================
-// Squidex Headless CMS
-// ==========================================================================
-// Copyright (c) Squidex UG (haftungsbeschraenkt)
-// All rights reserved. Licensed under the MIT license.
-// ==========================================================================
-
-namespace Squidex.ClientLibrary.Configuration;
-
-///
-/// Default implementation of the and that does
-/// not do anything and provides the default behavior.
-///
-///
-///
-public sealed class NoopHttpConfigurator : IHttpConfigurator, IHttpClientFactory
-{
- ///
- /// The only instance of this class.
- ///
- public static readonly NoopHttpConfigurator Instance = new NoopHttpConfigurator();
-
- private NoopHttpConfigurator()
- {
- }
-
- ///
- public void Configure(HttpClient httpClient)
- {
- }
-
- ///
- public void Configure(HttpClientHandler httpClientHandler)
- {
- }
-
- ///
- public HttpClient? CreateHttpClient(HttpMessageHandler messageHandler)
- {
- return null;
- }
-
- ///
- public HttpMessageHandler? CreateHttpMessageHandler(HttpMessageHandler inner)
- {
- return inner;
- }
-}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/StaticHttpClientProvider.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/StaticHttpClientProvider.cs
index f34fb673..37a9af2f 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/StaticHttpClientProvider.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Configuration/StaticHttpClientProvider.cs
@@ -12,9 +12,10 @@ namespace Squidex.ClientLibrary.Configuration;
///
/// Provides a static instance.
///
-public sealed class StaticHttpClientProvider : IHttpClientProvider
+public class StaticHttpClientProvider : IHttpClientProvider
{
- private readonly HttpClient staticHttpClient;
+ private readonly SquidexOptions options;
+ private HttpClient? staticHttpClient;
///
/// Initializes a new instance of the class.
@@ -24,45 +25,60 @@ public StaticHttpClientProvider(SquidexOptions options)
{
Guard.NotNull(options, nameof(options));
- staticHttpClient = CreateClient(options);
+ this.options = options;
}
- private static HttpClient CreateClient(SquidexOptions options)
+ ///
+ /// Creates the client from the options.
+ ///
+ /// The options.
+ ///
+ /// The created HTTP client.
+ ///
+ protected virtual HttpClient CreateHttpClient(SquidexOptions options)
{
- var handler = new HttpClientHandler();
+ var messageHandler = CreateMessageHandler(options);
- options.Configurator.Configure(handler);
-
- HttpMessageHandler messageHandler = new AuthenticatingHttpMessageHandler(options.Authenticator)
+ var httpClient = new HttpClient(messageHandler, false)
{
- InnerHandler = handler
+ BaseAddress = new Uri(options.Url, UriKind.Absolute)
};
- messageHandler = options.ClientFactory.CreateHttpMessageHandler(messageHandler) ?? messageHandler;
+ if (options.Timeout != null)
+ {
+ httpClient.Timeout = options.Timeout.Value;
+ }
- var httpClient =
- options.ClientFactory.CreateHttpClient(messageHandler) ??
- new HttpClient(messageHandler, false);
+ return httpClient;
+ }
- // Apply this setting afterwards, to override the value from the client factory.
- httpClient.BaseAddress = new Uri(options.Url, UriKind.Absolute);
+ ///
+ /// Creates the client handler from the options.
+ ///
+ /// The options.
+ ///
+ /// The created HTTP client handler.
+ ///
+ protected virtual HttpMessageHandler CreateMessageHandler(SquidexOptions options)
+ {
+ var innerHandler = new HttpClientHandler();
- // Also override timeout when create from factory.
- httpClient.Timeout = options.HttpClientTimeout;
+ if (options.IgnoreSelfSignedCertificates)
+ {
+ innerHandler.ServerCertificateCustomValidationCallback = (_, _, _, _) => true;
+ }
- options.Configurator.Configure(httpClient);
+ var messageHandler = new AuthenticatingHttpMessageHandler(options)
+ {
+ InnerHandler = innerHandler
+ };
- return httpClient;
+ return messageHandler;
}
///
public HttpClient Get()
{
- return staticHttpClient;
- }
-
- ///
- public void Return(HttpClient httpClient)
- {
+ return staticHttpClient ?? CreateHttpClient(options);
}
}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ContentsClient.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ContentsClient.cs
index 819bc538..ccb86266 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ContentsClient.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ContentsClient.cs
@@ -24,20 +24,15 @@ namespace Squidex.ClientLibrary;
///
/// Initializes a new instance of the class
- /// with the name of the schema, the options from the and the HTTP client.
+ /// with the name of the schema, the options from the and the HTTP client.
///
- /// The options from the . Cannot be null.
- /// Name of the app. Cannot be null or empty.
+ /// The options from the . Cannot be null.
/// Name of the schema. Cannot be null or empty.
- /// The HTTP client provider. Cannot be null.
/// is null.
- /// is null.
/// is null.
- /// is null.
- /// is empty.
/// is empty.
- public ContentsClient(SquidexOptions options, string appName, string schemaName, IHttpClientProvider httpClientProvider)
- : base(options, appName, httpClientProvider)
+ public ContentsClient(SquidexOptions options, string schemaName)
+ : base(options)
{
Guard.NotNullOrEmpty(schemaName, nameof(schemaName));
@@ -91,57 +86,51 @@ public async Task StreamAllAsync(Func callback, int skip = 0, Que
context = (context ?? QueryContext.Default).WithoutTotal();
- var httpClient = HttpClientProvider.Get();
- try
+ var httpClient = Options.ClientProvider.Get();
+
+ using (var request = BuildRequest(HttpMethod.Get, BuildUrl($"stream?skip={skip}", false), null, context))
{
- using (var request = BuildRequest(HttpMethod.Get, BuildUrl($"stream?skip={skip}", false), null, context))
+ using (var response = await httpClient.SendAsync(request, ct))
{
- using (var response = await httpClient.SendAsync(request, ct))
- {
- await EnsureResponseIsValidAsync(response);
+ await EnsureResponseIsValidAsync(response);
#if NETSTANDARD2_0 || NETCOREAPP3_1
- using (var reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
+ using (var reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
#else
- using (var reader = new StreamReader(await response.Content.ReadAsStreamAsync(ct)))
+ using (var reader = new StreamReader(await response.Content.ReadAsStreamAsync(ct)))
#endif
- {
- string? line;
+ {
+ string? line;
#if NET7_0_OR_GREATER
- while ((line = await reader.ReadLineAsync(ct)) != null)
+ while ((line = await reader.ReadLineAsync(ct)) != null)
#else
- while ((line = await reader.ReadLineAsync()) != null)
+ while ((line = await reader.ReadLineAsync()) != null)
#endif
- {
- ct.ThrowIfCancellationRequested();
+ {
+ ct.ThrowIfCancellationRequested();
- if (string.IsNullOrWhiteSpace(line))
- {
- continue;
- }
+ if (string.IsNullOrWhiteSpace(line))
+ {
+ continue;
+ }
- const string Prefix = "data: ";
+ const string Prefix = "data: ";
- if (!line.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase))
- {
- throw new SquidexException("Line does not start with data prefix.", 0, null);
- }
+ if (!line.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase))
+ {
+ throw new SquidexException("Line does not start with data prefix.", 0, null);
+ }
#pragma warning disable IDE0057 // Use range operator
- var contentJson = line.Substring(Prefix.Length);
+ var contentJson = line.Substring(Prefix.Length);
#pragma warning restore IDE0057 // Use range operator
- var contentItem = contentJson.FromJson();
+ var contentItem = contentJson.FromJson();
- await callback(contentItem);
- }
+ await callback(contentItem);
}
}
}
}
- finally
- {
- HttpClientProvider.Return(httpClient);
- }
}
///
@@ -171,15 +160,6 @@ public Task GetAsync(string id, long version, QueryContext? context = n
return RequestJsonAsync(HttpMethod.Get, BuildUrl($"{id}/?version={version}", true, context), null, context, ct);
}
- ///
- public Task GetDataAsync(string id, int version, QueryContext? context = null,
- CancellationToken ct = default)
- {
- Guard.NotNullOrEmpty(id, nameof(id));
-
- return RequestJsonAsync(HttpMethod.Get, BuildUrl($"{id}/{version}", true, context), null, context, ct);
- }
-
///
public Task> GetReferencingAsync(TEntity entity, ContentQuery? query = null, QueryContext? context = null,
CancellationToken ct = default)
@@ -372,11 +352,11 @@ private string BuildUrl(string path, bool query, QueryContext? context = null)
{
if (ShouldUseCDN(query, context))
{
- return $"{Options.ContentCDN}{AppName}/{SchemaName}/{path}";
+ return $"{Options.ContentCDN}{Options.AppName}/{SchemaName}/{path}";
}
else
{
- return $"api/content/{AppName}/{SchemaName}/{path}";
+ return $"api/content/{Options.AppName}/{SchemaName}/{path}";
}
}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ContentsSharedClient.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ContentsSharedClient.cs
index 83dc5751..ffb10807 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ContentsSharedClient.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ContentsSharedClient.cs
@@ -23,17 +23,12 @@ namespace Squidex.ClientLibrary;
{
///
/// Initializes a new instance of the class
- /// with the name of the schema, the options from the and the HTTP client.
+ /// with the name of the schema, the options from the and the HTTP client.
///
- /// The options from the . Cannot be null.
- /// Name of the app. Cannot be null or empty.
- /// The HTTP client provider. Cannot be null.
+ /// The options from the . Cannot be null.
/// is null.
- /// is null.
- /// is null.
- /// is empty.
- public ContentsSharedClient(SquidexOptions options, string appName, IHttpClientProvider httpClientProvider)
- : base(options, appName, httpClientProvider)
+ public ContentsSharedClient(SquidexOptions options)
+ : base(options)
{
}
@@ -107,11 +102,11 @@ private string BuildUrl(string path, bool query, QueryContext? context = null)
{
if (ShouldUseCDN(query, context))
{
- return $"{Options.ContentCDN}{AppName}/{path}";
+ return $"{Options.ContentCDN}{Options.AppName}/{path}";
}
else
{
- return $"api/content/{AppName}/{path}";
+ return $"api/content/{Options.AppName}/{path}";
}
}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Status.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/EnrichedEvents/Status.cs
similarity index 98%
rename from csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Status.cs
rename to csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/EnrichedEvents/Status.cs
index 2c43e938..6020582e 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Status.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/EnrichedEvents/Status.cs
@@ -7,7 +7,7 @@
using System.ComponentModel;
-namespace Squidex.ClientLibrary;
+namespace Squidex.ClientLibrary.EnrichedEvents;
///
/// Default status strings.
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/StatusTypeConverter.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/EnrichedEvents/StatusTypeConverter.cs
similarity index 96%
rename from csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/StatusTypeConverter.cs
rename to csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/EnrichedEvents/StatusTypeConverter.cs
index 3c312128..e3500761 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/StatusTypeConverter.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/EnrichedEvents/StatusTypeConverter.cs
@@ -8,7 +8,7 @@
using System.ComponentModel;
using System.Globalization;
-namespace Squidex.ClientLibrary;
+namespace Squidex.ClientLibrary.EnrichedEvents;
///
/// Converter for the Status.
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ExtendableRulesClient.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ExtendableRulesClient.cs
index 9a1aca59..769bdd6c 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ExtendableRulesClient.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ExtendableRulesClient.cs
@@ -19,17 +19,12 @@ public sealed class ExtendableRulesClient : SquidexClientBase, IExtendableRulesC
{
///
/// Initializes a new instance of the class
- /// with the name of the schema, the options from the and the HTTP client.
+ /// with the name of the schema, the options from the and the HTTP client.
///
- /// The options from the . Cannot be null.
- /// Name of the app. Cannot be null or empty.
- /// The HTTP client provider. Cannot be null.
+ /// The options from the . Cannot be null.
/// is null.
- /// is null.
- /// is null.
- /// is empty.
- public ExtendableRulesClient(SquidexOptions options, string appName, IHttpClientProvider httpClientProvider)
- : base(options, appName, httpClientProvider)
+ public ExtendableRulesClient(SquidexOptions options)
+ : base(options)
{
}
@@ -88,6 +83,6 @@ public Task DeleteRuleAsync(string id,
private string BuildUrl(string? path = null)
{
- return $"api/apps/{AppName}/rules/{path}";
+ return $"api/apps/{Options.AppName}/rules/{path}";
}
}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/IContentsClient.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/IContentsClient.cs
index 10dcbc8e..8f1516cb 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/IContentsClient.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/IContentsClient.cs
@@ -14,14 +14,6 @@ namespace Squidex.ClientLibrary;
/// The type that represents the data structure.
public interface IContentsClient where TEntity : Content where TData : class, new()
{
- ///
- /// Gets the name of the app for which this client has been created.
- ///
- ///
- /// The name of the app for which this client has been created.
- ///
- string AppName { get; }
-
///
/// Gets the name of the schema for which this client has been created.
///
@@ -325,22 +317,6 @@ Task GetAsync(string id, QueryContext? context = null,
Task GetAsync(string id, long version, QueryContext? context = null,
CancellationToken ct = default);
- ///
- /// Gets a content item by ID and version.
- ///
- /// The ID of the content item. Cannot be null or empty.
- /// The version of the content.
- /// The context object to add additonal headers to the request and change the behavior of the API when querying content items.
- /// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
- ///
- /// The content item or null if not found.
- ///
- /// is null.
- /// is empty.
- [Obsolete("Use GetAsync with version.")]
- Task GetDataAsync(string id, int version, QueryContext? context = null,
- CancellationToken ct = default);
-
///
/// Query content items by an optional query.
///
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/IContentsSharedClient.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/IContentsSharedClient.cs
index 8c40e33e..12eb3332 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/IContentsSharedClient.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/IContentsSharedClient.cs
@@ -14,14 +14,6 @@ namespace Squidex.ClientLibrary;
/// The type that represents the data structure.
public interface IContentsSharedClient where TEntity : Content where TData : class, new()
{
- ///
- /// Gets the name of the app for which this client has been created.
- ///
- ///
- /// The name of the app for which this client has been created.
- ///
- string AppName { get; }
-
///
/// Executes a bulk update.
///
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ISquidexClient.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ISquidexClient.cs
new file mode 100644
index 00000000..7a5e8c7e
--- /dev/null
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ISquidexClient.cs
@@ -0,0 +1,287 @@
+// ==========================================================================
+// Squidex Headless CMS
+// ==========================================================================
+// Copyright (c) Squidex UG (haftungsbeschraenkt)
+// All rights reserved. Licensed under the MIT license.
+// ==========================================================================
+
+using Squidex.ClientLibrary.Management;
+
+namespace Squidex.ClientLibrary;
+
+///
+/// Provides access to all endpoints through individual clients and handles authentication.
+///
+public interface ISquidexClient
+{
+ ///
+ /// Gets the options that are used to initialize the client manager.
+ ///
+ ///
+ /// The options that are used to initialize the client manager.
+ ///
+ ///
+ /// This object is frozen and cannot be changed later.
+ ///
+ SquidexOptions Options { get; }
+
+ ///
+ /// Generates the URL to the image with the specified ID.
+ ///
+ /// The ID of the asset.
+ ///
+ /// THe URL to the image.
+ ///
+ string? GenerateImageUrl(string? id);
+
+ ///
+ /// Generates the URL to the image with the first specified ID.
+ ///
+ /// The ID of the asset.
+ ///
+ /// THe URL to the image.
+ ///
+ string? GenerateImageUrl(IEnumerable? id);
+
+ ///
+ /// Generates an absolute URL.
+ ///
+ /// The relative URL.
+ ///
+ /// The absolute URL.
+ ///
+ string? GenerateUrl(string? relativeUrl);
+
+ ///
+ /// Generates an absolute URL for the asset CDN.
+ ///
+ /// The relative URL.
+ /// Asset CDN not configured.
+ ///
+ /// The absolute URL.
+ ///
+ string? GenerateAssetCDNUrl(string relativeUrl);
+
+ ///
+ /// Generates an absolute URL for the content CDN.
+ ///
+ /// The relative URL.
+ /// Content CDN not configured.
+ ///
+ /// The absolute URL.
+ ///
+ string? GenerateContentCDNUrl(string relativeUrl);
+
+ ///
+ /// Gets a client instance to query and manage app configuration.
+ ///
+ ///
+ /// The returned client.
+ ///
+ IAppsClient Apps { get; }
+
+ ///
+ /// Gets a client instance to query and manage assets.
+ ///
+ ///
+ /// The returned client.
+ ///
+ IAssetsClient Assets { get; }
+
+ ///
+ /// Gets a client instance to query and manage backups.
+ ///
+ ///
+ /// The returned client.
+ ///
+ IBackupsClient Backups { get; }
+
+ ///
+ /// Gets a client instance to query and manage comments.
+ ///
+ ///
+ /// The returned client.
+ ///
+ ICommentsClient Comments { get; }
+
+ ///
+ /// Gets a client instance to query diagnostics data.
+ ///
+ ///
+ /// The returned client.
+ ///
+ IDiagnosticsClient Diagnostics { get; }
+
+ ///
+ /// Gets a client instance to query and manage event consumers.
+ ///
+ ///
+ /// The returned client.
+ ///
+ IEventConsumersClient EventConsumers { get; }
+
+ ///
+ /// Gets a client instance to query and manage histories.
+ ///
+ ///
+ /// The returned client.
+ ///
+ IHistoryClient History { get; }
+
+ ///
+ /// Gets a client instance to query all supported languages.
+ ///
+ ///
+ /// The returned client.
+ ///
+ ///
+ /// Do not create new clients frequently.
+ ///
+ ILanguagesClient Languages { get; }
+
+ ///
+ /// Gets a client instance to ping the server for monitoring.
+ ///
+ ///
+ /// The returned client.
+ ///
+ IPingClient Ping { get; }
+
+ ///
+ /// Gets a client instance to query and manage plans and subscriptions.
+ ///
+ ///
+ /// The returned client.
+ ///
+ IPlansClient Plans { get; }
+
+ ///
+ /// Gets a client instance to query and manage rules.
+ ///
+ ///
+ /// The returned client.
+ ///
+ IRulesClient Rules { get; }
+
+ ///
+ /// Gets a client instance to query and manage schemas.
+ ///
+ ///
+ /// The returned client.
+ ///
+ ISchemasClient Schemas { get; }
+
+ ///
+ /// Gets a client instance to make searches across content and records.
+ ///
+ ///
+ /// The returned client.
+ ///
+ ISearchClient Search { get; }
+
+ ///
+ /// Gets a client instance to query statistics.
+ ///
+ ///
+ /// The returned client.
+ ///
+ IStatisticsClient Statistics { get; }
+
+ ///
+ /// Gets a client instance to query and manage teams.
+ ///
+ ///
+ /// The returned client.
+ ///
+ ITeamsClient Teams { get; }
+
+ ///
+ /// Gets a client instance to query templates.
+ ///
+ ///
+ /// The returned client.
+ ///
+ ITemplatesClient Templates { get; }
+
+ ///
+ /// Gets a client instance to translate content.
+ ///
+ ///
+ /// The returned client.
+ ///
+ ITranslationsClient Translations { get; }
+
+ ///
+ /// Gets a client instance to query user information.
+ ///
+ ///
+ /// The returned client.
+ ///
+ IUsersClient Users { get; }
+
+ ///
+ /// Gets a client instance to query and manage users as administrator.
+ ///
+ ///
+ /// The returned client.
+ ///
+ IUserManagementClient UserManagement { get; }
+
+ ///
+ /// Gets a client instance to query and manage untyped rules.
+ ///
+ ///
+ /// The returned client.
+ ///
+ IExtendableRulesClient ExtendableRules { get; }
+
+ ///
+ /// Gets a client instance to query and manage contents across all schemas with dynamic data shape.
+ ///
+ ///
+ /// The returned client.
+ ///
+ IContentsSharedClient SharedDynamicContents { get; }
+
+ ///
+ /// Gets a client instance to query and manage contents for a schema.
+ ///
+ /// The type for the content entity.
+ /// The type that represents the data structure.
+ /// The name of the schema. Cannot be null or empty.
+ ///
+ /// The returned client.
+ ///
+ /// is null.
+ /// is empty.
+ IContentsClient Contents(string schemaName) where TEntity : Content where TData : class, new();
+
+ ///
+ /// Gets a client instance to query and manage contents for a schema with dynamic data shape.
+ ///
+ /// The name of the schema. Cannot be null or empty.
+ ///
+ /// The returned client.
+ ///
+ /// is null.
+ /// is empty.
+ IContentsClient DynamicContents(string schemaName);
+
+ ///
+ /// Gets a client instance to query and manage contents across all schemas.
+ ///
+ /// The type for the content entity.
+ /// The type that represents the data structure.
+ ///
+ /// The returned client.
+ ///
+ IContentsSharedClient SharedContents() where TEntity : Content where TData : class, new();
+
+ ///
+ /// Creates a to make all kind of authorized requests.
+ ///
+ ///
+ /// The returned client.
+ ///
+ HttpClient CreateHttpClient();
+}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ISquidexClientManager.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ISquidexClientManager.cs
deleted file mode 100644
index a9bf1afa..00000000
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/ISquidexClientManager.cs
+++ /dev/null
@@ -1,412 +0,0 @@
-// ==========================================================================
-// Squidex Headless CMS
-// ==========================================================================
-// Copyright (c) Squidex UG (haftungsbeschraenkt)
-// All rights reserved. Licensed under the MIT license.
-// ==========================================================================
-
-using Squidex.ClientLibrary.Management;
-
-namespace Squidex.ClientLibrary;
-
-///
-/// Provides access to all endpoints through individual clients and handles authentication.
-///
-public interface ISquidexClientManager
-{
- ///
- /// Gets the options that are used to initialize the client manager.
- ///
- ///
- /// The options that are used to initialize the client manager.
- ///
- ///
- /// This object is frozen and cannot be changed later.
- ///
- SquidexOptions Options { get; }
-
- ///
- /// Gets the name of the App.
- ///
- ///
- /// The name of the App.
- ///
- string App { get; }
-
- ///
- /// Generates the URL to the image with the specified ID.
- ///
- /// The ID of the asset.
- ///
- /// THe URL to the image.
- ///
- string? GenerateImageUrl(string? id);
-
- ///
- /// Generates the URL to the image with the first specified ID.
- ///
- /// The ID of the asset.
- ///
- /// THe URL to the image.
- ///
- string? GenerateImageUrl(IEnumerable? id);
-
- ///
- /// Generates an absolute URL.
- ///
- /// The relative URL.
- ///
- /// The absolute URL.
- ///
- string? GenerateUrl(string? relativeUrl);
-
- ///
- /// Generates an absolute URL for the asset CDN.
- ///
- /// The relative URL.
- /// Asset CDN not configured.
- ///
- /// The absolute URL.
- ///
- string? GenerateAssetCDNUrl(string relativeUrl);
-
- ///
- /// Generates an absolute URL for the content CDN.
- ///
- /// The relative URL.
- /// Content CDN not configured.
- ///
- /// The absolute URL.
- ///
- string? GenerateContentCDNUrl(string relativeUrl);
-
- ///
- /// Creates a client instance to query and manage app configuration.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IAppsClient CreateAppsClient();
-
- ///
- /// Creates a client instance to query and manage assets.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IAssetsClient CreateAssetsClient();
-
- ///
- /// Creates a client instance to query and manage backups.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IBackupsClient CreateBackupsClient();
-
- ///
- /// Creates a client instance to query and manage comments.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- ICommentsClient CreateCommentsClient();
-
- ///
- /// Creates a client instance to query diagnostics data.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IDiagnosticsClient CreateDiagnosticsClient();
-
- ///
- /// Creates a client instance to query and manage event consumers.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IEventConsumersClient CreateEventConsumersClient();
-
- ///
- /// Creates a client instance to query and manage histories.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IHistoryClient CreateHistoryClient();
-
- ///
- /// Creates a client instance to query all supported languages.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- ILanguagesClient CreateLanguagesClient();
-
- ///
- /// Creates a client instance to ping the server for monitoring.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IPingClient CreatePingClient();
-
- ///
- /// Creates a client instance to query and manage plans and subscriptions.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IPlansClient CreatePlansClient();
-
- ///
- /// Creates a client instance to query and manage rules.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IRulesClient CreateRulesClient();
-
- ///
- /// Creates a client instance to query and manage schemas.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- ISchemasClient CreateSchemasClient();
-
- ///
- /// Creates a client instance to make searches across content and records.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- ISearchClient CreateSearchClient();
-
- ///
- /// Creates a client instance to query statistics.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IStatisticsClient CreateStatisticsClient();
-
- ///
- /// Creates a client instance to query and manage teams.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- ITeamsClient CreateTeamsClient();
-
- ///
- /// Creates a client instance to query templates.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- ITemplatesClient CreateTemplatesClient();
-
- ///
- /// Creates a client instance to translate content.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- ITranslationsClient CreateTranslationsClient();
-
- ///
- /// Creates a client instance to query user information.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IUsersClient CreateUsersClient();
-
- ///
- /// Creates a client instance to query and manage users as administrator.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IUserManagementClient CreateUserManagementClient();
-
- ///
- /// Creates a client instance to query and manage untyped rules.
- ///
- /// The optional app name.
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IExtendableRulesClient CreateExtendableRulesClient(string? appName = null);
-
- ///
- /// Creates a client instance to query and manage contents for a schema.
- ///
- /// The type for the content entity.
- /// The type that represents the data structure.
- /// The name of the schema. Cannot be null or empty.
- ///
- /// The created client.
- ///
- /// is null.
- /// is empty.
- ///
- /// Do not create new clients frequently.
- ///
- IContentsClient CreateContentsClient(string schemaName) where TEntity : Content where TData : class, new();
-
- ///
- /// Creates a client instance to query and manage contents for an app and schema.
- ///
- /// The type for the content entity.
- /// The type that represents the data structure.
- /// The name of the app. Cannot be null or empty.
- /// The name of the schema. Cannot be null or empty.
- ///
- /// The created client.
- ///
- /// is null.
- /// is null.
- /// is empty.
- /// is empty.
- ///
- /// Do not create new clients frequently.
- ///
- IContentsClient CreateContentsClient(string appName, string schemaName) where TEntity : Content where TData : class, new();
-
- ///
- /// Creates a client instance to query and manage contents for a schema with dynamic data shape.
- ///
- /// The name of the schema. Cannot be null or empty.
- ///
- /// The created client.
- ///
- /// is null.
- /// is empty.
- ///
- /// Do not create new clients frequently.
- ///
- IContentsClient CreateDynamicContentsClient(string schemaName);
-
- ///
- /// Creates a client instance to query and manage contents for an app and schema with dynamic data shape.
- ///
- /// The name of the app. Cannot be null or empty.
- /// The name of the schema. Cannot be null or empty.
- ///
- /// The created client.
- ///
- /// is null.
- /// is null.
- /// is empty.
- /// is empty.
- ///
- /// Do not create new clients frequently.
- ///
- IContentsClient CreateDynamicContentsClient(string appName, string schemaName);
-
- ///
- /// Creates a client instance to query and manage contents across all schemas.
- ///
- /// The type for the content entity.
- /// The type that represents the data structure.
- /// The optional app name.
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IContentsSharedClient CreateSharedContentsClient(string? appName = null) where TEntity : Content where TData : class, new();
-
- ///
- /// Creates a client instance to query and manage contents across all schemas with dynamic data shape.
- ///
- /// The optional app name.
- ///
- /// The created client.
- ///
- ///
- /// Do not create new clients frequently.
- ///
- IContentsSharedClient CreateSharedDynamicContentsClient(string? appName = null);
-
- ///
- /// Creates a to make all kind of authorized requests.
- ///
- ///
- /// The created client.
- ///
- ///
- /// Remember to return the client after each request.
- ///
- HttpClient CreateHttpClient();
-
- ///
- /// Returns the http client.
- ///
- /// The HTTP client to return.
- void ReturnHttpClient(HttpClient httpClient);
-}
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Management/AssetsClient.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Management/AssetsClient.cs
index ab074522..d8eee125 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Management/AssetsClient.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Management/AssetsClient.cs
@@ -17,19 +17,17 @@ public partial interface IAssetsClient
///
/// Gets the upload progress.
///
- /// The name of the app.
/// The file id of the upload.
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
///
/// The upload progress in bytes.
///
- Task GetUploadProgressAsync(string app, string fileId,
+ Task GetUploadProgressAsync(string fileId,
CancellationToken cancellationToken = default);
///
/// Upload a new asset using tus protocol.
///
- /// The name of the app.
/// The file to upload.
/// Optional arguments.
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
@@ -37,24 +35,22 @@ Task GetUploadProgressAsync(string app, string fileId,
/// Task for completion.
///
/// A server side error occurred.
- Task UploadAssetAsync(string app, FileParameter file, AssetUploadOptions options = default,
+ Task UploadAssetAsync(FileParameter file, AssetUploadOptions options = default,
CancellationToken cancellationToken = default);
/// Get assets.
- /// The name of the app.
/// The optional asset query.
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
///
/// Assets returned.
///
/// A server side error occurred.
- Task GetAssetsAsync(string app, AssetQuery? query = null,
+ Task GetAssetsAsync(AssetQuery? query = null,
CancellationToken cancellationToken = default);
///
/// Get assets.
///
- /// The name of the app.
/// The callback that is invoke for each asset.
/// The number of assets per request.
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
@@ -62,13 +58,12 @@ Task GetAssetsAsync(string app, AssetQuery? query = null,
/// Assets returned.
///
/// A server side error occurred.
- Task GetAllAsync(string app, Func callback, int batchSize = 200,
+ Task GetAllAsync(Func callback, int batchSize = 200,
CancellationToken cancellationToken = default);
///
/// Get assets.
///
- /// The name of the app.
/// The callback that is invoke for each asset.
/// The optional asset query.
/// The number of assets per request.
@@ -77,7 +72,7 @@ Task GetAllAsync(string app, Func callback, int batchSize = 200,
/// Assets returned.
///
/// A server side error occurred.
- Task GetAllByQueryAsync(string app, Func callback, AssetQuery? query = null, int batchSize = 200,
+ Task GetAllByQueryAsync(Func callback, AssetQuery? query = null, int batchSize = 200,
CancellationToken cancellationToken = default);
}
@@ -96,59 +91,47 @@ public partial class AssetsClient
}
///
- public async Task GetUploadProgressAsync(string app, string fileId,
+ public async Task GetUploadProgressAsync(string fileId,
CancellationToken cancellationToken = default)
{
Guard.NotNull(fileId, nameof(fileId));
- var url = $"api/apps/{app}/assets/tus/";
+ var url = $"api/apps/{_options.AppName}/assets/tus/";
- var httpClient = _httpClientProvider.Get();
- try
- {
- return await httpClient.GetUploadProgressAsync(url, fileId, cancellationToken);
- }
- finally
- {
- _httpClientProvider.Return(httpClient);
- }
+ var httpClient = _options.ClientProvider.Get();
+
+ return await httpClient.GetUploadProgressAsync(url, fileId, cancellationToken);
}
///
- public async Task UploadAssetAsync(string app, FileParameter file, AssetUploadOptions options = default,
+ public async Task UploadAssetAsync(FileParameter file, AssetUploadOptions options = default,
CancellationToken cancellationToken = default)
{
Guard.NotNull(file, nameof(file));
- var url = $"api/apps/{app}/assets/tus";
+ var url = $"api/apps/{_options.AppName}/assets/tus";
- var httpClient = _httpClientProvider.Get();
- try
- {
- await httpClient.UploadWithProgressAsync(url, file.ToUploadFile(), options.ToOptions(this), cancellationToken);
- }
- finally
- {
- _httpClientProvider.Return(httpClient);
- }
+ var httpClient = _options.ClientProvider.Get();
+
+ await httpClient.UploadWithProgressAsync(url, file.ToUploadFile(), options.ToOptions(this), cancellationToken);
}
///
- public Task GetAssetsAsync(string app, AssetQuery? query = null,
+ public Task GetAssetsAsync(AssetQuery? query = null,
CancellationToken cancellationToken = default)
{
- return GetAssetsAsync(app, query?.Top, query?.Skip, query?.OrderBy, query?.Filter, query?.ParentId, query?.ToIdString(), query?.ToQueryJson(), cancellationToken);
+ return GetAssetsAsync(query?.Top, query?.Skip, query?.OrderBy, query?.Filter, query?.ParentId, query?.ToIdString(), query?.ToQueryJson(), cancellationToken);
}
///
- public Task GetAllAsync(string app, Func callback, int batchSize = 200,
+ public Task GetAllAsync(Func callback, int batchSize = 200,
CancellationToken cancellationToken = default)
{
- return GetAllByQueryAsync(app, callback, null, batchSize, cancellationToken);
+ return GetAllByQueryAsync(callback, null, batchSize, cancellationToken);
}
///
- public async Task GetAllByQueryAsync(string app, Func callback, AssetQuery? query = null, int batchSize = 200,
+ public async Task GetAllByQueryAsync(Func callback, AssetQuery? query = null, int batchSize = 200,
CancellationToken cancellationToken = default)
{
Guard.Between(batchSize, 10, 10_000, nameof(batchSize));
@@ -163,7 +146,7 @@ public async Task GetAllByQueryAsync(string app, Func callback,
{
var isAnyAdded = false;
- var getResult = await GetAssetsAsync(app, query, cancellationToken);
+ var getResult = await GetAssetsAsync(query, cancellationToken);
foreach (var item in getResult.Items)
{
diff --git a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Management/Generated.cs b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Management/Generated.cs
index 090e672e..ccdd03f3 100644
--- a/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Management/Generated.cs
+++ b/csharp/Squidex.ClientLibrary/Squidex.ClientLibrary/Management/Generated.cs
@@ -92,12 +92,12 @@ public partial interface IUserManagementClient
[System.CodeDom.Compiler.GeneratedCode("NSwag", "13.17.0.0 (NJsonSchema v10.8.0.0 (Newtonsoft.Json v9.0.0.0))")]
public partial class UserManagementClient : IUserManagementClient
{
- private Squidex.ClientLibrary.Configuration.IHttpClientProvider _httpClientProvider;
+ private Squidex.ClientLibrary.SquidexOptions _options;
private System.Lazy _settings;
- public UserManagementClient(Squidex.ClientLibrary.Configuration.IHttpClientProvider httpClientProvider)
+ public UserManagementClient(Squidex.ClientLibrary.SquidexOptions options)
{
- _httpClientProvider = httpClientProvider;
+ _options = options;
_settings = new System.Lazy(CreateSerializerSettings);
}
@@ -129,6 +129,7 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
{
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append("api/user-management?");
+ urlBuilder_.Replace("{app}", _options.AppName);
if (query != null)
{
urlBuilder_.Append(System.Uri.EscapeDataString("query") + "=").Append(System.Uri.EscapeDataString(ConvertToString(query, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
@@ -143,12 +144,11 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
}
urlBuilder_.Length--;
- var client_ = _httpClientProvider.Get();
+ var client_ = _options.ClientProvider.Get();
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
-
request_.Method = new System.Net.Http.HttpMethod("GET");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
@@ -207,7 +207,6 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
}
finally
{
- _httpClientProvider.Return(client_);
}
}
@@ -225,13 +224,13 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append("api/user-management");
+ urlBuilder_.Replace("{app}", _options.AppName);
- var client_ = _httpClientProvider.Get();
+ var client_ = _options.ClientProvider.Get();
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
-
var json_ = Newtonsoft.Json.JsonConvert.SerializeObject(request, _settings.Value);
var content_ = new System.Net.Http.StringContent(json_);
content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
@@ -304,7 +303,6 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
}
finally
{
- _httpClientProvider.Return(client_);
}
}
@@ -322,14 +320,14 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append("api/user-management/{id}");
+ urlBuilder_.Replace("{app}", _options.AppName);
urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture)));
- var client_ = _httpClientProvider.Get();
+ var client_ = _options.ClientProvider.Get();
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
-
request_.Method = new System.Net.Http.HttpMethod("GET");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
@@ -394,7 +392,6 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
}
finally
{
- _httpClientProvider.Return(client_);
}
}
@@ -416,14 +413,14 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append("api/user-management/{id}");
+ urlBuilder_.Replace("{app}", _options.AppName);
urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture)));
- var client_ = _httpClientProvider.Get();
+ var client_ = _options.ClientProvider.Get();
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
-
var json_ = Newtonsoft.Json.JsonConvert.SerializeObject(request, _settings.Value);
var content_ = new System.Net.Http.StringContent(json_);
content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
@@ -502,7 +499,6 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
}
finally
{
- _httpClientProvider.Return(client_);
}
}
@@ -520,14 +516,14 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append("api/user-management/{id}");
+ urlBuilder_.Replace("{app}", _options.AppName);
urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture)));
- var client_ = _httpClientProvider.Get();
+ var client_ = _options.ClientProvider.Get();
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
-
request_.Method = new System.Net.Http.HttpMethod("DELETE");
PrepareRequest(client_, request_, urlBuilder_);
@@ -606,7 +602,6 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
}
finally
{
- _httpClientProvider.Return(client_);
}
}
@@ -624,14 +619,14 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append("api/user-management/{id}/lock");
+ urlBuilder_.Replace("{app}", _options.AppName);
urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture)));
- var client_ = _httpClientProvider.Get();
+ var client_ = _options.ClientProvider.Get();
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
-
request_.Content = new System.Net.Http.StringContent(string.Empty, System.Text.Encoding.UTF8, "application/json");
request_.Method = new System.Net.Http.HttpMethod("PUT");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
@@ -717,7 +712,6 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
}
finally
{
- _httpClientProvider.Return(client_);
}
}
@@ -735,14 +729,14 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append("api/user-management/{id}/unlock");
+ urlBuilder_.Replace("{app}", _options.AppName);
urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture)));
- var client_ = _httpClientProvider.Get();
+ var client_ = _options.ClientProvider.Get();
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
-
request_.Content = new System.Net.Http.StringContent(string.Empty, System.Text.Encoding.UTF8, "application/json");
request_.Method = new System.Net.Http.HttpMethod("PUT");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
@@ -828,7 +822,6 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
}
finally
{
- _httpClientProvider.Return(client_);
}
}
@@ -845,8 +838,6 @@ public ObjectResponseResult(T responseObject, string responseText)
public string Text { get; }
}
- public bool ReadResponseAsString { get; set; }
-
protected virtual async System.Threading.Tasks.Task> ReadObjectResponseAsync(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Threading.CancellationToken cancellationToken)
{
if (response == null || response.Content == null)
@@ -854,7 +845,7 @@ protected virtual async System.Threading.Tasks.Task> Rea
return new ObjectResponseResult(default(T), string.Empty);
}
- if (ReadResponseAsString)
+ if (_options.ReadResponseAsString)
{
var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
try
@@ -982,12 +973,12 @@ public partial interface IUsersClient
[System.CodeDom.Compiler.GeneratedCode("NSwag", "13.17.0.0 (NJsonSchema v10.8.0.0 (Newtonsoft.Json v9.0.0.0))")]
public partial class UsersClient : IUsersClient
{
- private Squidex.ClientLibrary.Configuration.IHttpClientProvider _httpClientProvider;
+ private Squidex.ClientLibrary.SquidexOptions _options;
private System.Lazy _settings;
- public UsersClient(Squidex.ClientLibrary.Configuration.IHttpClientProvider httpClientProvider)
+ public UsersClient(Squidex.ClientLibrary.SquidexOptions options)
{
- _httpClientProvider = httpClientProvider;
+ _options = options;
_settings = new System.Lazy(CreateSerializerSettings);
}
@@ -1016,13 +1007,13 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
{
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append("api");
+ urlBuilder_.Replace("{app}", _options.AppName);
- var client_ = _httpClientProvider.Get();
+ var client_ = _options.ClientProvider.Get();
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
-
request_.Method = new System.Net.Http.HttpMethod("GET");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
@@ -1081,7 +1072,6 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
}
finally
{
- _httpClientProvider.Return(client_);
}
}
@@ -1099,18 +1089,18 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
{
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append("api/users?");
+ urlBuilder_.Replace("{app}", _options.AppName);
if (query != null)
{
urlBuilder_.Append(System.Uri.EscapeDataString("query") + "=").Append(System.Uri.EscapeDataString(ConvertToString(query, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
}
urlBuilder_.Length--;
- var client_ = _httpClientProvider.Get();
+ var client_ = _options.ClientProvider.Get();
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
-
request_.Method = new System.Net.Http.HttpMethod("GET");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
@@ -1169,7 +1159,6 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
}
finally
{
- _httpClientProvider.Return(client_);
}
}
@@ -1187,14 +1176,14 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append("api/users/{id}");
+ urlBuilder_.Replace("{app}", _options.AppName);
urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture)));
- var client_ = _httpClientProvider.Get();
+ var client_ = _options.ClientProvider.Get();
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
-
request_.Method = new System.Net.Http.HttpMethod("GET");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
@@ -1259,7 +1248,6 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
}
finally
{
- _httpClientProvider.Return(client_);
}
}
@@ -1277,14 +1265,14 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append("api/users/{id}/picture");
+ urlBuilder_.Replace("{app}", _options.AppName);
urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture)));
- var client_ = _httpClientProvider.Get();
+ var client_ = _options.ClientProvider.Get();
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
-
request_.Method = new System.Net.Http.HttpMethod("GET");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream"));
@@ -1347,7 +1335,6 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
}
finally
{
- _httpClientProvider.Return(client_);
}
}
@@ -1364,8 +1351,6 @@ public ObjectResponseResult(T responseObject, string responseText)
public string Text { get; }
}
- public bool ReadResponseAsString { get; set; }
-
protected virtual async System.Threading.Tasks.Task> ReadObjectResponseAsync(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Threading.CancellationToken cancellationToken)
{
if (response == null || response.Content == null)
@@ -1373,7 +1358,7 @@ protected virtual async System.Threading.Tasks.Task> Rea
return new ObjectResponseResult(default(T), string.Empty);
}
- if (ReadResponseAsString)
+ if (_options.ReadResponseAsString)
{
var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
try
@@ -1462,23 +1447,22 @@ public partial interface ITranslationsClient
///
/// Translate a text.
///
- /// The name of the app.
/// The translation request.
/// Text translated.
/// A server side error occurred.
- System.Threading.Tasks.Task PostTranslationAsync(string app, TranslateDto request, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
+ System.Threading.Tasks.Task PostTranslationAsync(TranslateDto request, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
[System.CodeDom.Compiler.GeneratedCode("NSwag", "13.17.0.0 (NJsonSchema v10.8.0.0 (Newtonsoft.Json v9.0.0.0))")]
public partial class TranslationsClient : ITranslationsClient
{
- private Squidex.ClientLibrary.Configuration.IHttpClientProvider _httpClientProvider;
+ private Squidex.ClientLibrary.SquidexOptions _options;
private System.Lazy _settings;
- public TranslationsClient(Squidex.ClientLibrary.Configuration.IHttpClientProvider httpClientProvider)
+ public TranslationsClient(Squidex.ClientLibrary.SquidexOptions options)
{
- _httpClientProvider = httpClientProvider;
+ _options = options;
_settings = new System.Lazy(CreateSerializerSettings);
}
@@ -1501,30 +1485,23 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
///
/// Translate a text.
///
- /// The name of the app.
/// The translation request.
/// Text translated.
/// A server side error occurred.
- public virtual async System.Threading.Tasks.Task PostTranslationAsync(string app, TranslateDto request, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
+ public virtual async System.Threading.Tasks.Task PostTranslationAsync(TranslateDto request, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
- if (app == null)
- throw new System.ArgumentNullException("app");
-
if (request == null)
throw new System.ArgumentNullException("request");
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append("api/apps/{app}/translations");
- urlBuilder_.Replace("{app}", System.Uri.EscapeDataString(ConvertToString(app, System.Globalization.CultureInfo.InvariantCulture)));
+ urlBuilder_.Replace("{app}", _options.AppName);
- var client_ = _httpClientProvider.Get();
+ var client_ = _options.ClientProvider.Get();
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
-
- request_.Headers.TryAddWithoutValidation(SpecialHeaders.AppName, app);
-
var json_ = Newtonsoft.Json.JsonConvert.SerializeObject(request, _settings.Value);
var content_ = new System.Net.Http.StringContent(json_);
content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
@@ -1597,7 +1574,6 @@ private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
}
finally
{
- _httpClientProvider.Return(client_);
}
}
@@ -1614,8 +1590,6 @@ public ObjectResponseResult(T responseObject, string responseText)
public string Text { get; }
}
- public bool ReadResponseAsString { get; set; }
-
protected virtual async System.Threading.Tasks.Task> ReadObjectResponseAsync(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Threading.CancellationToken cancellationToken)
{
if (response == null || response.Content == null)
@@ -1623,7 +1597,7 @@ protected virtual async System.Threading.Tasks.Task