repo_id
stringlengths 8
105
| file_path
stringlengths 28
162
| content
stringlengths 15
661k
| __index_level_0__
int64 0
0
|
---|---|---|---|
raw_data\ibanity-dotnet\samples\webapp\wwwroot\lib | raw_data\ibanity-dotnet\samples\webapp\wwwroot\lib\jquery-validation-unobtrusive\LICENSE.txt | Copyright (c) .NET Foundation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
these files except in compliance with the License. You may obtain a copy of the
License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
| 0 |
raw_data\ibanity-dotnet\samples | raw_data\ibanity-dotnet\samples\webhooks\appsettings.Development.json | {
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
| 0 |
raw_data\ibanity-dotnet\samples | raw_data\ibanity-dotnet\samples\webhooks\appsettings.json | {
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Ibanity": {
"Endpoint": "https://api.ibanity.com",
"Certificates": {
"Client": {
"Path": "foo/certificate.pfx",
"Passphrase": "bar"
}
}
}
}
| 0 |
raw_data\ibanity-dotnet\samples | raw_data\ibanity-dotnet\samples\webhooks\Program.cs | using Ibanity.Apis.Client;
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
var ibanityService = new IbanityServiceBuilder().
SetEndpoint(configuration["Ibanity:Endpoint"]).
AddClientCertificate(
configuration["Ibanity:Certificates:Client:Path"],
configuration["Ibanity:Certificates:Client:Passphrase"]).
Build();
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton(ibanityService);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
| 0 |
raw_data\ibanity-dotnet\samples | raw_data\ibanity-dotnet\samples\webhooks\Webhooks.csproj | <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Client\Client.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
</Project>
| 0 |
raw_data\ibanity-dotnet\samples\webhooks | raw_data\ibanity-dotnet\samples\webhooks\Controllers\WebhooksController.cs | using Ibanity.Apis.Client;
using Ibanity.Apis.Client.Webhooks.Models.PontoConnect;
using Microsoft.AspNetCore.Mvc;
namespace webhooks.Controllers;
[ApiController]
[Route("/")]
public class WebhooksController : ControllerBase
{
private readonly ILogger<WebhooksController> _logger;
private readonly IIbanityService _ibanityService;
public WebhooksController(ILogger<WebhooksController> logger, IIbanityService ibanityService)
{
_logger = logger;
_ibanityService = ibanityService;
}
[HttpPost]
public async Task<IActionResult> Post([FromHeader] string signature)
{
string payload;
using (var reader = new StreamReader(Request.Body))
payload = await reader.ReadToEndAsync();
var content = await _ibanityService.Webhooks.VerifyAndDeserialize(payload, signature);
switch (content)
{
case IntegrationAccountAdded integrationAccountAdded:
_logger.LogInformation($"Integration account added webhook received: {content.Id} (account {integrationAccountAdded.AccountId})");
break;
default:
_logger.LogInformation($"Webhook received: {content.Id} ({content.GetType().Name})");
break;
}
return Ok(new { Message = "Webhook received: " + payload.Length });
}
}
| 0 |
raw_data\ibanity-dotnet\samples\webhooks | raw_data\ibanity-dotnet\samples\webhooks\Properties\launchSettings.json | {
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:3163",
"sslPort": 44328
}
},
"profiles": {
"webhooks": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5227",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
| 0 |
raw_data\ibanity-dotnet | raw_data\ibanity-dotnet\scripts\get-auth-code | #!/usr/bin/env python3
from argparse import ArgumentParser
import random
import string
from base64 import b64encode
from hashlib import sha256
from os import system
from urllib.parse import quote, urlparse, parse_qs
from http.server import BaseHTTPRequestHandler, HTTPServer
parser = ArgumentParser()
parser.add_argument("--endpoint")
parser.add_argument("--clientid")
parser.add_argument("--scope")
parser.add_argument("--codeverifier")
args = parser.parse_args()
statechars = string.digits + string.ascii_letters
state = ''.join(random.choice(statechars) for _ in range(64))
codechallengehash = sha256(args.codeverifier.encode()).digest()
codechallenge = b64encode(codechallengehash, b'-_').decode('UTF-8').rstrip('=')
challengemethod = "S256"
redirect = ("localhost", 8080)
authuri = "%s?client_id=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s&code_challenge=%s&code_challenge_method=%s" \
% (args.endpoint, args.clientid, quote("http://%s:%d" % redirect), quote(args.scope), state, codechallenge, challengemethod)
system(f"if command -v xdg-open &> /dev/null; then xdg-open '{authuri}'; elif command -v cygstart &> /dev/null; then cygstart '{authuri}'; elif command -v open &> /dev/null; then open '{authuri}'; else echo '{authuri}' 1>&2; fi")
class CallbackServer(BaseHTTPRequestHandler):
def do_GET(self):
query_components = parse_qs(urlparse(self.path).query)
if "error" in query_components:
errormessage = query_components["error"][0]
self.send_response(400)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write(bytes("Failure: " + errormessage, "utf-8"))
raise Exception(errormessage)
receivedstate = query_components["state"][0]
if receivedstate != state:
self.send_response(400)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write(bytes("Failure: invalid state", "utf-8"))
raise Exception("Invalid state received")
authorizationcode = query_components["code"][0]
print(authorizationcode)
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write(bytes("You can go back to shell", "utf-8"))
def log_message(self, format, *args):
pass
webServer = HTTPServer(redirect, CallbackServer)
webServer.handle_request()
| 0 |
raw_data\ibanity-dotnet | raw_data\ibanity-dotnet\scripts\get-integration-env | #!/usr/bin/env bash
grep -Ev "^$|^#" "$(dirname "$BASH_SOURCE")/../.env"
code_verifier=$(openssl rand -hex 32)
echo PONTO_CONNECT_CODE_VERIFIER=$code_verifier
echo PONTO_CONNECT_REDIRECT_URI=http://localhost:8080
grep -Eq '^PONTO_CONNECT_REFRESH_TOKEN=.+$' "$(dirname "$BASH_SOURCE")/../.env" || echo PONTO_CONNECT_AUTHORIZATION_CODE="$($(dirname "$BASH_SOURCE")/get-auth-code \
--endpoint 'https://sandbox-authorization.myponto.com/oauth2/auth' \
--clientid "$(awk -F= '{if ($1 == "PONTO_CONNECT_CLIENT_ID") print $2 }' $(dirname "$BASH_SOURCE")/../.env)" \
--scope 'offline_access ai pi name' \
--codeverifier $code_verifier)"
code_verifier=$(openssl rand -hex 32)
echo ISABEL_CONNECT_REDIRECT_URI=http://localhost:8080
| 0 |
raw_data\ibanity-dotnet\src | raw_data\ibanity-dotnet\src\Client\Client.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>Ibanity</AssemblyName>
<RootNamespace>Ibanity.Apis.$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>7.3</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AnalysisMode>Recommended</AnalysisMode>
<CodeAnalysisRuleSet>../../Analyzers.ruleset</CodeAnalysisRuleSet>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<PropertyGroup>
<PackageId>Ibanity</PackageId>
<Title>Ibanity .NET client library</Title>
<Description>Ibanity .NET client library</Description>
<Authors>Isabel NV</Authors>
<PackageIcon>icon.png</PackageIcon>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageProjectUrl>https://documentation.ibanity.com/</PackageProjectUrl>
<RepositoryUrl>https://github.com/ibanity/ibanity-dotnet</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Copyright>Copyright (c) 2022 Isabel NV</Copyright>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
<ItemGroup>
<None Include="../../assets/icon.png" Pack="true" Visible="false" PackagePath="" />
<None Include="../../README.md" Pack="true" Visible="false" PackagePath="" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="[10.0.3,14)" />
</ItemGroup>
</Project>
| 0 |
raw_data\ibanity-dotnet\src | raw_data\ibanity-dotnet\src\Client\HttpSignatureServiceBuilder.cs | using System;
using System.Security.Cryptography.X509Certificates;
using Ibanity.Apis.Client.Crypto;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Utils;
using Ibanity.Apis.Client.Utils.Logging;
namespace Ibanity.Apis.Client
{
/// <summary>
/// Builds an <see cref="IHttpSignatureService" /> instance.
/// </summary>
public class HttpSignatureServiceBuilder : IHttpSignatureServiceEndpointBuilder, IHttpSignatureServiceCertificateBuilder, IHttpSignatureServiceOptionalPropertiesBuilder
{
private readonly IClock _clock;
private Uri _endpoint;
private string _certificateId;
private X509Certificate2 _certificate;
private ILoggerFactory _loggerFactory;
internal HttpSignatureServiceBuilder(IClock clock) =>
_clock = clock;
/// <inheritdoc />
public IHttpSignatureServiceCertificateBuilder SetEndpoint(Uri endpoint)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
return this;
}
/// <inheritdoc />
public IHttpSignatureServiceCertificateBuilder SetEndpoint(string endpoint)
{
if (string.IsNullOrWhiteSpace(endpoint))
throw new ArgumentException($"'{nameof(endpoint)}' cannot be null or whitespace.", nameof(endpoint));
return SetEndpoint(new Uri(endpoint));
}
IHttpSignatureServiceOptionalPropertiesBuilder IHttpSignatureServiceCertificateBuilder.AddCertificate(string id, X509Certificate2 certificate)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentException($"'{nameof(id)}' cannot be null or whitespace.", nameof(id));
_certificateId = id;
_certificate = certificate ?? throw new ArgumentNullException(nameof(certificate));
return this;
}
IHttpSignatureServiceOptionalPropertiesBuilder IHttpSignatureServiceCertificateBuilder.AddCertificate(string id, string path, string password)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentException($"'{nameof(id)}' cannot be null or whitespace.", nameof(id));
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentException($"'{nameof(path)}' cannot be null or whitespace.", nameof(path));
if (string.IsNullOrWhiteSpace(password))
throw new ArgumentException($"'{nameof(password)}' cannot be null or whitespace.", nameof(password));
return ((IHttpSignatureServiceCertificateBuilder)this).AddCertificate(id, new X509Certificate2(path, password));
}
IHttpSignatureServiceOptionalPropertiesBuilder IHttpSignatureServiceOptionalPropertiesBuilder.AddLogging(ILogger logger) =>
((IHttpSignatureServiceOptionalPropertiesBuilder)this).AddLogging(new SimpleLoggerFactory(logger ?? throw new ArgumentNullException(nameof(logger))));
IHttpSignatureServiceOptionalPropertiesBuilder IHttpSignatureServiceOptionalPropertiesBuilder.AddLogging(ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
return this;
}
IHttpSignatureService IHttpSignatureServiceOptionalPropertiesBuilder.Build()
{
var loggerFactory = _loggerFactory == null
? (ILoggerFactory)new SimpleLoggerFactory(NullLogger.Instance)
: new LoggerFactoryNotNullDecorator(_loggerFactory);
return new HttpSignatureService(
loggerFactory,
new Sha512Digest(),
new RsaSsaPssSignature(_certificate),
_clock ?? new Clock(),
new HttpSignatureString(_endpoint),
_certificateId);
}
}
/// <summary>
/// Mandatory endpoint builder.
/// </summary>
public interface IHttpSignatureServiceEndpointBuilder
{
/// <summary>
/// Define Ibanity API base URI.
/// </summary>
/// <param name="endpoint">Ibanity API base URI</param>
/// <returns>The builder to be used to pursue configuration</returns>
IHttpSignatureServiceCertificateBuilder SetEndpoint(Uri endpoint);
/// <summary>
/// Define Ibanity API base URI.
/// </summary>
/// <param name="endpoint">Ibanity API base URI</param>
/// <returns>The builder to be used to pursue configuration</returns>
IHttpSignatureServiceCertificateBuilder SetEndpoint(string endpoint);
}
/// <summary>
/// Mandatory certificate builder.
/// </summary>
public interface IHttpSignatureServiceCertificateBuilder
{
/// <summary>
/// Define signature certificate.
/// </summary>
/// <param name="id">Certificate ID from the Developer Portal</param>
/// <param name="certificate">Signature certificate</param>
/// <returns>The builder to be used to pursue configuration</returns>
IHttpSignatureServiceOptionalPropertiesBuilder AddCertificate(string id, X509Certificate2 certificate);
/// <summary>
/// Define signature certificate.
/// </summary>
/// <param name="id">Certificate ID from the Developer Portal</param>
/// <param name="path">Signature certificate path</param>
/// <param name="password">Signature certificate passphrase</param>
/// <returns>The builder to be used to pursue configuration</returns>
IHttpSignatureServiceOptionalPropertiesBuilder AddCertificate(string id, string path, string password);
}
/// <summary>
/// Optional configuration builder.
/// </summary>
public interface IHttpSignatureServiceOptionalPropertiesBuilder
{
/// <summary>
/// Configure logger.
/// </summary>
/// <param name="logger">Logger instance that will be used within the whole library</param>
/// <returns>The builder to be used to pursue configuration</returns>
IHttpSignatureServiceOptionalPropertiesBuilder AddLogging(ILogger logger);
/// <summary>
/// Configure logger factory.
/// </summary>
/// <param name="loggerFactory">Logger factory will be called in all library-created instances to get named loggers</param>
/// <returns>The builder to be used to pursue configuration</returns>
IHttpSignatureServiceOptionalPropertiesBuilder AddLogging(ILoggerFactory loggerFactory);
/// <summary>
/// Create the signature service instance.
/// </summary>
/// <returns>A ready-to-use service</returns>
IHttpSignatureService Build();
}
}
| 0 |
raw_data\ibanity-dotnet\src | raw_data\ibanity-dotnet\src\Client\IbanityException.cs | using System;
namespace Ibanity.Apis.Client
{
/// <summary>
/// Base exception for all Ibanity errors.
/// </summary>
public class IbanityException : ApplicationException
{
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="message">Error description</param>
public IbanityException(string message) : base(message) { }
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="message">Error description</param>
/// <param name="innerException">Original error</param>
public IbanityException(string message, Exception innerException) : base(message, innerException) { }
}
/// <summary>
/// Something is misconfigured.
/// </summary>
public class IbanityConfigurationException : IbanityException
{
/// <inheritdoc />
public IbanityConfigurationException(string message) : base(message) { }
}
}
| 0 |
raw_data\ibanity-dotnet\src | raw_data\ibanity-dotnet\src\Client\IbanityService.cs | using System;
using System.Net.Http;
using Ibanity.Apis.Client.Products.CodaboxConnect;
using Ibanity.Apis.Client.Products.eInvoicing;
using Ibanity.Apis.Client.Products.IsabelConnect;
using Ibanity.Apis.Client.Products.PontoConnect;
using Ibanity.Apis.Client.Products.XS2A;
using Ibanity.Apis.Client.Webhooks;
namespace Ibanity.Apis.Client
{
/// <inheritdoc />
public class IbanityService : IIbanityService
{
private readonly HttpClient _httpClient;
private bool _disposedValue;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="httpClient">Low-level HTTP client</param>
/// <param name="pontoConnectClient">Ponto Connect service</param>
/// <param name="isabelConnectClient">Isabel Connect service</param>
/// <param name="eInvoicingClient">eInvoicing service</param>
/// <param name="codaboxConnectClient">Codabox Connect service</param>
/// <param name="xs2aClient">XS2A service</param>
/// <param name="webhooksService">Webhooks service</param>
public IbanityService(HttpClient httpClient, IPontoConnectClient pontoConnectClient, IIsabelConnectClient isabelConnectClient, IEInvoicingClient eInvoicingClient, ICodaboxConnectClient codaboxConnectClient, IXS2AClient xs2aClient, IWebhooksService webhooksService)
{
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
PontoConnect = pontoConnectClient ?? throw new ArgumentNullException(nameof(pontoConnectClient));
IsabelConnect = isabelConnectClient ?? throw new ArgumentNullException(nameof(isabelConnectClient));
EInvoicing = eInvoicingClient ?? throw new ArgumentNullException(nameof(eInvoicingClient));
CodaboxConnect = codaboxConnectClient ?? throw new ArgumentNullException(nameof(codaboxConnectClient));
XS2A = xs2aClient ?? throw new ArgumentNullException(nameof(xs2aClient));
Webhooks = webhooksService ?? throw new ArgumentNullException(nameof(webhooksService));
}
/// <inheritdoc />
public IPontoConnectClient PontoConnect { get; }
/// <inheritdoc />
public IIsabelConnectClient IsabelConnect { get; }
/// <inheritdoc />
public IEInvoicingClient EInvoicing { get; }
/// <inheritdoc />
public ICodaboxConnectClient CodaboxConnect { get; }
/// <inheritdoc />
public IXS2AClient XS2A { get; }
/// <inheritdoc />
public IWebhooksService Webhooks { get; }
/// <summary>
/// Release used resources.
/// </summary>
/// <param name="disposing">Dispose managed resources</param>
protected virtual void Dispose(bool disposing)
{
if (_disposedValue)
return;
if (disposing)
_httpClient.Dispose();
_disposedValue = true;
}
/// <summary>
/// Release used resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
/// <summary>
/// <para>Root Ibanity service.</para>
/// <para>It contains all the products.</para>
/// </summary>
public interface IIbanityService : IDisposable
{
/// <summary>
/// Get the Ponto Connect service.
/// </summary>
IPontoConnectClient PontoConnect { get; }
/// <summary>
/// Get the Isabel Connect service.
/// </summary>
IIsabelConnectClient IsabelConnect { get; }
/// <summary>
/// Get the eInvoicing service.
/// </summary>
IEInvoicingClient EInvoicing { get; }
/// <summary>
/// Get the Codabox Connect service.
/// </summary>
ICodaboxConnectClient CodaboxConnect { get; }
/// <summary>
/// Get the XS2A service.
/// </summary>
IXS2AClient XS2A { get; }
/// <summary>
/// Allows to validate and deserialize webhook payloads.
/// </summary>
IWebhooksService Webhooks { get; }
}
}
| 0 |
raw_data\ibanity-dotnet\src | raw_data\ibanity-dotnet\src\Client\IbanityServiceBuilder.cs | using System;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Http.OAuth2;
using Ibanity.Apis.Client.Products.CodaboxConnect;
using Ibanity.Apis.Client.Products.eInvoicing;
using Ibanity.Apis.Client.Products.IsabelConnect;
using Ibanity.Apis.Client.Products.PontoConnect;
using Ibanity.Apis.Client.Products.XS2A;
using Ibanity.Apis.Client.Utils;
using Ibanity.Apis.Client.Utils.Logging;
using Ibanity.Apis.Client.Webhooks;
using Ibanity.Apis.Client.Webhooks.Jwt;
namespace Ibanity.Apis.Client
{
/// <summary>
/// Builds an <see cref="IIbanityService" /> instance.
/// </summary>
public class IbanityServiceBuilder :
IIbanityServiceEndpointBuilder,
IIbanityServiceMutualTlsBuilder,
IIbanityServiceOptionalPropertiesBuilder
{
private Uri _endpoint;
private X509Certificate2 _clientCertificate;
IWebProxy _proxy;
private string _signatureCertificateId;
private X509Certificate2 _signatureCertificate;
private string _pontoConnectClientId;
private string _pontoConnectClientSecret;
private string _isabelConnectClientId;
private string _isabelConnectClientSecret;
private string _eInvoicingClientId;
private string _eInvoicingClientSecret;
private string _codaboxConnectClientId;
private string _codaboxConnectClientSecret;
private ILoggerFactory _loggerFactory;
private TimeSpan? _timeout;
private Action<HttpClient> _customizeClient;
private Action<HttpClientHandler> _customizeHandler;
private Action<HttpRequestMessage> _customizeRequest;
private int? _retryCount;
private TimeSpan? _retryBaseDelay;
private TimeSpan? _webhooksJwksCachingDuration;
private TimeSpan? _webhooksAllowedClockSkew;
/// <inheritdoc />
public IIbanityServiceMutualTlsBuilder SetEndpoint(Uri endpoint)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
return this;
}
/// <inheritdoc />
public IIbanityServiceMutualTlsBuilder SetEndpoint(string endpoint)
{
if (string.IsNullOrWhiteSpace(endpoint))
throw new ArgumentException($"'{nameof(endpoint)}' cannot be null or whitespace.", nameof(endpoint));
return SetEndpoint(new Uri(endpoint));
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceMutualTlsBuilder.AddClientCertificate(X509Certificate2 certificate)
{
_clientCertificate = certificate ?? throw new ArgumentNullException(nameof(certificate));
return this;
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceMutualTlsBuilder.AddClientCertificate(string path, string password)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentException($"'{nameof(path)}' cannot be null or whitespace.", nameof(path));
if (string.IsNullOrWhiteSpace(password))
throw new ArgumentException($"'{nameof(password)}' cannot be null or whitespace.", nameof(password));
return ((IIbanityServiceMutualTlsBuilder)this).AddClientCertificate(new X509Certificate2(path, password));
}
IIbanityServiceProxyBuilder IIbanityServiceMutualTlsBuilder.DisableMutualTls()
{
_clientCertificate = null;
return this;
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceProxyBuilder.AddProxy(IWebProxy proxy)
{
_proxy = proxy ?? throw new ArgumentNullException(nameof(proxy));
return this;
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceProxyBuilder.AddProxy(Uri endpoint) =>
((IIbanityServiceProxyBuilder)this).AddProxy(new WebProxy(endpoint ?? throw new ArgumentNullException(nameof(endpoint))));
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceProxyBuilder.AddProxy(string endpoint)
{
if (string.IsNullOrWhiteSpace(endpoint))
throw new ArgumentException($"'{nameof(endpoint)}' cannot be null or whitespace.", nameof(endpoint));
return ((IIbanityServiceProxyBuilder)this).AddProxy(new Uri(endpoint));
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceOptionalPropertiesBuilder.AddSignatureCertificate(string id, X509Certificate2 certificate)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentException($"'{nameof(id)}' cannot be null or whitespace.", nameof(id));
_signatureCertificateId = id;
_signatureCertificate = certificate ?? throw new ArgumentNullException(nameof(certificate));
return this;
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceOptionalPropertiesBuilder.AddSignatureCertificate(string id, string path, string password)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentException($"'{nameof(id)}' cannot be null or whitespace.", nameof(id));
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentException($"'{nameof(path)}' cannot be null or whitespace.", nameof(path));
if (string.IsNullOrWhiteSpace(password))
throw new ArgumentException($"'{nameof(password)}' cannot be null or whitespace.", nameof(password));
return ((IIbanityServiceOptionalPropertiesBuilder)this).AddSignatureCertificate(id, new X509Certificate2(path, password));
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceOptionalPropertiesBuilder.AddPontoConnectOAuth2Authentication(string clientId, string clientSecret)
{
if (string.IsNullOrWhiteSpace(clientId))
throw new ArgumentException($"'{nameof(clientId)}' cannot be null or whitespace.", nameof(clientId));
if (string.IsNullOrWhiteSpace(clientSecret))
throw new ArgumentException($"'{nameof(clientSecret)}' cannot be null or whitespace.", nameof(clientSecret));
_pontoConnectClientId = clientId;
_pontoConnectClientSecret = clientSecret;
return this;
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceOptionalPropertiesBuilder.AddIsabelConnectOAuth2Authentication(string clientId, string clientSecret)
{
if (string.IsNullOrWhiteSpace(clientId))
throw new ArgumentException($"'{nameof(clientId)}' cannot be null or whitespace.", nameof(clientId));
if (string.IsNullOrWhiteSpace(clientSecret))
throw new ArgumentException($"'{nameof(clientSecret)}' cannot be null or whitespace.", nameof(clientSecret));
_isabelConnectClientId = clientId;
_isabelConnectClientSecret = clientSecret;
return this;
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceOptionalPropertiesBuilder.AddEInvoicingOAuth2Authentication(string clientId, string clientSecret)
{
if (string.IsNullOrWhiteSpace(clientId))
throw new ArgumentException($"'{nameof(clientId)}' cannot be null or whitespace.", nameof(clientId));
if (string.IsNullOrWhiteSpace(clientSecret))
throw new ArgumentException($"'{nameof(clientSecret)}' cannot be null or whitespace.", nameof(clientSecret));
_eInvoicingClientId = clientId;
_eInvoicingClientSecret = clientSecret;
return this;
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceOptionalPropertiesBuilder.AddCodaboxConnectOAuth2Authentication(string clientId, string clientSecret)
{
if (string.IsNullOrWhiteSpace(clientId))
throw new ArgumentException($"'{nameof(clientId)}' cannot be null or whitespace.", nameof(clientId));
if (string.IsNullOrWhiteSpace(clientSecret))
throw new ArgumentException($"'{nameof(clientSecret)}' cannot be null or whitespace.", nameof(clientSecret));
_codaboxConnectClientId = clientId;
_codaboxConnectClientSecret = clientSecret;
return this;
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceOptionalPropertiesBuilder.AddLogging(ILogger logger) =>
((IIbanityServiceOptionalPropertiesBuilder)this).AddLogging(new SimpleLoggerFactory(logger ?? throw new ArgumentNullException(nameof(logger))));
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceOptionalPropertiesBuilder.AddLogging(ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
return this;
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceOptionalPropertiesBuilder.SetTimeout(TimeSpan timeout)
{
_timeout = timeout;
return this;
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceOptionalPropertiesBuilder.CustomizeHttpClient(Action<HttpClient> customizeClient, Action<HttpClientHandler> customizeHandler, Action<HttpRequestMessage> customizeRequest)
{
_customizeClient = customizeClient;
_customizeHandler = customizeHandler;
_customizeRequest = customizeRequest;
return this;
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceOptionalPropertiesBuilder.EnableRetries(int count, TimeSpan? baseDelay)
{
_retryCount = count;
_retryBaseDelay = baseDelay;
return this;
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceOptionalPropertiesBuilder.SetWebhooksJwksCachingDuration(TimeSpan timeToLive)
{
_webhooksJwksCachingDuration = timeToLive;
return this;
}
IIbanityServiceOptionalPropertiesBuilder IIbanityServiceOptionalPropertiesBuilder.SetWebhooksAllowedClockSkew(TimeSpan allowedClockSkew)
{
_webhooksAllowedClockSkew = allowedClockSkew;
return this;
}
IIbanityService IIbanityServiceOptionalPropertiesBuilder.Build()
{
var handler = new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
Proxy = _proxy,
UseProxy = _proxy != null
};
if (_clientCertificate != null)
handler.ClientCertificates.Add(_clientCertificate);
if (_customizeHandler != null)
_customizeHandler(handler);
var httpClient = new HttpClient(handler) { BaseAddress = _endpoint };
if (_timeout.HasValue)
httpClient.Timeout = _timeout.Value;
if (_customizeClient != null)
_customizeClient(httpClient);
var serializer = new JsonSerializer();
var clock = new Clock();
IHttpSignatureService signatureService;
if (_signatureCertificate == null)
{
signatureService = NullHttpSignatureService.Instance;
}
else
{
var builder = new HttpSignatureServiceBuilder(clock).
SetEndpoint(_endpoint).
AddCertificate(_signatureCertificateId, _signatureCertificate);
if (_loggerFactory != null)
builder = builder.AddLogging(_loggerFactory);
signatureService = builder.Build();
}
var loggerFactory = _loggerFactory == null
? (ILoggerFactory)new SimpleLoggerFactory(NullLogger.Instance)
: new LoggerFactoryNotNullDecorator(_loggerFactory);
var v2ApiClient = BuildApiClient(httpClient, serializer, signatureService, loggerFactory, "2");
var versionLessApiClient = BuildApiClient(httpClient, serializer, signatureService, loggerFactory, null);
var pontoConnectClient = new PontoConnectClient(
v2ApiClient,
_pontoConnectClientId == null
? UnconfiguredTokenProvider.InstanceWithCodeVerifier
: new OAuth2TokenProvider(
loggerFactory,
httpClient,
clock,
serializer,
PontoConnectClient.UrlPrefix,
_pontoConnectClientId,
_pontoConnectClientSecret),
_pontoConnectClientId == null
? UnconfiguredTokenProvider.ClientAccessInstance
: new OAuth2ClientAccessTokenProvider(
loggerFactory,
httpClient,
clock,
serializer,
PontoConnectClient.UrlPrefix,
_pontoConnectClientId,
_pontoConnectClientSecret),
UnconfiguredTokenProvider.CustomerAccessInstance);
var isabelConnectClient = new IsabelConnectClient(
v2ApiClient,
_isabelConnectClientId == null
? UnconfiguredTokenProvider.InstanceWithoutCodeVerifier
: new OAuth2TokenProvider(
loggerFactory,
httpClient,
clock,
serializer,
IsabelConnectClient.UrlPrefix,
_isabelConnectClientId,
_isabelConnectClientSecret),
_isabelConnectClientId == null
? UnconfiguredTokenProvider.ClientAccessInstance
: new OAuth2ClientAccessTokenProvider(
loggerFactory,
httpClient,
clock,
serializer,
IsabelConnectClient.UrlPrefix,
_isabelConnectClientId,
_isabelConnectClientSecret),
UnconfiguredTokenProvider.CustomerAccessInstance);
var eInvoicingClient = new EInvoicingClient(
versionLessApiClient,
UnconfiguredTokenProvider.InstanceWithoutCodeVerifier,
_eInvoicingClientId == null
? UnconfiguredTokenProvider.ClientAccessInstance
: new OAuth2ClientAccessTokenProvider(
loggerFactory,
httpClient,
clock,
serializer,
EInvoicingClient.UrlPrefix,
_eInvoicingClientId,
_eInvoicingClientSecret),
UnconfiguredTokenProvider.CustomerAccessInstance);
var codaboxConnectClient = new CodaboxConnectClient(
versionLessApiClient,
UnconfiguredTokenProvider.InstanceWithoutCodeVerifier,
_codaboxConnectClientId == null
? UnconfiguredTokenProvider.ClientAccessInstance
: new OAuth2ClientAccessTokenProvider(
loggerFactory,
httpClient,
clock,
serializer,
CodaboxConnectClient.UrlPrefix,
_codaboxConnectClientId,
_codaboxConnectClientSecret),
UnconfiguredTokenProvider.CustomerAccessInstance);
var xs2aClient = new XS2AClient(
versionLessApiClient,
UnconfiguredTokenProvider.InstanceWithoutCodeVerifier,
UnconfiguredTokenProvider.ClientAccessInstance,
new CustomerAccessTokenProvider(
versionLessApiClient,
XS2AClient.UrlPrefix));
IJwksService jwksService = new JwksService(versionLessApiClient);
var webhooksJwksCachingDuration = _webhooksJwksCachingDuration ?? TimeSpan.FromSeconds(30d);
if (webhooksJwksCachingDuration != TimeSpan.Zero)
jwksService = new JwksServiceCachingDecorator(
jwksService,
clock,
webhooksJwksCachingDuration);
var webhooksService = new WebhooksService(
serializer,
jwksService,
new Rs512Verifier(
new Parser(serializer),
jwksService,
clock,
_webhooksAllowedClockSkew ?? TimeSpan.FromSeconds(30d)));
return new IbanityService(httpClient, pontoConnectClient, isabelConnectClient, eInvoicingClient, codaboxConnectClient, xs2aClient, webhooksService);
}
private IApiClient BuildApiClient(HttpClient httpClient, JsonSerializer serializer, IHttpSignatureService signatureService, ILoggerFactory loggerFactory, string version)
{
var apiClient = new ApiClient(
loggerFactory,
httpClient,
serializer,
signatureService,
version,
_customizeRequest ?? (_ => { }));
if (!_retryCount.HasValue)
return apiClient;
return new ApiClientRetryDecorator(
loggerFactory,
apiClient,
_retryCount.Value,
_retryBaseDelay ?? TimeSpan.FromSeconds(1d));
}
}
/// <summary>
/// Mandatory endpoint builder.
/// </summary>
public interface IIbanityServiceEndpointBuilder
{
/// <summary>
/// Define Ibanity API base URI.
/// </summary>
/// <param name="endpoint">Ibanity API base URI</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceMutualTlsBuilder SetEndpoint(Uri endpoint);
/// <summary>
/// Define Ibanity API base URI.
/// </summary>
/// <param name="endpoint">Ibanity API base URI</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceMutualTlsBuilder SetEndpoint(string endpoint);
}
/// <summary>
/// Mandatory mutual TLS builder.
/// </summary>
public interface IIbanityServiceMutualTlsBuilder
{
/// <summary>
/// Disable client certificate.
/// </summary>
/// <returns>The builder to be used to pursue configuration</returns>
/// <remarks>You will have to manage client certificate within your proxy server.</remarks>
IIbanityServiceProxyBuilder DisableMutualTls();
/// <summary>
/// Define client certificate you generated for your application in our Developer Portal.
/// </summary>
/// <param name="certificate">Client certificate</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceOptionalPropertiesBuilder AddClientCertificate(X509Certificate2 certificate);
/// <summary>
/// Define client certificate you generated for your application in our Developer Portal.
/// </summary>
/// <param name="path">Client certificate (PFX file) path</param>
/// <param name="password">Client certificate passphrase</param>
/// <returns>The builder to be used to pursue configuration</returns>
/// <remarks>The file is probably named <c>certificate.pfx</c>. Do not use <c>signature_certificate.pfx</c> here.</remarks>
IIbanityServiceOptionalPropertiesBuilder AddClientCertificate(string path, string password);
}
/// <summary>
/// Mandatory proxy builder.
/// </summary>
public interface IIbanityServiceProxyBuilder
{
/// <summary>
/// Configure proxy server.
/// </summary>
/// <param name="proxy">Proxy instance in which you can configure address, credentials, ...</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceOptionalPropertiesBuilder AddProxy(IWebProxy proxy);
/// <summary>
/// Configure proxy server.
/// </summary>
/// <param name="endpoint">Proxy server address</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceOptionalPropertiesBuilder AddProxy(Uri endpoint);
/// <summary>
/// Configure proxy server.
/// </summary>
/// <param name="endpoint">Proxy server address</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceOptionalPropertiesBuilder AddProxy(string endpoint);
}
/// <summary>
/// Optional configuration builder.
/// </summary>
public interface IIbanityServiceOptionalPropertiesBuilder : IIbanityServiceProxyBuilder
{
/// <summary>
/// Define signature certificate.
/// </summary>
/// <param name="id">Certificat ID from the Developer Portal</param>
/// <param name="certificate">Signature certificate</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceOptionalPropertiesBuilder AddSignatureCertificate(string id, X509Certificate2 certificate);
/// <summary>
/// Define signature certificate.
/// </summary>
/// <param name="id">Certificat ID from the Developer Portal</param>
/// <param name="path">Signature certificate (PFX file) path</param>
/// <param name="password">Signature certificate passphrase</param>
/// <returns>The builder to be used to pursue configuration</returns>
/// <remarks>The file is probably named <c>signature_certificate.pfx</c>. Do not use <c>certificate.pfx</c> here.</remarks>
IIbanityServiceOptionalPropertiesBuilder AddSignatureCertificate(string id, string path, string password);
/// <summary>
/// Define Ponto Connect OAuth2 credentials.
/// </summary>
/// <param name="clientId">Valid OAuth2 client identifier for your application</param>
/// <param name="clientSecret">OAuth2 client secret</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceOptionalPropertiesBuilder AddPontoConnectOAuth2Authentication(string clientId, string clientSecret);
/// <summary>
/// Define Isabel Connect OAuth2 credentials.
/// </summary>
/// <param name="clientId">Valid OAuth2 client identifier for your application</param>
/// <param name="clientSecret">OAuth2 client secret</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceOptionalPropertiesBuilder AddIsabelConnectOAuth2Authentication(string clientId, string clientSecret);
/// <summary>
/// Define eInvoicing OAuth2 credentials.
/// </summary>
/// <param name="clientId">Valid OAuth2 client identifier for your application</param>
/// <param name="clientSecret">OAuth2 client secret</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceOptionalPropertiesBuilder AddEInvoicingOAuth2Authentication(string clientId, string clientSecret);
/// <summary>
/// Define Codabox Connect OAuth2 credentials.
/// </summary>
/// <param name="clientId">Valid OAuth2 client identifier for your application</param>
/// <param name="clientSecret">OAuth2 client secret</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceOptionalPropertiesBuilder AddCodaboxConnectOAuth2Authentication(string clientId, string clientSecret);
/// <summary>
/// Configure logger.
/// </summary>
/// <param name="logger">Logger instance that will be used across the whole library</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceOptionalPropertiesBuilder AddLogging(ILogger logger);
/// <summary>
/// Configure logger factory.
/// </summary>
/// <param name="loggerFactory">Logger factory will be called in all library-created instances to get named loggers</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceOptionalPropertiesBuilder AddLogging(ILoggerFactory loggerFactory);
/// <summary>
/// Configure HTTP client timeout.
/// </summary>
/// <param name="timeout">Delay before giving up a request</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceOptionalPropertiesBuilder SetTimeout(TimeSpan timeout);
/// <summary>
/// Low-level HTTP client customizations.
/// </summary>
/// <param name="customizeClient">Callback in which <see cref="HttpClient" /> can be customized</param>
/// <param name="customizeHandler">Callback in which <see cref="HttpClientHandler" /> can be customized</param>
/// <param name="customizeRequest">Callback in which <see cref="HttpRequestMessage" /> can be customized</param>
/// <returns>The builder to be used to pursue configuration</returns>
IIbanityServiceOptionalPropertiesBuilder CustomizeHttpClient(Action<HttpClient> customizeClient = null, Action<HttpClientHandler> customizeHandler = null, Action<HttpRequestMessage> customizeRequest = null);
/// <summary>
/// Allow to retry failed requests.
/// </summary>
/// <param name="count">Number of retries after failed operations</param>
/// <param name="baseDelay">Delay before a retry with exponential backoff</param>
/// <returns>The builder to be used to pursue configuration</returns>
/// <remarks>Delay is increased by a 2-factor after each failure: 1 second, then 2 seconds, then 4 seconds, ...</remarks>
IIbanityServiceOptionalPropertiesBuilder EnableRetries(int count = 5, TimeSpan? baseDelay = null);
/// <summary>
/// Define webhooks JWKS caching duration.
/// </summary>
/// <param name="timeToLive">Delay before a key is reloaded from server</param>
/// <returns>The builder to be used to pursue configuration</returns>
/// <remarks>Default is 30 seconds.</remarks>
IIbanityServiceOptionalPropertiesBuilder SetWebhooksJwksCachingDuration(TimeSpan timeToLive);
/// <summary>
/// Set the amount of clock skew to allow for when validate the expiration time and issued at time claims.
/// </summary>
/// <param name="allowedClockSkew">Leniency in date comparisons</param>
/// <returns>The builder to be used to pursue configuration</returns>
/// <remarks>Default is 30 seconds.</remarks>
IIbanityServiceOptionalPropertiesBuilder SetWebhooksAllowedClockSkew(TimeSpan allowedClockSkew);
/// <summary>
/// Create the signature service instance.
/// </summary>
/// <returns>A ready-to-use service</returns>
IIbanityService Build();
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Crypto\RsaSsaPssSignature.cs | using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace Ibanity.Apis.Client.Crypto
{
/// <inheritdoc />
public class RsaSsaPssSignature : ISignature
{
private static readonly Encoding Encoding = Encoding.UTF8;
private readonly X509Certificate2 _certificate;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="certificate">The certificate that will be used to sign data</param>
public RsaSsaPssSignature(X509Certificate2 certificate) =>
_certificate = certificate ?? throw new ArgumentNullException(nameof(certificate));
/// <inheritdoc />
public string Sign(string value)
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException($"'{nameof(value)}' cannot be null or whitespace.", nameof(value));
var bytes = Encoding.GetBytes(value);
byte[] signature;
using (var privateKey = _certificate.GetRSAPrivateKey())
signature = privateKey.SignData(bytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);
return Convert.ToBase64String(signature);
}
}
/// <summary>
/// Compute signatures from string values.
/// </summary>
public interface ISignature
{
/// <summary>
/// Compute a signature from a string.
/// </summary>
/// <param name="value">Value to sign</param>
/// <returns>The signature as base64 string</returns>
string Sign(string value);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Crypto\Sha512Digest.cs | using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Ibanity.Apis.Client.Crypto
{
/// <inheritdoc />
public class Sha512Digest : IDigest
{
private const string Prefix = "SHA-512=";
private static readonly Encoding Encoding = Encoding.UTF8;
/// <inheritdoc />
public string Compute(Stream value)
{
byte[] digest;
using (var algorithm = new SHA512Managed())
digest = value == null
? algorithm.ComputeHash(Encoding.GetBytes(string.Empty))
: algorithm.ComputeHash(value);
return Prefix + Convert.ToBase64String(digest);
}
}
/// <summary>
/// Compute digests from string values.
/// </summary>
public interface IDigest
{
/// <summary>
/// Compute a digest from a string.
/// </summary>
/// <param name="value">Value to hash</param>
/// <returns>The digest as base64 string</returns>
string Compute(Stream value);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\ApiClient.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Utils;
using Ibanity.Apis.Client.Utils.Logging;
namespace Ibanity.Apis.Client.Http
{
/// <inheritdoc />
public class ApiClient : IApiClient
{
private const string RequestIdHeader = "ibanity-request-id";
private static readonly Encoding Encoding = Encoding.UTF8;
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
private readonly ISerializer<string> _serializer;
private readonly IHttpSignatureService _signatureService;
private readonly string _apiVersion;
private readonly Action<HttpRequestMessage> _customizeRequest;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="loggerFactory">Allow to build the logger used within this instance</param>
/// <param name="httpClient">Low-level HTTP client</param>
/// <param name="serializer">To-string serializer</param>
/// <param name="signatureService">HTTP request signature service</param>
/// <param name="apiVersion">Used in accept header</param>
/// <param name="customizeRequest">Allow to modify requests before sending them</param>
public ApiClient(ILoggerFactory loggerFactory, HttpClient httpClient, ISerializer<string> serializer, IHttpSignatureService signatureService, string apiVersion, Action<HttpRequestMessage> customizeRequest)
{
if (loggerFactory is null)
throw new ArgumentNullException(nameof(loggerFactory));
_logger = loggerFactory.CreateLogger<ApiClient>();
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
_serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
_signatureService = signatureService ?? throw new ArgumentNullException(nameof(signatureService));
_apiVersion = apiVersion;
_customizeRequest = customizeRequest ?? throw new ArgumentNullException(nameof(customizeRequest));
}
/// <inheritdoc />
public Task<T> Get<T>(string path, string bearerToken, CancellationToken cancellationToken) =>
SendWithoutPayload<T>(HttpMethod.Get, path, bearerToken, cancellationToken);
private async Task<T> SendWithoutPayload<T>(HttpMethod method, string path, string bearerToken, CancellationToken cancellationToken)
{
if (path is null)
throw new ArgumentNullException(nameof(path));
var headers = GetCommonHeaders(method, bearerToken, path, null, null);
_logger.Trace($"Sending request: {method.ToString().ToUpper(CultureInfo.InvariantCulture)} {path}");
using (var request = new HttpRequestMessage(method, path))
{
foreach (var header in headers)
request.Headers.Add(header.Key, header.Value);
_customizeRequest(request);
var response = await (await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false)).ThrowOnFailure(_serializer, _logger).ConfigureAwait(false);
var requestId = response.Headers.TryGetValues(RequestIdHeader, out var values) ? values.SingleOrDefault() : null;
_logger.Debug($"Response received ({response.StatusCode:D} {response.StatusCode:G}): {method.ToString().ToUpper(CultureInfo.InvariantCulture)} {path} (request ID: {requestId})");
var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return _serializer.Deserialize<T>(body);
}
}
/// <inheritdoc />
public Task<T> Delete<T>(string path, string bearerToken, CancellationToken cancellationToken) =>
SendWithoutPayload<T>(HttpMethod.Delete, path, bearerToken, cancellationToken);
/// <inheritdoc />
public Task Delete(string path, string bearerToken, CancellationToken cancellationToken) =>
Delete<object>(path, bearerToken, cancellationToken);
/// <inheritdoc />
public Task<TResponse> Post<TRequest, TResponse>(string path, string bearerToken, TRequest payload, Guid? idempotencyKey, CancellationToken cancellationToken) =>
SendWithPayload<TRequest, TResponse>(HttpMethod.Post, path, bearerToken, payload, idempotencyKey, cancellationToken);
/// <inheritdoc />
public Task<TResponse> Patch<TRequest, TResponse>(string path, string bearerToken, TRequest payload, Guid? idempotencyKey, CancellationToken cancellationToken) =>
SendWithPayload<TRequest, TResponse>(new HttpMethod("PATCH"), path, bearerToken, payload, idempotencyKey, cancellationToken);
private async Task<TResponse> SendWithPayload<TRequest, TResponse>(HttpMethod method, string path, string bearerToken, TRequest payload, Guid? idempotencyKey, CancellationToken cancellationToken)
{
if (path is null)
throw new ArgumentNullException(nameof(path));
var content = _serializer.Serialize(payload);
Dictionary<string, string> headers;
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream, Encoding))
{
writer.Write(payload);
await writer.FlushAsync().ConfigureAwait(false);
stream.Seek(0L, SeekOrigin.Begin);
headers = GetCommonHeaders(method, bearerToken, path, idempotencyKey, stream);
}
_logger.Trace($"Sending request: {method.ToString().ToUpper(CultureInfo.InvariantCulture)} {path}");
using (var request = new HttpRequestMessage(method, path))
{
foreach (var header in headers)
request.Headers.Add(header.Key, header.Value);
request.Content = new StringContent(content, Encoding, "application/vnd.api+json");
_customizeRequest(request);
var response = await (await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false)).ThrowOnFailure(_serializer, _logger).ConfigureAwait(false);
var requestId = response.Headers.TryGetValues(RequestIdHeader, out var values) ? values.SingleOrDefault() : null;
_logger.Debug($"Response received ({response.StatusCode:D} {response.StatusCode:G}): {method.ToString().ToUpper(CultureInfo.InvariantCulture)} {path} (request ID: {requestId})");
var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return _serializer.Deserialize<TResponse>(body);
}
}
private Dictionary<string, string> GetCommonHeaders(HttpMethod method, string bearerToken, string path, Guid? idempotencyKey, Stream payload)
{
var headers = new Dictionary<string, string>
{
{
"Accept",
"application/vnd.api+json" + (string.IsNullOrWhiteSpace(_apiVersion) ? string.Empty : $";version={_apiVersion}")
}
};
if (!string.IsNullOrWhiteSpace(bearerToken))
headers["Authorization"] = $"Bearer {bearerToken}";
if (idempotencyKey.HasValue)
headers["Ibanity-Idempotency-Key"] = idempotencyKey.Value.ToString();
var signatureHeaders = _signatureService.GetHttpSignatureHeaders(
method.Method.ToUpper(CultureInfo.InvariantCulture),
new Uri(_httpClient.BaseAddress + path),
headers,
payload);
foreach (var header in signatureHeaders)
headers.Add(header.Key, header.Value);
return headers;
}
/// <inheritdoc />
public async Task<TResponse> PostInline<TResponse>(string path, string bearerToken, IDictionary<string, string> additionalHeaders, string filename, Stream payload, string contentType, CancellationToken cancellationToken)
{
if (path is null)
throw new ArgumentNullException(nameof(path));
if (filename is null)
throw new ArgumentNullException(nameof(filename));
if (string.IsNullOrWhiteSpace(filename))
throw new ArgumentException("File name is empty", nameof(filename));
var headers = GetCommonHeaders(HttpMethod.Post, bearerToken, path, null, payload);
payload.Seek(0L, SeekOrigin.Begin);
_logger.Trace($"Sending request: {HttpMethod.Post.ToString().ToUpper(CultureInfo.InvariantCulture)} {path}");
using (var request = new HttpRequestMessage(HttpMethod.Post, path))
{
foreach (var header in headers)
request.Headers.Add(header.Key, header.Value);
foreach (var header in additionalHeaders)
request.Headers.Add(header.Key, header.Value);
request.Content = new StreamContent(payload);
request.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue(contentType);
request.Content.Headers.Add("Content-Disposition", $@"inline; filename=""{EscapeFilename(filename)}""");
_customizeRequest(request);
var response = await (await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false)).ThrowOnFailure(_serializer, _logger).ConfigureAwait(false);
var requestId = response.Headers.TryGetValues(RequestIdHeader, out var values) ? values.SingleOrDefault() : null;
_logger.Debug($"Response received ({response.StatusCode:D} {response.StatusCode:G}): {HttpMethod.Post.ToString().ToUpper(CultureInfo.InvariantCulture)} {path} (request ID: {requestId})");
var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return _serializer.Deserialize<TResponse>(body);
}
}
private static string EscapeFilename(string filename) =>
filename.Replace(@"\", @"\\").Replace(@"""", @"\""");
/// <inheritdoc />
public async Task GetToStream(string path, string bearerToken, string acceptHeader, Stream target, CancellationToken cancellationToken)
{
if (path is null)
throw new ArgumentNullException(nameof(path));
if (target is null)
throw new ArgumentNullException(nameof(target));
var headers = GetCommonHeaders(HttpMethod.Get, bearerToken, path, null, null);
using (var request = new HttpRequestMessage(HttpMethod.Get, path))
{
if (!string.IsNullOrWhiteSpace(acceptHeader))
request.Headers.Add("Accept", acceptHeader);
foreach (var header in headers)
if (header.Key != "Accept")
request.Headers.Add(header.Key, header.Value);
_customizeRequest(request);
using (var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false))
using (var streamToReadFrom = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
await streamToReadFrom.CopyToAsync(target, 81920, cancellationToken).ConfigureAwait(false);
}
}
}
/// <summary>
/// Low-level HTTP client
/// </summary>
public interface IApiClient
{
/// <summary>
/// Send a GET request.
/// </summary>
/// <typeparam name="T">Type of the received payload</typeparam>
/// <param name="path">Query string, absolute, or relative to product root</param>
/// <param name="bearerToken">Token added to Authorization header</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The specified resource</returns>
Task<T> Get<T>(string path, string bearerToken, CancellationToken cancellationToken);
/// <summary>
/// Send a GET request and save the result to a provided stream.
/// </summary>
/// <param name="path">Query string, absolute, or relative to product root</param>
/// <param name="bearerToken">Token added to Authorization header</param>
/// <param name="acceptHeader">Format of the response you expect from the call</param>
/// <param name="target">Destination stream where the payload will be written to</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The specified resource</returns>
Task GetToStream(string path, string bearerToken, string acceptHeader, Stream target, CancellationToken cancellationToken);
/// <summary>
/// Send a DELETE request with a returned payload.
/// </summary>
/// <typeparam name="T">Type of the received payload</typeparam>
/// <param name="path">Query string, absolute, or relative to product root</param>
/// <param name="bearerToken">Token added to Authorization header</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The deleted resource</returns>
Task<T> Delete<T>(string path, string bearerToken, CancellationToken cancellationToken);
/// <summary>
/// Send a DELETE request without a returned payload.
/// </summary>
/// <param name="path">Query string, absolute, or relative to product root</param>
/// <param name="bearerToken">Token added to Authorization header</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
Task Delete(string path, string bearerToken, CancellationToken cancellationToken);
/// <summary>
/// Send a POST request.
/// </summary>
/// <typeparam name="TRequest">Type of the payload to be sent</typeparam>
/// <typeparam name="TResponse">Type of the received payload</typeparam>
/// <param name="path">Query string, absolute, or relative to product root</param>
/// <param name="bearerToken">Token added to Authorization header</param>
/// <param name="payload">Data to be sent</param>
/// <param name="idempotencyKey">Several requests with the same idempotency key will be executed only once</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The created resource</returns>
Task<TResponse> Post<TRequest, TResponse>(string path, string bearerToken, TRequest payload, Guid? idempotencyKey, CancellationToken cancellationToken);
/// <summary>
/// Send an inline payload with a POST request.
/// </summary>
/// <typeparam name="TResponse">Type of the received payload</typeparam>
/// <param name="path">Query string, absolute, or relative to product root</param>
/// <param name="bearerToken">Token added to Authorization header</param>
/// <param name="additionalHeaders">Additional headers</param>
/// <param name="filename">Content disposition filename</param>
/// <param name="payload">Data to be sent</param>
/// <param name="contentType">Payload MIME type</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The created resource</returns>
Task<TResponse> PostInline<TResponse>(string path, string bearerToken, IDictionary<string, string> additionalHeaders, string filename, Stream payload, string contentType, CancellationToken cancellationToken);
/// <summary>
/// Send a PATCH request.
/// </summary>
/// <typeparam name="TRequest">Type of the payload to be sent</typeparam>
/// <typeparam name="TResponse">Type of the received payload</typeparam>
/// <param name="path">Query string, absolute, or relative to product root</param>
/// <param name="bearerToken">Token added to Authorization header</param>
/// <param name="payload">Data to be sent</param>
/// <param name="idempotencyKey">Several requests with the same idempotency key will be executed only once</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The updated resource</returns>
Task<TResponse> Patch<TRequest, TResponse>(string path, string bearerToken, TRequest payload, Guid? idempotencyKey, CancellationToken cancellationToken);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\ApiClientRetryDecorator.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Utils.Logging;
namespace Ibanity.Apis.Client.Http
{
/// <summary>
/// Wrapper around the actual client, allowing to retry failed requests.
/// </summary>
public class ApiClientRetryDecorator : IApiClient
{
private readonly ILogger _logger;
private readonly IApiClient _underlyingInstance;
private readonly int _count;
private readonly TimeSpan _baseDelay;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="loggerFactory">Allow to build the logger used within this instance</param>
/// <param name="underlyingInstance">Actual client</param>
/// <param name="count">Number of retries after failed operations</param>
/// <param name="baseDelay">Delay before a retry with exponential backoff</param>
/// <remarks>Delay is increased by a 2-factor after each failure: 1 second, then 2 seconds, then 4 seconds, ...</remarks>
public ApiClientRetryDecorator(ILoggerFactory loggerFactory, IApiClient underlyingInstance, int count, TimeSpan baseDelay)
{
if (loggerFactory is null)
throw new ArgumentNullException(nameof(loggerFactory));
_logger = loggerFactory.CreateLogger<ApiClientRetryDecorator>();
_underlyingInstance = underlyingInstance ?? throw new ArgumentNullException(nameof(underlyingInstance));
_count = count;
_baseDelay = baseDelay;
}
private async Task<T> Execute<T>(string operation, Func<Task<T>> action, CancellationToken cancellationToken)
{
for (var i = 0; ; i++)
try
{
return await action().ConfigureAwait(false);
}
catch (IbanityClientException)
{
throw; // no need to retry a faulty request
}
catch (Exception e) when (i < _count)
{
var delay = TimeSpan.FromSeconds(Math.Pow(_baseDelay.TotalSeconds, i + 1));
_logger.Warn($"{operation} failed (try {i + 1} of {_count}), retrying in {delay.TotalSeconds:F2} seconds", e);
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
}
/// <inheritdoc />
public Task<T> Delete<T>(string path, string bearerToken, CancellationToken cancellationToken) =>
Execute("Delete", async () => await _underlyingInstance.Delete<T>(path, bearerToken, cancellationToken).ConfigureAwait(false), cancellationToken);
/// <inheritdoc />
public Task Delete(string path, string bearerToken, CancellationToken cancellationToken) =>
Delete<object>(path, bearerToken, cancellationToken);
/// <inheritdoc />
public Task<T> Get<T>(string path, string bearerToken, CancellationToken cancellationToken) =>
Execute("Get", async () => await _underlyingInstance.Get<T>(path, bearerToken, cancellationToken).ConfigureAwait(false), cancellationToken);
/// <inheritdoc />
public Task<TResponse> Patch<TRequest, TResponse>(string path, string bearerToken, TRequest payload, Guid? idempotencyKey, CancellationToken cancellationToken) =>
Execute("Patch", async () => await _underlyingInstance.Patch<TRequest, TResponse>(path, bearerToken, payload, idempotencyKey, cancellationToken).ConfigureAwait(false), cancellationToken);
/// <inheritdoc />
public Task<TResponse> Post<TRequest, TResponse>(string path, string bearerToken, TRequest payload, Guid? idempotencyKey, CancellationToken cancellationToken) =>
Execute("Post", async () => await _underlyingInstance.Post<TRequest, TResponse>(path, bearerToken, payload, idempotencyKey, cancellationToken).ConfigureAwait(false), cancellationToken);
/// <inheritdoc />
public Task<TResponse> PostInline<TResponse>(string path, string bearerToken, IDictionary<string, string> additionalHeaders, string filename, Stream payload, string contentType, CancellationToken cancellationToken) =>
Execute("Post", async () => await _underlyingInstance.PostInline<TResponse>(path, bearerToken, additionalHeaders, filename, payload, contentType, cancellationToken).ConfigureAwait(false), cancellationToken);
/// <inheritdoc />
public Task GetToStream(string path, string bearerToken, string acceptHeader, Stream target, CancellationToken cancellationToken) =>
Execute<object>("Get", async () => { await _underlyingInstance.GetToStream(path, bearerToken, acceptHeader, target, cancellationToken).ConfigureAwait(false); return null; }, cancellationToken);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\BaseToken.cs | namespace Ibanity.Apis.Client.Http
{
/// <summary>
/// Base access token, only containing access token value.
/// </summary>
public class BaseToken
{
/// <summary>
/// Bearer token.
/// </summary>
public string AccessToken { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\BasicAuthenticationHeaderValue.cs | using System;
using System.Net.Http.Headers;
using System.Text;
namespace Ibanity.Apis.Client.Http
{
/// <summary>
/// Authentication header with user and password as base64 string.
/// </summary>
public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue
{
private static readonly Encoding Encoding = Encoding.ASCII;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="username">Username to encode</param>
/// <param name="password">Password to encode</param>
public BasicAuthenticationHeaderValue(string username, string password)
: base("Basic", Convert.ToBase64String(Encoding.GetBytes($"{username}:{password}")))
{
if (string.IsNullOrWhiteSpace(username))
throw new ArgumentException($"'{nameof(username)}' cannot be null or whitespace.", nameof(username));
if (string.IsNullOrWhiteSpace(password))
throw new ArgumentException($"'{nameof(password)}' cannot be null or whitespace.", nameof(password));
}
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\ClientAccessToken.cs | using System;
namespace Ibanity.Apis.Client.Http
{
/// <summary>
/// Client access token, generated from a client ID and client secret.
/// </summary>
public class ClientAccessToken : BaseToken
{
/// <summary>
/// Build a new instance.
/// </summary>
public ClientAccessToken() { }
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="accessToken">Bearer token</param>
/// <param name="validUntil">Validity limit</param>
public ClientAccessToken(string accessToken, DateTimeOffset validUntil)
{
AccessToken = accessToken;
ValidUntil = validUntil;
}
/// <summary>
/// Validity limit.
/// </summary>
public DateTimeOffset ValidUntil { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\CustomerAccessToken.cs | using System;
namespace Ibanity.Apis.Client.Http
{
/// <summary>
/// Customer access token, generated from a client ID and client secret.
/// </summary>
public class CustomerAccessToken : BaseToken
{
/// <summary>
/// Unique identifier for the customer access token.
/// </summary>
public Guid Id { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\CustomerAccessTokenModels.cs | using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.Http
{
/// <summary>
/// <p>This is an object representing a customer access token. A customer access token has to be created for each of your customers and is required to call customer-specific endpoints like accounts or transactions.</p>
/// <p>If you replace an active customer access token by creating a new one with the same application customer reference, it will be linked to the existing customer and the previous token will be revoked.</p>
/// </summary>
public class CustomerAccessTokenRequest
{
/// <summary>
/// Your unique identifier for this customer
/// </summary>
[DataMember(Name = "applicationCustomerReference", EmitDefaultValue = false)]
public string ApplicationCustomerReference { get; set; }
}
/// <summary>
/// The created customer access token resource.
/// </summary>
public class CustomerAccessTokenResponse
{
/// <summary>
/// Token corresponding to the customer. To be used when accessing customer-specific endpoints like account and transaction
/// </summary>
[DataMember(Name = "token", EmitDefaultValue = false)]
public string Token { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\CustomerAccessTokenProvider.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Utils.Logging;
namespace Ibanity.Apis.Client.Http
{
/// <inheritdoc />
public class CustomerAccessTokenProvider : ICustomerAccessTokenProvider
{
private readonly IApiClient _apiClient;
private readonly string _urlPrefix;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="urlPrefix">Product endpoint</param>
public CustomerAccessTokenProvider(IApiClient apiClient, string urlPrefix)
{
if (string.IsNullOrWhiteSpace(urlPrefix))
throw new ArgumentException($"'{nameof(urlPrefix)}' cannot be null or whitespace.", nameof(urlPrefix));
_apiClient = apiClient ?? throw new ArgumentNullException(nameof(apiClient));
_urlPrefix = urlPrefix;
}
/// <inheritdoc />
public async Task<CustomerAccessToken> GetToken(string applicationCustomerReference, Guid? idempotencyKey = null, CancellationToken? cancellationToken = null)
{
var response = await _apiClient.Post<JsonApi.Resource<CustomerAccessTokenRequest, object, object, object>, JsonApi.Resource<CustomerAccessTokenResponse, object, object, object>>(
_urlPrefix + "/customer-access-tokens",
null,
new JsonApi.Resource<CustomerAccessTokenRequest, object, object, object>
{
Data = new JsonApi.Data<CustomerAccessTokenRequest, object, object, object>
{
Type = "customerAccessToken",
Attributes = new CustomerAccessTokenRequest
{
ApplicationCustomerReference = applicationCustomerReference
}
}
},
idempotencyKey ?? Guid.NewGuid(),
cancellationToken ?? CancellationToken.None).ConfigureAwait(false);
return new CustomerAccessToken
{
AccessToken = response.Data.Attributes.Token,
Id = Guid.Parse(response.Data.Id)
};
}
/// <inheritdoc />
/// <remarks>Does nothing.</remarks>
public Task<CustomerAccessToken> RefreshToken(CustomerAccessToken token, CancellationToken? cancellationToken = null) =>
Task.FromResult(token);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\HttpResponseMessageExtensions.cs | using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Utils;
using Ibanity.Apis.Client.Utils.Logging;
namespace Ibanity.Apis.Client.Http
{
/// <summary>
/// Add a few methods to <see cref="HttpResponseMessage" />.
/// </summary>
public static class HttpResponseMessageExtensions
{
private const string RequestIdHeader = "ibanity-request-id";
/// <summary>
/// <para>Checks status code and throws an exception if an error occurred.</para>
/// <para>The error payload will be contained inside the exception.</para>
/// </summary>
/// <param name="this"><see cref="HttpResponseMessage" /> instance</param>
/// <param name="serializer">To-string serializer</param>
/// <param name="logger">Logger used to log error</param>
/// <returns>The instance received in argument</returns>
public static async Task<HttpResponseMessage> ThrowOnFailure(this HttpResponseMessage @this, ISerializer<string> serializer, ILogger logger)
{
if (@this is null)
throw new ArgumentNullException(nameof(@this));
if (serializer is null)
throw new ArgumentNullException(nameof(serializer));
if (@this.IsSuccessStatusCode)
return @this;
string body;
using (var content = @this.Content)
body = content == null
? null
: await content.ReadAsStringAsync().ConfigureAwait(false);
var requestId = @this.Headers.TryGetValues(RequestIdHeader, out var values) ? values.SingleOrDefault() : null;
var statusCode = @this.StatusCode;
JsonApi.Error errors;
try
{
errors = string.IsNullOrWhiteSpace(body)
? null
: serializer.Deserialize<JsonApi.Error>(body);
}
catch
{
errors = null;
}
var exception = (int)@this.StatusCode < 500
? (IbanityRequestException)(new IbanityClientException(requestId, statusCode, errors))
: new IbanityServerException(requestId, statusCode, errors);
logger.Error(exception.Message, exception);
throw exception;
}
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\HttpSignatureService.cs | using System;
using System.Collections.Generic;
using System.IO;
using Ibanity.Apis.Client.Crypto;
using Ibanity.Apis.Client.Utils;
using Ibanity.Apis.Client.Utils.Logging;
namespace Ibanity.Apis.Client.Http
{
/// <inheritdoc />
public class HttpSignatureService : IHttpSignatureService
{
private const string SignatureHeaderAlgorithm = "hs2019";
private readonly ILogger _logger;
private readonly IDigest _digest;
private readonly ISignature _signature;
private readonly IClock _clock;
private readonly IHttpSignatureString _signatureString;
private readonly string _certificateId;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="loggerFactory">Allow to build the logger used within this instance</param>
/// <param name="digest">Used to compute signature string hash</param>
/// <param name="signature">Signature algorithm</param>
/// <param name="clock">Returns current date and time</param>
/// <param name="signatureString">Used to build signature string from payload</param>
/// <param name="certificateId">Identifier for the application's signature certificate, obtained from the Developer Portal</param>
public HttpSignatureService(ILoggerFactory loggerFactory, IDigest digest, ISignature signature, IClock clock, IHttpSignatureString signatureString, string certificateId)
{
if (loggerFactory is null)
throw new ArgumentNullException(nameof(loggerFactory));
if (string.IsNullOrWhiteSpace(certificateId))
throw new ArgumentException($"'{nameof(certificateId)}' cannot be null or whitespace.", nameof(certificateId));
_logger = loggerFactory.CreateLogger<HttpSignatureService>();
_digest = digest ?? throw new ArgumentNullException(nameof(digest));
_signature = signature ?? throw new ArgumentNullException(nameof(signature));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_signatureString = signatureString ?? throw new ArgumentNullException(nameof(signatureString));
_certificateId = certificateId;
}
/// <inheritdoc />
public IDictionary<string, string> GetHttpSignatureHeaders(string httpMethod, Uri url, IDictionary<string, string> requestHeaders, Stream payload)
{
if (string.IsNullOrWhiteSpace(httpMethod))
throw new ArgumentException($"'{nameof(httpMethod)}' cannot be null or whitespace.", nameof(httpMethod));
if (url is null)
throw new ArgumentNullException(nameof(url));
if (requestHeaders is null)
throw new ArgumentNullException(nameof(requestHeaders));
_logger.Trace("Signing request with certificate " + _certificateId);
var now = _clock.Now;
var digest = _digest.Compute(payload);
var signatureString = _signatureString.Compute(
httpMethod,
url,
requestHeaders,
digest,
now);
var signature = _signature.Sign(signatureString);
var signedHeaders = _signatureString.GetSignedHeaders(requestHeaders);
var signatureHeaderFields = new[]
{
$@"keyId=""{_certificateId}""",
$@"created={now.ToUnixTimeSeconds()}",
$@"algorithm=""{SignatureHeaderAlgorithm}""",
$@"headers=""{string.Join(" ", signedHeaders)}""",
$@"signature=""{signature}"""
};
return new Dictionary<string, string>
{
{ "Digest", digest },
{ "Signature", string.Join(",", signatureHeaderFields) }
};
}
}
/// <summary>
/// Null signature service, used when the signature certificate isn't configured.
/// </summary>
public class NullHttpSignatureService : IHttpSignatureService
{
/// <summary>
/// Singleton instance.
/// </summary>
public static readonly IHttpSignatureService Instance = new NullHttpSignatureService();
private NullHttpSignatureService() { }
/// <inheritdoc />
/// <remarks>Returns an empty dictionary.</remarks>
public IDictionary<string, string> GetHttpSignatureHeaders(string httpMethod, Uri url, IDictionary<string, string> requestHeaders, Stream payload) =>
new Dictionary<string, string>();
}
/// <summary>
/// Allow to compute the signature headers for a given request.
/// </summary>
public interface IHttpSignatureService
{
/// <summary>
/// Compute the signature headers.
/// </summary>
/// <param name="httpMethod">HTTP method (GET, POST, ...)</param>
/// <param name="url">URI where to request is going to be sent</param>
/// <param name="requestHeaders">Existing request headers</param>
/// <param name="payload">Request payload</param>
/// <returns>Headers names and values</returns>
IDictionary<string, string> GetHttpSignatureHeaders(string httpMethod, Uri url, IDictionary<string, string> requestHeaders, Stream payload);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\HttpSignatureString.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
namespace Ibanity.Apis.Client.Http
{
/// <inheritdoc />
public class HttpSignatureString : IHttpSignatureString
{
private static readonly Regex HeaderPattern = new Regex(
"(authorization|ibanity.*?)",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
private readonly Uri _ibanityEndpoint;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="ibanityEndpoint">Base Ibanity endpoint</param>
public HttpSignatureString(Uri ibanityEndpoint) =>
_ibanityEndpoint = ibanityEndpoint;
/// <inheritdoc />
public string Compute(string httpMethod, Uri url, IDictionary<string, string> requestHeaders, string digest, DateTimeOffset timestamp)
{
if (string.IsNullOrWhiteSpace(httpMethod))
throw new ArgumentException($"'{nameof(httpMethod)}' cannot be null or whitespace.", nameof(httpMethod));
if (url is null)
throw new ArgumentNullException(nameof(url));
if (requestHeaders is null)
throw new ArgumentNullException(nameof(requestHeaders));
if (string.IsNullOrWhiteSpace(digest))
throw new ArgumentException($"'{nameof(digest)}' cannot be null or whitespace.", nameof(digest));
return string.Join(
"\n",
new[]
{
$"(request-target): {httpMethod.ToLower(CultureInfo.InvariantCulture)} {url.PathAndQuery}",
"host: " + _ibanityEndpoint.Host,
"digest: " + digest,
"(created): " + timestamp.ToUnixTimeSeconds()
}.Union(requestHeaders.
Where(kvp => HeaderPattern.IsMatch(kvp.Key)).
Select(kvp => $"{kvp.Key.ToLower(CultureInfo.InvariantCulture)}: {kvp.Value}")));
}
/// <inheritdoc />
public IEnumerable<string> GetSignedHeaders(IDictionary<string, string> requestHeaders)
{
yield return "(request-target)";
yield return "host";
yield return "digest";
yield return "(created)";
foreach (var key in requestHeaders.Keys)
if (HeaderPattern.IsMatch(key))
yield return key.ToLower(CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Allow to build, from a request, the string to be signed
/// </summary>
public interface IHttpSignatureString
{
/// <summary>
/// Build, from a request, the string to be signed
/// </summary>
/// <param name="httpMethod"></param>
/// <param name="url"></param>
/// <param name="requestHeaders">Existing request headers</param>
/// <param name="digest">Hash of the payload</param>
/// <param name="timestamp">Now</param>
/// <returns>String to be signed</returns>
string Compute(string httpMethod, Uri url, IDictionary<string, string> requestHeaders, string digest, DateTimeOffset timestamp);
/// <summary>
/// Get the list of headers to be signed.
/// </summary>
/// <param name="requestHeaders">Existing request headers</param>
/// <returns>A list of header names</returns>
IEnumerable<string> GetSignedHeaders(IDictionary<string, string> requestHeaders);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\IbanityRequestException.cs | using System.Linq;
using System.Net;
namespace Ibanity.Apis.Client.Http
{
/// <summary>
/// Exception occurring when a request is sent to Ibanity.
/// </summary>
public abstract class IbanityRequestException : IbanityException
{
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="requestId">Ibanity API Request ID</param>
/// <param name="statusCode">Received HTTP status code</param>
/// <param name="error">Error details</param>
protected IbanityRequestException(string requestId, HttpStatusCode statusCode, JsonApi.Error error) :
base($"Request {requestId} failed ({statusCode:D} {statusCode:G}): " + Format(error))
{
RequestId = requestId;
StatusCode = statusCode;
Error = error;
}
private static string Format(JsonApi.Error error)
{
if (error?.Errors?.Any() ?? false)
return string.Join(" - ", error.Errors.Select(e => $"{e.Code} ({e.Detail})"));
return "Unspecified";
}
/// <summary>
/// Ibanity API Request ID
/// </summary>
/// <remarks>Providing this identifier with your support request will ensure a faster resolution of your issue.</remarks>
public string RequestId { get; }
/// <summary>
/// Received HTTP status code
/// </summary>
public HttpStatusCode StatusCode { get; }
/// <summary>
/// Error details
/// </summary>
public JsonApi.Error Error { get; }
}
/// <inheritdoc />
/// <remarks>Related to a 4xx HTTP error that could be solved client-side</remarks>
public class IbanityClientException : IbanityRequestException
{
/// <inheritdoc />
public IbanityClientException(string requestId, HttpStatusCode statusCode, JsonApi.Error error) :
base(requestId, statusCode, error)
{ }
}
/// <inheritdoc />
/// <remarks>Related to a 5xx HTTP error that occurred server-side</remarks>
public class IbanityServerException : IbanityRequestException
{
/// <inheritdoc />
public IbanityServerException(string requestId, HttpStatusCode statusCode, JsonApi.Error error) :
base(requestId, statusCode, error)
{ }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\ITokenProvider.cs | using System;
using System.Threading;
using System.Threading.Tasks;
namespace Ibanity.Apis.Client.Http
{
/// <summary>
/// Manage access tokens.
/// </summary>
public interface ITokenProvider : IAccessTokenProvider<Token>
{
/// <summary>
/// Create a new access token using a previously received refresh token.
/// </summary>
/// <param name="refreshToken">Refresh token received during in previous authentication</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A new access token</returns>
Task<Token> GetToken(string refreshToken, CancellationToken? cancellationToken = null);
/// <summary>
/// Revoke a token.
/// </summary>
/// <param name="token">Token to be revoked</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
Task RevokeToken(Token token, CancellationToken? cancellationToken = null);
}
/// <inheritdoc />
public interface ITokenProviderWithCodeVerifier : ITokenProvider
{
/// <summary>
/// Create a new access token using code received during user linking process.
/// </summary>
/// <param name="authorizationCode">Authorization code provided during the user linking process</param>
/// <param name="codeVerifier">PKCE code verifier corresponding to the code challenge string used in the authorization request</param>
/// <param name="redirectUri">Redirection URL authorized for your application in the Developer Portal</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A new access token</returns>
Task<Token> GetToken(string authorizationCode, string codeVerifier, Uri redirectUri, CancellationToken? cancellationToken = null);
/// <summary>
/// Create a new access token using code received during user linking process.
/// </summary>
/// <param name="authorizationCode">Authorization code provided during the user linking process</param>
/// <param name="codeVerifier">PKCE code verifier corresponding to the code challenge string used in the authorization request</param>
/// <param name="redirectUri">Redirection URL authorized for your application in the Developer Portal</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A new access token</returns>
Task<Token> GetToken(string authorizationCode, string codeVerifier, string redirectUri, CancellationToken? cancellationToken = null);
}
/// <inheritdoc />
public interface ITokenProviderWithoutCodeVerifier : ITokenProvider
{
/// <summary>
/// Create a new access token using code received during user linking process.
/// </summary>
/// <param name="authorizationCode">Authorization code provided during the user linking process</param>
/// <param name="redirectUri">Redirection URL authorized for your application in the Developer Portal</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A new access token</returns>
Task<Token> GetToken(string authorizationCode, Uri redirectUri, CancellationToken? cancellationToken = null);
/// <summary>
/// Create a new access token using code received during user linking process.
/// </summary>
/// <param name="authorizationCode">Authorization code provided during the user linking process</param>
/// <param name="redirectUri">Redirection URL authorized for your application in the Developer Portal</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A new access token</returns>
Task<Token> GetToken(string authorizationCode, string redirectUri, CancellationToken? cancellationToken = null);
}
/// <summary>
/// Allows clients to refresh (if needed) their access token.
/// </summary>
/// <typeparam name="T">Token type</typeparam>
public interface IAccessTokenProvider<T>
{
/// <summary>
/// Refresh access token if needed
/// </summary>
/// <param name="token">Token to check</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The token given as argument, refreshed if it was near expiration</returns>
Task<T> RefreshToken(T token, CancellationToken? cancellationToken = null);
}
/// <summary>
/// Manage client access tokens.
/// </summary>
public interface IClientAccessTokenProvider : IAccessTokenProvider<ClientAccessToken>
{
/// <summary>
/// Create a new client access token from the client ID and client secret.
/// </summary>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A new client access token</returns>
Task<ClientAccessToken> GetToken(CancellationToken? cancellationToken = null);
}
/// <summary>
/// Manage customer access tokens.
/// </summary>
public interface ICustomerAccessTokenProvider : IAccessTokenProvider<CustomerAccessToken>
{
/// <summary>
/// Create a new customer access token for the application customer reference.
/// </summary>
/// <param name="applicationCustomerReference">Your unique identifier for this customer</param>
/// <param name="idempotencyKey">Several requests with the same idempotency key will be executed only once</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A new customer access token</returns>
Task<CustomerAccessToken> GetToken(string applicationCustomerReference, Guid? idempotencyKey = null, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\Token.cs | using System;
namespace Ibanity.Apis.Client.Http
{
/// <summary>
/// Access token, generated from an authorization code or a refresh token.
/// </summary>
public class Token : BaseToken
{
private string _refreshToken;
/// <summary>
/// Build a new instance.
/// </summary>
public Token() { }
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="accessToken">Bearer token</param>
/// <param name="validUntil">Validity limit</param>
/// <param name="refreshToken">Token used to get a new bearer token</param>
/// <exception cref="ArgumentException"></exception>
public Token(string accessToken, DateTimeOffset validUntil, string refreshToken)
{
AccessToken = accessToken;
ValidUntil = validUntil;
RefreshToken = refreshToken;
}
/// <summary>
/// Validity limit.
/// </summary>
public DateTimeOffset ValidUntil { get; set; }
/// <summary>
/// Token used to get a new bearer token.
/// </summary>
/// <remarks>Don't forget to save this value if you want to reuse the token later.</remarks>
public string RefreshToken
{
get => _refreshToken;
set
{
var previousValue = _refreshToken;
_refreshToken = value;
if (_refreshToken == previousValue)
return;
var handler = RefreshTokenUpdated;
if (handler != null)
handler(this, new RefreshTokenUpdatedEventArgs { PreviousToken = previousValue, NewToken = _refreshToken });
}
}
/// <summary>
/// The refresh token was nearly expired and was replaced by a new one.
/// </summary>
public event EventHandler<RefreshTokenUpdatedEventArgs> RefreshTokenUpdated;
}
/// <summary>
/// Former and current refresh tokens.
/// </summary>
public class RefreshTokenUpdatedEventArgs : EventArgs
{
/// <summary>
/// Former refresh token
/// </summary>
public string PreviousToken { get; set; }
/// <summary>
/// Current refresh token
/// </summary>
public string NewToken { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Http\UnconfiguredTokenProvider.cs | using System;
using System.Threading;
using System.Threading.Tasks;
namespace Ibanity.Apis.Client.Http
{
/// <summary>
/// Token provider only throwing exception.
/// </summary>
/// <remarks>Used when client ID and client secret aren't configured.</remarks>
public class UnconfiguredTokenProvider : ITokenProviderWithCodeVerifier, ITokenProviderWithoutCodeVerifier, IClientAccessTokenProvider, ICustomerAccessTokenProvider
{
/// <summary>
/// Singleton instance
/// </summary>
public static readonly ITokenProviderWithCodeVerifier InstanceWithCodeVerifier;
/// <summary>
/// Singleton instance
/// </summary>
public static readonly ITokenProviderWithoutCodeVerifier InstanceWithoutCodeVerifier;
/// <summary>
/// Singleton instance for client access token
/// </summary>
public static readonly IClientAccessTokenProvider ClientAccessInstance;
/// <summary>
/// Singleton instance for customer access token
/// </summary>
public static readonly ICustomerAccessTokenProvider CustomerAccessInstance;
static UnconfiguredTokenProvider()
{
var instance = new UnconfiguredTokenProvider();
InstanceWithCodeVerifier = instance;
InstanceWithoutCodeVerifier = instance;
ClientAccessInstance = instance;
CustomerAccessInstance = instance;
}
private UnconfiguredTokenProvider() { }
private const string Message = "Missing client ID and client secret";
/// <inheritdoc />
/// <remarks>Does nothing besides throwing an exception.</remarks>
public Task<Token> GetToken(string authorizationCode, string codeVerifier, Uri redirectUri, CancellationToken? cancellationToken = null) =>
throw new IbanityConfigurationException(Message);
/// <inheritdoc />
/// <remarks>Does nothing besides throwing an exception.</remarks>
public Task<Token> GetToken(string authorizationCode, string codeVerifier, string redirectUri, CancellationToken? cancellationToken = null) =>
throw new IbanityConfigurationException(Message);
/// <inheritdoc />
/// <remarks>Does nothing besides throwing an exception.</remarks>
public Task<Token> GetToken(string authorizationCode, Uri redirectUri, CancellationToken? cancellationToken = null) =>
throw new IbanityConfigurationException(Message);
/// <inheritdoc />
/// <remarks>Does nothing besides throwing an exception.</remarks>
public Task<Token> GetToken(string authorizationCode, string redirectUri, CancellationToken? cancellationToken = null) =>
throw new IbanityConfigurationException(Message);
/// <inheritdoc />
/// <remarks>Does nothing besides throwing an exception.</remarks>
public Task<Token> GetToken(string refreshToken, CancellationToken? cancellationToken = null) =>
throw new IbanityConfigurationException(Message);
/// <inheritdoc />
/// <remarks>Does nothing besides throwing an exception.</remarks>
public Task<ClientAccessToken> GetToken(CancellationToken? cancellationToken = null) =>
throw new IbanityConfigurationException(Message);
/// <inheritdoc />
/// <remarks>Does nothing besides throwing an exception.</remarks>
public Task<Token> RefreshToken(Token token, CancellationToken? cancellationToken = null) =>
throw new IbanityConfigurationException(Message);
/// <inheritdoc />
/// <remarks>Does nothing besides throwing an exception.</remarks>
public Task<ClientAccessToken> RefreshToken(ClientAccessToken token, CancellationToken? cancellationToken = null) =>
throw new IbanityConfigurationException(Message);
/// <inheritdoc />
/// <remarks>Does nothing besides throwing an exception.</remarks>
public Task RevokeToken(Token token, CancellationToken? cancellationToken = null) =>
throw new IbanityConfigurationException(Message);
/// <inheritdoc />
/// <remarks>Does nothing besides throwing an exception.</remarks>
public Task<CustomerAccessToken> GetToken(string applicationCustomerReference, Guid? idempotencyKey, CancellationToken? cancellationToken) =>
throw new IbanityConfigurationException("Product doesn't support customer access tokens");
/// <inheritdoc />
/// <remarks>Does nothing besides throwing an exception.</remarks>
public Task<CustomerAccessToken> RefreshToken(CustomerAccessToken token, CancellationToken? cancellationToken) =>
throw new IbanityConfigurationException("Product doesn't support customer access tokens");
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Http | raw_data\ibanity-dotnet\src\Client\Http\OAuth2\HttpResponseMessageExtensions.cs | using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Utils;
using Ibanity.Apis.Client.Utils.Logging;
namespace Ibanity.Apis.Client.Http.OAuth2
{
/// <summary>
/// Add a few methods to <see cref="HttpResponseMessage" />.
/// </summary>
public static class HttpResponseMessageExtensions
{
private const string RequestIdHeader = "ibanity-request-id";
/// <summary>
/// <para>Checks status code and throws an exception if an error occurred.</para>
/// <para>The error payload will be contained inside the exception.</para>
/// </summary>
/// <param name="this"><see cref="HttpResponseMessage" /> instance</param>
/// <param name="serializer">To-string serializer</param>
/// <param name="logger">Logger used to log error</param>
/// <returns>The instance received in argument</returns>
public static async Task<HttpResponseMessage> ThrowOnOAuth2Failure(this HttpResponseMessage @this, ISerializer<string> serializer, ILogger logger)
{
if (@this is null)
throw new ArgumentNullException(nameof(@this));
if (serializer is null)
throw new ArgumentNullException(nameof(serializer));
if (@this.IsSuccessStatusCode)
return @this;
string body;
using (var content = @this.Content)
body = content == null
? null
: await content.ReadAsStringAsync().ConfigureAwait(false);
var requestId = @this.Headers.GetValues(RequestIdHeader).SingleOrDefault();
var statusCode = @this.StatusCode;
var errors = string.IsNullOrWhiteSpace(body)
? null
: serializer.Deserialize<OAuth2Error>(body);
var jsonApiError = errors != null && errors.Error == null
? serializer.Deserialize<JsonApi.Error>(body)
: errors?.ToJsonApi();
var exception = new IbanityOAuth2Exception(requestId, statusCode, jsonApiError);
logger.Error(exception.Message, exception);
throw exception;
}
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Http | raw_data\ibanity-dotnet\src\Client\Http\OAuth2\IbanityOAuth2Exception.cs | using System.Net;
namespace Ibanity.Apis.Client.Http.OAuth2
{
/// <summary>
/// Exception occurring when authenticating to Ibanity.
/// </summary>
public class IbanityOAuth2Exception : IbanityRequestException
{
/// <inheritdoc />
public IbanityOAuth2Exception(string requestId, HttpStatusCode statusCode, JsonApi.Error error) :
base(requestId, statusCode, error)
{ }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Http | raw_data\ibanity-dotnet\src\Client\Http\OAuth2\OAuth2ClientAccessTokenProvider.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Utils;
using Ibanity.Apis.Client.Utils.Logging;
namespace Ibanity.Apis.Client.Http.OAuth2
{
/// <inheritdoc />
public class OAuth2ClientAccessTokenProvider : IClientAccessTokenProvider
{
private const string RequestIdHeader = "ibanity-request-id";
private static readonly TimeSpan ValidityThreshold = TimeSpan.FromMinutes(1d);
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
private readonly IClock _clock;
private readonly ISerializer<string> _serializer;
private readonly string _urlPrefix;
private readonly string _clientId;
private readonly string _clientSecret;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="loggerFactory">Allow to build the logger used within this instance</param>
/// <param name="httpClient">Low-level HTTP client</param>
/// <param name="clock">Returns current date and time</param>
/// <param name="serializer">To-string serializer</param>
/// <param name="urlPrefix">Product endpoint</param>
/// <param name="clientId">OAuth2 client ID</param>
/// <param name="clientSecret">OAuth2 client secret</param>
public OAuth2ClientAccessTokenProvider(ILoggerFactory loggerFactory, HttpClient httpClient, IClock clock, ISerializer<string> serializer, string urlPrefix, string clientId, string clientSecret)
{
if (loggerFactory is null)
throw new ArgumentNullException(nameof(loggerFactory));
if (string.IsNullOrWhiteSpace(urlPrefix))
throw new ArgumentException($"'{nameof(urlPrefix)}' cannot be null or whitespace.", nameof(urlPrefix));
if (string.IsNullOrWhiteSpace(clientId))
throw new ArgumentException($"'{nameof(clientId)}' cannot be null or whitespace.", nameof(clientId));
if (string.IsNullOrWhiteSpace(clientSecret))
throw new ArgumentException($"'{nameof(clientSecret)}' cannot be null or whitespace.", nameof(clientSecret));
_logger = loggerFactory.CreateLogger<OAuth2ClientAccessTokenProvider>();
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
_urlPrefix = urlPrefix;
_clientId = clientId;
_clientSecret = clientSecret;
}
/// <inheritdoc />
public async Task<ClientAccessToken> GetToken(CancellationToken? cancellationToken)
{
var token = new ClientAccessToken(
null,
DateTimeOffset.MinValue);
return await RefreshToken(token, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<ClientAccessToken> RefreshToken(ClientAccessToken token, CancellationToken? cancellationToken)
{
if (token is null)
throw new ArgumentNullException(nameof(token));
if (token.ValidUntil - _clock.Now >= ValidityThreshold)
return token;
var payload = new Dictionary<string, string>
{
{ "grant_type", "client_credentials" }
};
var request = new HttpRequestMessage(HttpMethod.Post, $"{_urlPrefix}/oauth2/token")
{
Content = new FormUrlEncodedContent(payload)
};
request.Headers.Authorization = new BasicAuthenticationHeaderValue(_clientId, _clientSecret);
_logger.Debug("Getting new token from client credentials");
var result = await (await _httpClient.SendAsync(request, cancellationToken ?? CancellationToken.None).ConfigureAwait(false)).ThrowOnOAuth2Failure(_serializer, _logger).ConfigureAwait(false);
var requestId = result.Headers.TryGetValues(RequestIdHeader, out var values) ? values.SingleOrDefault() : null;
_logger.Debug($"Response received ({result.StatusCode:D} {result.StatusCode:G}): {request.Method.ToString().ToUpper(CultureInfo.InvariantCulture)} {request.RequestUri.AbsolutePath} (request ID: {requestId})");
var response = _serializer.Deserialize<OAuth2Response>(await result.Content.ReadAsStringAsync().ConfigureAwait(false));
token.AccessToken = response.AccessToken;
token.ValidUntil = _clock.Now + response.ExpiresIn;
return token;
}
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Http | raw_data\ibanity-dotnet\src\Client\Http\OAuth2\OAuth2Error.cs | using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.Http.OAuth2
{
/// <summary>
/// Payload received on authentication errors
/// </summary>
[DataContract]
public class OAuth2Error
{
/// <summary>
/// Error code.
/// </summary>
[DataMember(Name = "error")]
public string Error { get; set; }
/// <summary>
/// Error description.
/// </summary>
[DataMember(Name = "error_description")]
public string Description { get; set; }
/// <summary>
/// Convert to standard error format.
/// </summary>
/// <returns>JSON:API error</returns>
public JsonApi.Error ToJsonApi() => new JsonApi.Error
{
Errors = new List<JsonApi.ErrorItem>
{
new JsonApi.ErrorItem
{
Code = Error,
Detail = Description
}
}
};
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Http | raw_data\ibanity-dotnet\src\Client\Http\OAuth2\OAuth2Response.cs | using System;
using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.Http.OAuth2
{
/// <summary>
/// Payload received on OAuth2 operations.
/// </summary>
[DataContract]
public class OAuth2Response
{
/// <summary>
/// Access token.
/// </summary>
[DataMember(Name = "access_token")]
public string AccessToken { get; set; }
/// <summary>
/// Duration in seconds before the access token expires.
/// </summary>
[DataMember(Name = "expires_in")]
public int ExpiresInSeconds { get; set; }
/// <summary>
/// Duration before the access token expires.
/// </summary>
public TimeSpan ExpiresIn => TimeSpan.FromSeconds(ExpiresInSeconds);
/// <summary>
/// Refresh token.
/// </summary>
[DataMember(Name = "refresh_token")]
public string RefreshToken { get; set; }
/// <summary>
/// Scope.
/// </summary>
[DataMember(Name = "scope")]
public string Scope { get; set; }
/// <summary>
/// Token type (always bearer).
/// </summary>
[DataMember(Name = "token_type")]
public string TokenType { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Http | raw_data\ibanity-dotnet\src\Client\Http\OAuth2\OAuth2TokenProvider.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Utils;
using Ibanity.Apis.Client.Utils.Logging;
namespace Ibanity.Apis.Client.Http.OAuth2
{
/// <inheritdoc cref="ITokenProviderWithCodeVerifier" />
public class OAuth2TokenProvider : ITokenProviderWithCodeVerifier, ITokenProviderWithoutCodeVerifier
{
private const string RequestIdHeader = "ibanity-request-id";
private static readonly TimeSpan ValidityThreshold = TimeSpan.FromMinutes(1d);
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
private readonly IClock _clock;
private readonly ISerializer<string> _serializer;
private readonly string _urlPrefix;
private readonly string _clientId;
private readonly string _clientSecret;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="loggerFactory">Allow to build the logger used within this instance</param>
/// <param name="httpClient">Low-level HTTP client</param>
/// <param name="clock">Returns current date and time</param>
/// <param name="serializer">To-string serializer</param>
/// <param name="urlPrefix">Product endpoint</param>
/// <param name="clientId">OAuth2 client ID</param>
/// <param name="clientSecret">OAuth2 client secret</param>
public OAuth2TokenProvider(ILoggerFactory loggerFactory, HttpClient httpClient, IClock clock, ISerializer<string> serializer, string urlPrefix, string clientId, string clientSecret)
{
if (loggerFactory is null)
throw new ArgumentNullException(nameof(loggerFactory));
if (string.IsNullOrWhiteSpace(urlPrefix))
throw new ArgumentException($"'{nameof(urlPrefix)}' cannot be null or whitespace.", nameof(urlPrefix));
if (string.IsNullOrWhiteSpace(clientId))
throw new ArgumentException($"'{nameof(clientId)}' cannot be null or whitespace.", nameof(clientId));
if (string.IsNullOrWhiteSpace(clientSecret))
throw new ArgumentException($"'{nameof(clientSecret)}' cannot be null or whitespace.", nameof(clientSecret));
_logger = loggerFactory.CreateLogger<OAuth2TokenProvider>();
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
_urlPrefix = urlPrefix;
_clientId = clientId;
_clientSecret = clientSecret;
}
/// <inheritdoc />
public async Task<Token> GetToken(string authorizationCode, string codeVerifier, Uri redirectUri, CancellationToken? cancellationToken)
{
if (string.IsNullOrWhiteSpace(authorizationCode))
throw new ArgumentException($"'{nameof(authorizationCode)}' cannot be null or whitespace.", nameof(authorizationCode));
if (redirectUri is null)
throw new ArgumentNullException(nameof(redirectUri));
var payload = new Dictionary<string, string>
{
{ "grant_type", "authorization_code" },
{ "code", authorizationCode },
{ "client_id", _clientId },
{ "redirect_uri", redirectUri.OriginalString }
};
if (!string.IsNullOrWhiteSpace(codeVerifier))
payload.Add("code_verifier", codeVerifier);
var request = new HttpRequestMessage(HttpMethod.Post, $"{_urlPrefix}/oauth2/token")
{
Content = new FormUrlEncodedContent(payload)
};
request.Headers.Authorization = new BasicAuthenticationHeaderValue(_clientId, _clientSecret);
_logger.Debug("Getting new token from authorization code");
var result = await (await _httpClient.SendAsync(request, cancellationToken ?? CancellationToken.None).ConfigureAwait(false)).ThrowOnOAuth2Failure(_serializer, _logger).ConfigureAwait(false);
var requestId = result.Headers.TryGetValues(RequestIdHeader, out var values) ? values.SingleOrDefault() : null;
_logger.Debug($"Response received ({result.StatusCode:D} {result.StatusCode:G}): {request.Method.ToString().ToUpper(CultureInfo.InvariantCulture)} {request.RequestUri.AbsolutePath} (request ID: {requestId})");
var response = _serializer.Deserialize<OAuth2Response>(await result.Content.ReadAsStringAsync().ConfigureAwait(false));
if (string.IsNullOrWhiteSpace(response.RefreshToken))
_logger.Info("Missing refresh token, probably running without 'offline_access' scope");
return new Token(
response.AccessToken,
_clock.Now + response.ExpiresIn,
response.RefreshToken);
}
/// <inheritdoc />
public Task<Token> GetToken(string authorizationCode, string codeVerifier, string redirectUri, CancellationToken? cancellationToken) =>
GetToken(
authorizationCode,
codeVerifier,
new Uri(redirectUri ?? throw new ArgumentException($"'{nameof(redirectUri)}' cannot be null or whitespace.", nameof(redirectUri))),
cancellationToken);
/// <inheritdoc />
public Task<Token> GetToken(string authorizationCode, Uri redirectUri, CancellationToken? cancellationToken) =>
GetToken(authorizationCode, null, redirectUri, cancellationToken);
/// <inheritdoc />
public Task<Token> GetToken(string authorizationCode, string redirectUri, CancellationToken? cancellationToken) =>
GetToken(authorizationCode, null, redirectUri, cancellationToken);
/// <inheritdoc />
public async Task<Token> GetToken(string refreshToken, CancellationToken? cancellationToken)
{
if (string.IsNullOrWhiteSpace(refreshToken))
throw new ArgumentException($"'{nameof(refreshToken)}' cannot be null or whitespace.", nameof(refreshToken));
var token = new Token(
null,
DateTimeOffset.MinValue,
refreshToken);
return await RefreshToken(token, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<Token> RefreshToken(Token token, CancellationToken? cancellationToken)
{
if (token is null)
throw new ArgumentNullException(nameof(token));
if (token.ValidUntil - _clock.Now >= ValidityThreshold)
return token;
if (string.IsNullOrWhiteSpace(token.RefreshToken))
throw new IbanityException("Your access token is expired and there's no refresh token available. Did you forget 'offline_access' scope?");
var payload = new Dictionary<string, string>
{
{ "grant_type", "refresh_token" },
{ "refresh_token", token.RefreshToken },
{ "client_id", _clientId }
};
var request = new HttpRequestMessage(HttpMethod.Post, $"{_urlPrefix}/oauth2/token")
{
Content = new FormUrlEncodedContent(payload)
};
request.Headers.Authorization = new BasicAuthenticationHeaderValue(_clientId, _clientSecret);
_logger.Debug("Getting new token from refresh token");
var result = await (await _httpClient.SendAsync(request, cancellationToken ?? CancellationToken.None).ConfigureAwait(false)).ThrowOnOAuth2Failure(_serializer, _logger).ConfigureAwait(false);
var requestId = result.Headers.TryGetValues(RequestIdHeader, out var values) ? values.SingleOrDefault() : null;
_logger.Debug($"Response received ({result.StatusCode:D} {result.StatusCode:G}): {request.Method.ToString().ToUpper(CultureInfo.InvariantCulture)} {request.RequestUri.AbsolutePath} (request ID: {requestId})");
var response = _serializer.Deserialize<OAuth2Response>(await result.Content.ReadAsStringAsync().ConfigureAwait(false));
token.AccessToken = response.AccessToken;
token.ValidUntil = _clock.Now + response.ExpiresIn;
token.RefreshToken = response.RefreshToken;
return token;
}
/// <inheritdoc />
public async Task RevokeToken(Token token, CancellationToken? cancellationToken)
{
if (token is null)
throw new ArgumentNullException(nameof(token));
var payload = new Dictionary<string, string>
{
{ "token", token.RefreshToken }
};
var request = new HttpRequestMessage(HttpMethod.Post, $"{_urlPrefix}/oauth2/revoke")
{
Content = new FormUrlEncodedContent(payload)
};
request.Headers.Authorization = new BasicAuthenticationHeaderValue(_clientId, _clientSecret);
var result = await (await _httpClient.SendAsync(request, cancellationToken ?? CancellationToken.None).ConfigureAwait(false)).ThrowOnOAuth2Failure(_serializer, _logger).ConfigureAwait(false);
var requestId = result.Headers.TryGetValues(RequestIdHeader, out var values) ? values.SingleOrDefault() : null;
_logger.Debug($"Response received ({result.StatusCode:D} {result.StatusCode:G}): {request.Method.ToString().ToUpper(CultureInfo.InvariantCulture)} {request.RequestUri.AbsolutePath} (request ID: {requestId})");
}
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\JsonApi\Collection.cs | using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.JsonApi
{
/// <summary>
/// JSON:API collection.
/// </summary>
/// <typeparam name="TAttributes">Items attribute type</typeparam>
/// <typeparam name="TMeta">Items meta type</typeparam>
/// <typeparam name="TRelationships">Items relationships type</typeparam>
/// <typeparam name="TLinks">Items links type</typeparam>
/// <typeparam name="TPaging">Paging type</typeparam>
[DataContract]
#pragma warning disable CA1711 // Keep 'Collection' name as specified in JSON:API
public class Collection<TAttributes, TMeta, TRelationships, TLinks, TPaging>
#pragma warning restore CA1711
{
/// <summary>
/// Meta.
/// </summary>
[DataMember(Name = "meta", EmitDefaultValue = false)]
public CollectionMeta<TPaging> Meta { get; set; }
/// <summary>
/// Links.
/// </summary>
[DataMember(Name = "links", EmitDefaultValue = false)]
public CollectionLinks Links { get; set; }
/// <summary>
/// Items list.
/// </summary>
[DataMember(Name = "data", EmitDefaultValue = false)]
public List<Data<TAttributes, TMeta, TRelationships, TLinks>> Data { get; set; } =
new List<Data<TAttributes, TMeta, TRelationships, TLinks>>();
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\JsonApi\CollectionLinks.cs | using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.JsonApi
{
/// <summary>
/// Collection links (next, first, ...).
/// </summary>
[DataContract]
public class CollectionLinks
{
/// <summary>
/// Link to the first page.
/// </summary>
[DataMember(Name = "first", EmitDefaultValue = false)]
public string First { get; set; }
/// <summary>
/// Link to the previous page.
/// </summary>
[DataMember(Name = "prev", EmitDefaultValue = false)]
public string Previous { get; set; }
/// <summary>
/// Link to the next page.
/// </summary>
[DataMember(Name = "next", EmitDefaultValue = false)]
public string Next { get; set; }
/// <summary>
/// Link to the last page.
/// </summary>
[DataMember(Name = "last", EmitDefaultValue = false)]
public string Last { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\JsonApi\CollectionMeta.cs | using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.JsonApi
{
/// <summary>
/// Collection meta.
/// </summary>
[DataContract]
public class CollectionMeta<TPaging>
{
/// <summary>
/// Paging information.
/// </summary>
[DataMember(Name = "paging", EmitDefaultValue = false)]
public TPaging Paging { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\JsonApi\Data.cs | using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.JsonApi
{
/// <summary>
/// Resource container.
/// </summary>
[DataContract]
public class Data
{
/// <summary>
/// Resource type.
/// </summary>
[DataMember(Name = "type", EmitDefaultValue = false)]
public string Type { get; set; }
/// <summary>
/// Resource ID.
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public string Id { get; set; }
}
/// <summary>
/// Resource container.
/// </summary>
/// <typeparam name="TAttributes">Resource attribute type</typeparam>
/// <typeparam name="TMeta">Resource meta type</typeparam>
/// <typeparam name="TRelationships">Resource relationships type</typeparam>
/// <typeparam name="TLinks">Resource links type</typeparam>
[DataContract]
public class Data<TAttributes, TMeta, TRelationships, TLinks> : Data
{
/// <summary>
/// Resource actual content.
/// </summary>
[DataMember(Name = "attributes", EmitDefaultValue = false)]
public TAttributes Attributes { get; set; }
/// <summary>
/// Resource meta.
/// </summary>
[DataMember(Name = "meta", EmitDefaultValue = false)]
public TMeta Meta { get; set; }
/// <summary>
/// Resource relationships.
/// </summary>
[DataMember(Name = "relationships", EmitDefaultValue = false)]
public TRelationships Relationships { get; set; }
/// <summary>
/// Resource links.
/// </summary>
[DataMember(Name = "links", EmitDefaultValue = false)]
public TLinks Links { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\JsonApi\Error.cs | using System.Collections.Generic;
namespace Ibanity.Apis.Client.JsonApi
{
/// <summary>
/// Errors collection.
/// </summary>
public class Error
{
/// <summary>
/// Errors list.
/// </summary>
public List<ErrorItem> Errors { get; set; }
}
/// <summary>
/// Error.
/// </summary>
public class ErrorItem
{
/// <summary>
/// Error code.
/// </summary>
public string Code { get; set; }
/// <summary>
/// Error description.
/// </summary>
public string Detail { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\JsonApi\Paging.cs | using System;
using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.JsonApi
{
/// <summary>
/// Cursor-based paging.
/// </summary>
[DataContract]
public class CursorBasedPaging
{
/// <summary>
/// Page size.
/// </summary>
[DataMember(Name = "limit", EmitDefaultValue = false)]
public long? Limit { get; set; }
/// <summary>
/// Previous item.
/// </summary>
[DataMember(Name = "before", EmitDefaultValue = false)]
public Guid? Before { get; set; }
/// <summary>
/// Next item.
/// </summary>
[DataMember(Name = "after", EmitDefaultValue = false)]
public Guid? After { get; set; }
}
/// <summary>
/// Offset-based paging.
/// </summary>
[DataContract]
public class OffsetBasedPaging
{
/// <summary>
/// Start position of the results by giving the number of records to be skipped.
/// </summary>
[DataMember(Name = "offset", EmitDefaultValue = false)]
public long? Offset { get; set; }
/// <summary>
/// Number of total resources in the requested scope.
/// </summary>
[DataMember(Name = "total", EmitDefaultValue = false)]
public long? Total { get; set; }
}
/// <summary>
/// Page-based paging.
/// </summary>
[DataContract]
public class PageBasedPaging
{
/// <summary>
/// Index of the results page.
/// </summary>
[DataMember(Name = "number", EmitDefaultValue = false)]
public long? Number { get; set; }
/// <summary>
/// Number of returned resources.
/// </summary>
[DataMember(Name = "size", EmitDefaultValue = false)]
public int? Size { get; set; }
/// <summary>
/// Number of total resources in the requested scope.
/// </summary>
[DataMember(Name = "total", EmitDefaultValue = false)]
public long? Total { get; set; }
/// <summary>
/// Number of total resources in the requested scope.
/// </summary>
[DataMember(Name = "totalEntries", EmitDefaultValue = false)]
public long? TotalEntries { get; set; }
/// <summary>
/// Number of total pages in the requested scope.
/// </summary>
[DataMember(Name = "totalPages", EmitDefaultValue = false)]
public long? TotalPages { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\JsonApi\Relationship.cs | using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.JsonApi
{
/// <summary>
/// Resource relationship.
/// </summary>
[DataContract]
public class BaseRelationship
{
/// <summary>
/// Links to other resources.
/// </summary>
[DataMember(Name = "links", EmitDefaultValue = false)]
public Dictionary<string, string> Links { get; set; }
}
/// <summary>
/// Resource relationship.
/// </summary>
[DataContract]
public class Relationship : BaseRelationship
{
/// <summary>
/// Linked resource.
/// </summary>
[DataMember(Name = "data", EmitDefaultValue = false)]
public Data Data { get; set; }
}
/// <summary>
/// Resource relationship.
/// </summary>
[DataContract]
public class Relationship<TAttributes> : BaseRelationship
{
/// <summary>
/// Linked resource.
/// </summary>
[DataMember(Name = "data", EmitDefaultValue = false)]
public Data<TAttributes, object, object, object> Data { get; set; }
}
/// <summary>
/// Resource relationships.
/// </summary>
[DataContract]
public class Relationships
{
/// <summary>
/// Linked resources.
/// </summary>
[DataMember(Name = "data", EmitDefaultValue = false)]
public Data[] Data { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\JsonApi\Resource.cs | using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.JsonApi
{
/// <summary>
/// Single resource.
/// </summary>
/// <typeparam name="TAttributes">Resource attribute type</typeparam>
/// <typeparam name="TMeta">Resource meta type</typeparam>
/// <typeparam name="TRelationships">Resource relationships type</typeparam>
/// <typeparam name="TLinks">Resource links type</typeparam>
[DataContract]
public class Resource<TAttributes, TMeta, TRelationships, TLinks>
{
/// <summary>
/// Actual item.
/// </summary>
[DataMember(Name = "data", EmitDefaultValue = false)]
public Data<TAttributes, TMeta, TRelationships, TLinks> Data { get; set; }
/// <summary>
/// Resource metadata.
/// </summary>
[DataMember(Name = "meta", EmitDefaultValue = false)]
public TMeta Meta { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Models\Filter.cs | using System;
using System.Globalization;
namespace Ibanity.Apis.Client.Models
{
/// <summary>
/// Filter results when using <c>List</c> methods.
/// </summary>
public class Filter
{
private readonly string _field;
private readonly FilterOperator _operator;
private readonly string _value;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="field">Resource field to check</param>
/// <param name="operator">Comparison type</param>
/// <param name="value">Value to check for</param>
public Filter(string field, FilterOperator @operator, string value)
{
if (string.IsNullOrWhiteSpace(field))
throw new ArgumentException($"'{nameof(field)}' cannot be null or whitespace.", nameof(field));
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException($"'{nameof(value)}' cannot be null or whitespace.", nameof(value));
_field = field;
_operator = @operator;
_value = value;
}
/// <summary>
/// String representation of the filter.
/// </summary>
/// <returns>Filter to be used in query string</returns>
public override string ToString() =>
$"filter[{_field}][{_operator.ToString("g").ToLower(CultureInfo.InvariantCulture)}]={_value}";
}
/// <summary>
/// Comparison types.
/// </summary>
public enum FilterOperator
{
/// <summary>
/// Equals.
/// </summary>
Eq,
/// <summary>
/// Fuzzy match.
/// </summary>
Like,
/// <summary>
/// Contains.
/// </summary>
Contains,
/// <summary>
/// In.
/// </summary>
In
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Products\ProductClient.cs | using System;
using Ibanity.Apis.Client.Http;
namespace Ibanity.Apis.Client.Products
{
/// <summary>
/// Base product client.
/// </summary>
public abstract class ProductClient<T> : IProductWithRefreshTokenClient<T> where T : class, ITokenProvider
{
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="tokenService">Service to generate and refresh access tokens</param>
/// <param name="clientAccessTokenService">Service to generate and refresh client access tokens.</param>
/// <param name="customerTokenService">Service to generate and refresh customer access tokens.</param>
protected ProductClient(IApiClient apiClient, T tokenService, IClientAccessTokenProvider clientAccessTokenService, ICustomerAccessTokenProvider customerTokenService)
{
ApiClient = apiClient ?? throw new ArgumentNullException(nameof(apiClient));
TokenService = tokenService ?? throw new ArgumentNullException(nameof(tokenService));
ClientTokenService = clientAccessTokenService ?? throw new ArgumentNullException(nameof(clientAccessTokenService));
CustomerTokenService = customerTokenService ?? throw new ArgumentNullException(nameof(customerTokenService));
}
/// <inheritdoc />
public IApiClient ApiClient { get; }
/// <inheritdoc />
public T TokenService { get; }
/// <inheritdoc />
public IClientAccessTokenProvider ClientTokenService { get; }
/// <inheritdoc />
public ICustomerAccessTokenProvider CustomerTokenService { get; }
}
/// <summary>
/// Base product client interface.
/// </summary>
public interface IProductWithRefreshTokenClient<out T> : IProductClientWithClientAccessToken where T : ITokenProvider
{
/// <summary>
/// Service to generate and refresh access tokens.
/// </summary>
T TokenService { get; }
}
/// <summary>
/// Base product client interface.
/// </summary>
public interface IProductClient
{
/// <summary>
/// Generic API client.
/// </summary>
IApiClient ApiClient { get; }
}
/// <summary>
/// Base product client interface.
/// </summary>
public interface IProductClientWithClientAccessToken : IProductClient
{
/// <summary>
/// Service to generate and refresh client access tokens.
/// </summary>
IClientAccessTokenProvider ClientTokenService { get; }
}
/// <summary>
/// Base product client interface.
/// </summary>
public interface IProductClientWithCustomerAccessToken : IProductClient
{
/// <summary>
/// Service to generate and refresh customer access tokens.
/// </summary>
ICustomerAccessTokenProvider CustomerTokenService { get; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client | raw_data\ibanity-dotnet\src\Client\Products\ResourceClient.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Models;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products
{
/// <summary>
/// Base class to manage an API resource.
/// </summary>
/// <typeparam name="TAttributes">Resource attribute type</typeparam>
/// <typeparam name="TMeta">Resource meta type</typeparam>
/// <typeparam name="TRelationships">Resource relationships type</typeparam>
/// <typeparam name="TLinks">Resource links type</typeparam>
/// <typeparam name="TId">Resource ID type</typeparam>
/// <typeparam name="TToken">Token type</typeparam>
public abstract class BaseResourceClient<TAttributes, TMeta, TRelationships, TLinks, TId, TToken> where TAttributes : IIdentified<TId> where TToken : BaseToken
{
private readonly IApiClient _apiClient;
private readonly IAccessTokenProvider<TToken> _accessTokenProvider;
private readonly bool _generateIdempotencyKey;
/// <summary>
/// Beginning of URIs, composed by Ibanity API endpoint, followed by product name.
/// </summary>
protected string UrlPrefix { get; }
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
/// <param name="generateIdempotencyKey">Generate a random idempotency key if none was specified</param>
protected BaseResourceClient(IApiClient apiClient, IAccessTokenProvider<TToken> accessTokenProvider, string urlPrefix, bool generateIdempotencyKey)
{
if (string.IsNullOrWhiteSpace(urlPrefix))
throw new ArgumentException($"'{nameof(urlPrefix)}' cannot be null or whitespace.", nameof(urlPrefix));
_apiClient = apiClient ?? throw new ArgumentNullException(nameof(apiClient));
_accessTokenProvider = accessTokenProvider ?? throw new ArgumentNullException(nameof(accessTokenProvider));
UrlPrefix = urlPrefix;
_generateIdempotencyKey = generateIdempotencyKey;
}
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Resource collection path</param>
/// <param name="filters">Attributes to be filtered from the results</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="pageBefore">Cursor that specifies the first resource of the next page</param>
/// <param name="pageAfter">Cursor that specifies the last resource of the previous page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected Task<IbanityCollection<TAttributes>> InternalCursorBasedList(TToken token, string path, IEnumerable<Filter> filters, int? pageSize, Guid? pageBefore, Guid? pageAfter, CancellationToken? cancellationToken)
{
var parameters = (filters ?? Enumerable.Empty<Filter>()).Select(f => f.ToString()).ToList();
if (pageSize.HasValue)
parameters.Add($"page[limit]={pageSize.Value}");
if (pageBefore.HasValue)
parameters.Add($"page[before]={pageBefore.Value:D}");
if (pageAfter.HasValue)
parameters.Add($"page[after]={pageAfter.Value:D}");
// we need a proper builder here
var queryParameters = parameters.Any()
? "?" + string.Join("&", parameters)
: string.Empty;
return InternalCursorBasedList(
token,
$"{path}{queryParameters}",
cancellationToken);
}
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Resource collection path</param>
/// <param name="filters">Attributes to be filtered from the results</param>
/// <param name="customParameters">Custom parameters</param>
/// <param name="pageOffset">Defines the start position of the results by giving the number of records to be skipped</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected Task<IsabelCollection<TAttributes>> InternalOffsetBasedList(TToken token, string path, IEnumerable<Filter> filters, IEnumerable<(string, string)> customParameters, long? pageOffset, int? pageSize, CancellationToken? cancellationToken)
{
var parameters = (filters ?? Enumerable.Empty<Filter>()).Select(f => f.ToString()).ToList();
if (customParameters != null)
parameters.AddRange(customParameters.Select(p => $"{p.Item1}={p.Item2}"));
if (pageSize.HasValue)
parameters.Add($"size={pageSize.Value}");
if (pageOffset.HasValue)
parameters.Add($"offset={pageOffset.Value}");
// we need a proper builder here
var queryParameters = parameters.Any()
? "?" + string.Join("&", parameters)
: string.Empty;
return InternalOffsetBasedList(
token,
$"{path}{queryParameters}",
cancellationToken);
}
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Resource collection path</param>
/// <param name="filters">Attributes to be filtered from the results</param>
/// <param name="customParameters">Custom parameters</param>
/// <param name="pageNumber">Number of page that should be returned. Must be included to use page-based pagination.</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected Task<EInvoicingCollection<TAttributes>> InternalPageBasedList(TToken token, string path, IEnumerable<Filter> filters, IEnumerable<(string, string)> customParameters, long? pageNumber, int? pageSize, CancellationToken? cancellationToken)
{
var parameters = (filters ?? Enumerable.Empty<Filter>()).Select(f => f.ToString()).ToList();
if (customParameters != null)
parameters.AddRange(customParameters.Select(p => $"{p.Item1}={p.Item2}"));
if (pageSize.HasValue)
parameters.Add($"page[size]={pageSize.Value}");
if (pageNumber.HasValue)
parameters.Add($"page[number]={pageNumber.Value}");
// we need a proper builder here
var queryParameters = parameters.Any()
? "?" + string.Join("&", parameters)
: string.Empty;
return InternalPageBasedList(
token,
$"{path}{queryParameters}",
cancellationToken);
}
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Resource collection path</param>
/// <param name="filters">Attributes to be filtered from the results</param>
/// <param name="customParameters">Custom parameters</param>
/// <param name="pageNumber">Number of page that should be returned. Must be included to use page-based pagination.</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected Task<PageBasedXS2ACollection<TAttributes>> InternalXs2aPageBasedList(TToken token, string path, IEnumerable<Filter> filters, IEnumerable<(string, string)> customParameters, long? pageNumber, int? pageSize, CancellationToken? cancellationToken)
{
var parameters = (filters ?? Enumerable.Empty<Filter>()).Select(f => f.ToString()).ToList();
if (customParameters != null)
parameters.AddRange(customParameters.Select(p => $"{p.Item1}={p.Item2}"));
if (pageSize.HasValue)
parameters.Add($"page[size]={pageSize.Value}");
if (pageNumber.HasValue)
parameters.Add($"page[number]={pageNumber.Value}");
// we need a proper builder here
var queryParameters = parameters.Any()
? "?" + string.Join("&", parameters)
: string.Empty;
return InternalXs2aPageBasedList(
token,
$"{path}{queryParameters}",
cancellationToken);
}
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="continuationToken">Token referencing the page to request</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Requested page of items</returns>
protected Task<IbanityCollection<TAttributes>> InternalCursorBasedList(TToken token, ContinuationToken continuationToken, CancellationToken? cancellationToken) =>
InternalCursorBasedList(
token ?? throw new ArgumentNullException(nameof(token)),
(continuationToken ?? throw new ArgumentNullException(nameof(continuationToken))).NextUrl,
cancellationToken);
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Resource collection path</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected async Task<IbanityCollection<TAttributes>> InternalCursorBasedList(TToken token, string path, CancellationToken? cancellationToken)
{
var page = await _apiClient.Get<JsonApi.Collection<TAttributes, TMeta, TRelationships, TLinks, JsonApi.CursorBasedPaging>>(
path,
await GetAccessToken(token).ConfigureAwait(false),
cancellationToken ?? CancellationToken.None).ConfigureAwait(false);
var result = new IbanityCollection<TAttributes>()
{
PageLimit = page.Meta?.Paging?.Limit,
BeforeCursor = page.Meta?.Paging?.Before,
AfterCursor = page.Meta?.Paging?.After,
FirstLink = page.Links?.First,
PreviousLink = page.Links?.Previous,
NextLink = page.Links?.Next,
Items = page.Data.Select(Map).ToList(),
ContinuationToken = page.Links?.Next == null
? null
: new ContinuationToken { NextUrl = page.Links.Next }
};
return result;
}
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Resource collection path</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected async Task<IsabelCollection<TAttributes>> InternalOffsetBasedList(TToken token, string path, CancellationToken? cancellationToken)
{
var page = await _apiClient.Get<JsonApi.Collection<TAttributes, TMeta, TRelationships, TLinks, JsonApi.OffsetBasedPaging>>(
path,
await GetAccessToken(token).ConfigureAwait(false),
cancellationToken ?? CancellationToken.None).ConfigureAwait(false);
var result = new IsabelCollection<TAttributes>()
{
Offset = page.Meta.Paging.Offset,
Total = page.Meta.Paging.Total,
Items = page.Data.Select(Map).ToList(),
ContinuationToken = page.Meta.Paging.Total <= page.Meta.Paging.Offset + page.Data.Count
? null
: new ContinuationToken
{
PageSize = page.Data.Count,
PageOffset = page.Meta.Paging.Offset + page.Data.Count
}
};
return result;
}
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Resource collection path</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected async Task<EInvoicingCollection<TAttributes>> InternalPageBasedList(TToken token, string path, CancellationToken? cancellationToken)
{
var page = await _apiClient.Get<JsonApi.Collection<TAttributes, TMeta, TRelationships, TLinks, JsonApi.PageBasedPaging>>(
path,
await GetAccessToken(token).ConfigureAwait(false),
cancellationToken ?? CancellationToken.None).ConfigureAwait(false);
var result = new EInvoicingCollection<TAttributes>()
{
Number = page.Meta.Paging.Number,
Size = page.Meta.Paging.Size,
Total = page.Meta.Paging.Total,
Items = page.Data.Select(Map).ToList()
};
return result;
}
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Resource collection path</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected async Task<PageBasedXS2ACollection<TAttributes>> InternalXs2aPageBasedList(TToken token, string path, CancellationToken? cancellationToken)
{
var page = await _apiClient.Get<JsonApi.Collection<TAttributes, TMeta, TRelationships, TLinks, JsonApi.PageBasedPaging>>(
path,
await GetAccessToken(token).ConfigureAwait(false),
cancellationToken ?? CancellationToken.None).ConfigureAwait(false);
var result = new PageBasedXS2ACollection<TAttributes>()
{
Number = page.Meta.Paging.Number,
Size = page.Meta.Paging.Size,
TotalEntries = page.Meta.Paging.TotalEntries,
TotalPages = page.Meta.Paging.TotalPages,
Items = page.Data.Select(Map).ToList(),
FirstLink = page.Links.First,
LastLink = page.Links.Last,
NextLink = page.Links.Next,
PreviousLink = page.Links.Previous
};
return result;
}
/// <summary>
/// Get a single resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Path part preceding the ID</param>
/// <param name="id">Unique identifier of the resource</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Requested resource</returns>
protected async Task<TAttributes> InternalGet(TToken token, string path, TId id, CancellationToken? cancellationToken) =>
Map((await _apiClient.Get<JsonApi.Resource<TAttributes, TMeta, TRelationships, TLinks>>(
$"{path}/{id}",
await GetAccessToken(token).ConfigureAwait(false),
cancellationToken ?? CancellationToken.None).ConfigureAwait(false)).Data);
/// <summary>
/// Delete a single resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Path part preceding the ID</param>
/// <param name="id">Unique identifier of the resource</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
protected async Task InternalDelete(TToken token, string path, TId id, CancellationToken? cancellationToken) =>
await _apiClient.Delete(
$"{path}/{id}",
await GetAccessToken(token).ConfigureAwait(false),
cancellationToken ?? CancellationToken.None).ConfigureAwait(false);
/// <summary>
/// Delete a resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Resource collection path</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
protected async Task<TAttributes> InternalDelete(TToken token, string path, CancellationToken? cancellationToken) =>
Map((await _apiClient.Delete<JsonApi.Resource<TAttributes, TMeta, TRelationships, TLinks>>(
path,
await GetAccessToken(token).ConfigureAwait(false),
cancellationToken ?? CancellationToken.None).ConfigureAwait(false)).Data);
private Guid? GetIdempotencyKey(Guid? from) => from ?? (_generateIdempotencyKey ? (Guid?)Guid.NewGuid() : null);
/// <summary>
/// Create a new resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Resource collection path</param>
/// <param name="payload">Resource data</param>
/// <param name="idempotencyKey">Several requests with the same idempotency key will be executed only once</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The created resource</returns>
protected Task<TAttributes> InternalCreate<TRequestAttributes, TRequestMeta, TRequestRelationships, TRequestLinks>(TToken token, string path, JsonApi.Data<TRequestAttributes, TRequestMeta, TRequestRelationships, TRequestLinks> payload, Guid? idempotencyKey, CancellationToken? cancellationToken) =>
InternalCreate(
token,
path,
new JsonApi.Resource<TRequestAttributes, TRequestMeta, TRequestRelationships, TRequestLinks> { Data = payload },
idempotencyKey,
cancellationToken);
/// <summary>
/// Create a new resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Resource collection path</param>
/// <param name="resource">Resource</param>
/// <param name="idempotencyKey">Several requests with the same idempotency key will be executed only once</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The created resource</returns>
protected async Task<TAttributes> InternalCreate<TRequestAttributes, TRequestMeta, TRequestRelationships, TRequestLinks>(TToken token, string path, JsonApi.Resource<TRequestAttributes, TRequestMeta, TRequestRelationships, TRequestLinks> resource, Guid? idempotencyKey, CancellationToken? cancellationToken) =>
Map((await _apiClient.Post<JsonApi.Resource<TRequestAttributes, TRequestMeta, TRequestRelationships, TRequestLinks>, JsonApi.Resource<TAttributes, TMeta, TRelationships, TLinks>>(
path,
await GetAccessToken(token).ConfigureAwait(false),
resource,
GetIdempotencyKey(idempotencyKey),
cancellationToken ?? CancellationToken.None).ConfigureAwait(false)).Data);
/// <summary>
/// Create a new resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Resource collection path</param>
/// <param name="id">Unique identifier of the resource</param>
/// <param name="payload">Resource data</param>
/// <param name="idempotencyKey">Several requests with the same idempotency key will be executed only once</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The updated resource</returns>
protected async Task<TAttributes> InternalUpdate<T>(TToken token, string path, TId id, JsonApi.Data<T, object, object, object> payload, Guid? idempotencyKey, CancellationToken? cancellationToken) =>
Map((await _apiClient.Patch<JsonApi.Resource<T, object, object, object>, JsonApi.Resource<TAttributes, TMeta, TRelationships, TLinks>>(
$"{path}/{id}",
await GetAccessToken(token).ConfigureAwait(false),
new JsonApi.Resource<T, object, object, object> { Data = payload },
GetIdempotencyKey(idempotencyKey),
cancellationToken ?? CancellationToken.None).ConfigureAwait(false)).Data);
/// <summary>
/// Get payload and write it to a provided stream.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="path">Path part preceding the ID</param>
/// <param name="id">Unique identifier of the resource</param>
/// <param name="acceptHeader">Format of the response you expect from the call</param>
/// <param name="target">Destination stream where the payload will be written to</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
protected async Task InternalGetToStream(TToken token, string path, TId id, string acceptHeader, Stream target, CancellationToken? cancellationToken) =>
await _apiClient.GetToStream(
$"{path}/{id}",
await GetAccessToken(token).ConfigureAwait(false),
acceptHeader,
target,
cancellationToken ?? CancellationToken.None).ConfigureAwait(false);
/// <summary>
/// Map received JSON:API data to a single-level object.
/// </summary>
/// <param name="data">Data received from the server</param>
/// <returns>A single-level object ready to be used by the client application</returns>
protected virtual TAttributes Map(JsonApi.Data<TAttributes, TMeta, TRelationships, TLinks> data)
{
if (data is null)
throw new ArgumentNullException(nameof(data));
var result = data.Attributes;
result.Id = ParseId(data.Id);
return result;
}
/// <summary>
/// Parse identifier.
/// </summary>
/// <param name="id">String representation of the resource identifier</param>
/// <returns></returns>
protected abstract TId ParseId(string id);
/// <summary>
/// Refresh the token if necessary and returns the bearer token.
/// </summary>
/// <param name="token">Authentication token</param>
/// <returns>Bearer token</returns>
protected async Task<string> GetAccessToken(TToken token) => token == null
? null
: (await _accessTokenProvider.RefreshToken(token).ConfigureAwait(false)).AccessToken;
}
/// <summary>
/// Base class to manage an API resource with a single ID.
/// </summary>
/// <typeparam name="TAttributes">Resource attribute type</typeparam>
/// <typeparam name="TMeta">Resource meta type</typeparam>
/// <typeparam name="TRelationships">Resource relationships type</typeparam>
/// <typeparam name="TLinks">Resource links type</typeparam>
/// <typeparam name="TId">Resource ID type</typeparam>
/// <typeparam name="TToken">Token type</typeparam>
public abstract class ResourceClient<TAttributes, TMeta, TRelationships, TLinks, TId, TToken> :
BaseResourceClient<TAttributes, TMeta, TRelationships, TLinks, TId, TToken> where TAttributes : IIdentified<TId> where TToken : BaseToken
{
private readonly string _entityName;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
/// <param name="entityName">Name of the resource</param>
/// <param name="generateIdempotencyKey">Generate a random idempotency key if none was specified</param>
protected ResourceClient(IApiClient apiClient, IAccessTokenProvider<TToken> accessTokenProvider, string urlPrefix, string entityName, bool generateIdempotencyKey = true) :
base(apiClient, accessTokenProvider, urlPrefix, generateIdempotencyKey)
{
if (string.IsNullOrWhiteSpace(entityName))
throw new ArgumentException($"'{nameof(entityName)}' cannot be null or whitespace.", nameof(entityName));
_entityName = entityName;
}
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="filters">Attributes to be filtered from the results</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="pageBefore">Cursor that specifies the first resource of the next page</param>
/// <param name="pageAfter">Cursor that specifies the last resource of the previous page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected Task<IbanityCollection<TAttributes>> InternalCursorBasedList(TToken token, IEnumerable<Filter> filters, int? pageSize, Guid? pageBefore, Guid? pageAfter, CancellationToken? cancellationToken) =>
InternalCursorBasedList(token, GetPath(), filters, pageSize, pageBefore, pageAfter, cancellationToken);
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="filters">Attributes to be filtered from the results</param>
/// <param name="customParameters">Custom parameters</param>
/// <param name="pageOffset">Defines the start position of the results by giving the number of records to be skipped</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected Task<IsabelCollection<TAttributes>> InternalOffsetBasedList(TToken token, IEnumerable<Filter> filters, IEnumerable<(string, string)> customParameters, long? pageOffset, int? pageSize, CancellationToken? cancellationToken) =>
InternalOffsetBasedList(token, GetPath(), filters, customParameters, pageOffset, pageSize, cancellationToken);
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="filters">Attributes to be filtered from the results</param>
/// <param name="customParameters">Custom parameters</param>
/// <param name="pageNumber">Number of page that should be returned. Must be included to use page-based pagination.</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected Task<EInvoicingCollection<TAttributes>> InternalPageBasedList(TToken token, IEnumerable<Filter> filters, IEnumerable<(string, string)> customParameters, long? pageNumber, int? pageSize, CancellationToken? cancellationToken) =>
InternalPageBasedList(token, GetPath(), filters, customParameters, pageNumber, pageSize, cancellationToken);
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="filters">Attributes to be filtered from the results</param>
/// <param name="customParameters">Custom parameters</param>
/// <param name="pageNumber">Number of page that should be returned. Must be included to use page-based pagination.</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected Task<PageBasedXS2ACollection<TAttributes>> InternalXs2aPageBasedList(TToken token, IEnumerable<Filter> filters, IEnumerable<(string, string)> customParameters, long? pageNumber, int? pageSize, CancellationToken? cancellationToken) =>
InternalXs2aPageBasedList(token, GetPath(), filters, null, pageNumber, pageSize, cancellationToken);
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="continuationToken">Token referencing the page to request</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected Task<IsabelCollection<TAttributes>> InternalOffsetBasedList(TToken token, ContinuationToken continuationToken, CancellationToken? cancellationToken) =>
InternalOffsetBasedList(token, GetPath(), null, null, continuationToken.PageOffset, continuationToken.PageSize, cancellationToken);
/// <summary>
/// Get a single resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="id">Unique identifier of the resource</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Requested resource</returns>
protected Task<TAttributes> InternalGet(TToken token, TId id, CancellationToken? cancellationToken) =>
InternalGet(token, GetPath(), id, cancellationToken);
/// <summary>
/// Get payload and write it to a provided stream.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="id">Unique identifier of the resource</param>
/// <param name="acceptHeader">Format of the response you expect from the call</param>
/// <param name="target">Destination stream where the payload will be written to</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
protected Task InternalGetToStream(TToken token, TId id, string acceptHeader, Stream target, CancellationToken? cancellationToken) =>
InternalGetToStream(token, GetPath(), id, acceptHeader, target, cancellationToken);
/// <summary>
/// Delete a single resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="id">Unique identifier of the resource</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
protected Task InternalDelete(TToken token, TId id, CancellationToken? cancellationToken) =>
InternalDelete(token, GetPath(), id, cancellationToken);
/// <summary>
/// Delete a resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
protected Task<TAttributes> InternalDelete(TToken token, CancellationToken? cancellationToken) =>
InternalDelete(token, GetPath(), cancellationToken);
/// <summary>
/// Create a new resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="payload">Resource data</param>
/// <param name="idempotencyKey">Several requests with the same idempotency key will be executed only once</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The created resource</returns>
protected Task<TAttributes> InternalCreate<T>(TToken token, JsonApi.Data<T, object, object, object> payload, Guid? idempotencyKey, CancellationToken? cancellationToken) =>
InternalCreate(token, GetPath(), payload, idempotencyKey, cancellationToken);
/// <summary>
/// Update a resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="id">Unique identifier of the resource</param>
/// <param name="payload">Resource data</param>
/// <param name="idempotencyKey">Several requests with the same idempotency key will be executed only once</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Requested resource</returns>
protected Task<TAttributes> InternalUpdate<T>(TToken token, TId id, JsonApi.Data<T, object, object, object> payload, Guid? idempotencyKey, CancellationToken? cancellationToken) =>
InternalUpdate(token, GetPath(), id, payload, idempotencyKey, cancellationToken);
private string GetPath() =>
$"{UrlPrefix}/{_entityName}";
}
/// <summary>
/// Base class to manage an API resource with a single ID.
/// </summary>
/// <typeparam name="TAttributes">Resource attribute type</typeparam>
/// <typeparam name="TMeta">Resource meta type</typeparam>
/// <typeparam name="TRelationships">Resource relationships type</typeparam>
/// <typeparam name="TLinks">Resource links type</typeparam>
/// <typeparam name="TToken">Token type</typeparam>
public abstract class ResourceClient<TAttributes, TMeta, TRelationships, TLinks, TToken> :
ResourceClient<TAttributes, TMeta, TRelationships, TLinks, Guid, TToken> where TAttributes : IIdentified<Guid> where TToken : BaseToken
{
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
/// <param name="entityName">Name of the resource</param>
/// <param name="generateIdempotencyKey">Generate a random idempotency key if none was specified</param>
protected ResourceClient(IApiClient apiClient, IAccessTokenProvider<TToken> accessTokenProvider, string urlPrefix, string entityName, bool generateIdempotencyKey = true) :
base(apiClient, accessTokenProvider, urlPrefix, entityName, generateIdempotencyKey)
{ }
/// <inheritdoc />
protected override Guid ParseId(string id) => Guid.Parse(id);
}
/// <summary>
/// Base class to manage an API resource with a multiple IDs.
/// </summary>
/// <typeparam name="TAttributes">Resource attribute type</typeparam>
/// <typeparam name="TMeta">Resource meta type</typeparam>
/// <typeparam name="TRelationships">Resource relationships type</typeparam>
/// <typeparam name="TLinks">Resource links type</typeparam>
/// <typeparam name="TParentsId">Parent resources ID type</typeparam>
/// <typeparam name="TId">Resource ID type</typeparam>
/// <typeparam name="TToken">Token type</typeparam>
public abstract class ResourceWithParentClient<TAttributes, TMeta, TRelationships, TLinks, TParentsId, TId, TToken> :
BaseResourceClient<TAttributes, TMeta, TRelationships, TLinks, TId, TToken> where TAttributes : IIdentified<TId> where TToken : BaseToken
{
private readonly string[] _entityNames;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
/// <param name="entityNames">Names of the resources hierarchy</param>
/// <param name="generateIdempotencyKey">Generate a random idempotency key if none was specified</param>
protected ResourceWithParentClient(IApiClient apiClient, IAccessTokenProvider<TToken> accessTokenProvider, string urlPrefix, string[] entityNames, bool generateIdempotencyKey = true) :
base(apiClient, accessTokenProvider, urlPrefix, generateIdempotencyKey)
{
_entityNames = entityNames ?? throw new ArgumentNullException(nameof(entityNames));
if (entityNames.Any(string.IsNullOrWhiteSpace))
throw new ArgumentException("Empty entity name", nameof(entityNames));
if (entityNames.Length < 2)
throw new ArgumentException($"Too few entity names (expected at least 2 but got {entityNames.Length})", nameof(entityNames));
}
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="parentIds">IDs of parent resources</param>
/// <param name="filters">Attributes to be filtered from the results</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="pageBefore">Cursor that specifies the first resource of the next page</param>
/// <param name="pageAfter">Cursor that specifies the last resource of the previous page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected Task<IbanityCollection<TAttributes>> InternalCursorBasedList(TToken token, TParentsId[] parentIds, IEnumerable<Filter> filters, int? pageSize, Guid? pageBefore, Guid? pageAfter, CancellationToken? cancellationToken) =>
InternalCursorBasedList(token, GetPath(parentIds), filters, pageSize, pageBefore, pageAfter, cancellationToken);
/// <summary>
/// Get all resources.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="parentIds">IDs of parent resources</param>
/// <param name="filters">Attributes to be filtered from the results</param>
/// <param name="customParameters">Custom parameters</param>
/// <param name="pageOffset">Defines the start position of the results by giving the number of records to be skipped</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>First page of items</returns>
protected Task<IsabelCollection<TAttributes>> InternalOffsetBasedList(TToken token, TParentsId[] parentIds, IEnumerable<Filter> filters, IEnumerable<(string, string)> customParameters, long? pageOffset, int? pageSize, CancellationToken? cancellationToken) =>
InternalOffsetBasedList(token, GetPath(parentIds), filters, customParameters, pageOffset, pageSize, cancellationToken);
/// <summary>
/// Get a single resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="parentIds">IDs of parent resources</param>
/// <param name="id">Unique identifier of the resource</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Requested resource</returns>
protected Task<TAttributes> InternalGet(TToken token, TParentsId[] parentIds, TId id, CancellationToken? cancellationToken) =>
InternalGet(token, GetPath(parentIds), id, cancellationToken);
/// <summary>
/// Get payload and write it to a provided stream.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="parentIds">IDs of parent resources</param>
/// <param name="id">Unique identifier of the resource</param>
/// <param name="acceptHeader">Format of the response you expect from the call</param>
/// <param name="target">Destination stream where the payload will be written to</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
protected Task InternalGetToStream(TToken token, TParentsId[] parentIds, TId id, string acceptHeader, Stream target, CancellationToken? cancellationToken) =>
InternalGetToStream(token, GetPath(parentIds), id, acceptHeader, target, cancellationToken);
/// <summary>
/// Delete a single resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="parentIds">IDs of parent resources</param>
/// <param name="id">Unique identifier of the resource</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
protected Task InternalDelete(TToken token, TParentsId[] parentIds, TId id, CancellationToken? cancellationToken) =>
InternalDelete(token, GetPath(parentIds), id, cancellationToken);
/// <summary>
/// Create a new resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="parentIds">IDs of parent resources</param>
/// <param name="payload">Resource data</param>
/// <param name="idempotencyKey">Several requests with the same idempotency key will be executed only once</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The created resource</returns>
protected Task<TAttributes> InternalCreate<TRequestAttributes, TRequestMeta, TRequestRelationships, TRequestLinks>(TToken token, TParentsId[] parentIds, JsonApi.Data<TRequestAttributes, TRequestMeta, TRequestRelationships, TRequestLinks> payload, Guid? idempotencyKey, CancellationToken? cancellationToken) =>
InternalCreate(token, GetPath(parentIds), payload, idempotencyKey, cancellationToken);
/// <summary>
/// Create a new resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="parentIds">IDs of parent resources</param>
/// <param name="resource">Resource</param>
/// <param name="idempotencyKey">Several requests with the same idempotency key will be executed only once</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The created resource</returns>
protected Task<TAttributes> InternalCreate<TRequestAttributes, TRequestMeta, TRequestRelationships, TRequestLinks>(TToken token, TParentsId[] parentIds, JsonApi.Resource<TRequestAttributes, TRequestMeta, TRequestRelationships, TRequestLinks> resource, Guid? idempotencyKey, CancellationToken? cancellationToken) =>
InternalCreate(token, GetPath(parentIds), resource, idempotencyKey, cancellationToken);
/// <summary>
/// Create a new resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="parentIds">IDs of parent resources</param>
/// <param name="id">Unique identifier of the resource</param>
/// <param name="payload">Resource data</param>
/// <param name="idempotencyKey">Several requests with the same idempotency key will be executed only once</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The updated resource</returns>
protected Task<TAttributes> InternalUpdate<T>(TToken token, TParentsId[] parentIds, TId id, JsonApi.Data<T, object, object, object> payload, Guid? idempotencyKey, CancellationToken? cancellationToken) =>
InternalUpdate(token, GetPath(parentIds), id, payload, idempotencyKey, cancellationToken);
private string GetPath(TParentsId[] ids)
{
if (ids is null)
throw new ArgumentNullException(nameof(ids));
if (ids.Length != _entityNames.Length - 1)
throw new ArgumentException($"Expected {_entityNames.Length - 1} IDs but got {ids.Length}", nameof(ids));
return
UrlPrefix + "/" +
string.Join(string.Empty, _entityNames.Take(_entityNames.Length - 1).Zip(ids, (e, i) => $"{e}/{i}/")) +
_entityNames.Last();
}
}
/// <summary>
/// Base class to manage an API resource with a multiple IDs.
/// </summary>
/// <typeparam name="TAttributes">Resource attribute type</typeparam>
/// <typeparam name="TMeta">Resource meta type</typeparam>
/// <typeparam name="TRelationships">Resource relationships type</typeparam>
/// <typeparam name="TLinks">Resource links type</typeparam>
/// <typeparam name="TToken">Token type</typeparam>
public abstract class ResourceWithParentClient<TAttributes, TMeta, TRelationships, TLinks, TToken> :
ResourceWithParentClient<TAttributes, TMeta, TRelationships, TLinks, Guid, Guid, TToken> where TAttributes : IIdentified<Guid> where TToken : BaseToken
{
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
/// <param name="entityNames">Names of the resources hierarchy</param>
/// <param name="generateIdempotencyKey">Generate a random idempotency key if none was specified</param>
protected ResourceWithParentClient(IApiClient apiClient, IAccessTokenProvider<TToken> accessTokenProvider, string urlPrefix, string[] entityNames, bool generateIdempotencyKey = true) :
base(apiClient, accessTokenProvider, urlPrefix, entityNames, generateIdempotencyKey)
{ }
/// <inheritdoc />
protected override Guid ParseId(string id) => Guid.Parse(id);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\AccountingOfficeConsents.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.CodaboxConnect.Models;
namespace Ibanity.Apis.Client.Products.CodaboxConnect
{
/// <inheritdoc cref="IAccountingOfficeConsents" />
public class AccountingOfficeConsents : ResourceClient<AccountingOfficeConsentResponse, object, object, object, ClientAccessToken>, IAccountingOfficeConsents
{
private const string EntityName = "accounting-office-consents";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public AccountingOfficeConsents(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) : base(apiClient, accessTokenProvider, urlPrefix, EntityName, false)
{ }
/// <inheritdoc />
public Task<AccountingOfficeConsentResponse> Get(ClientAccessToken token, Guid id, CancellationToken? cancellationToken = null) =>
InternalGet(token, id, cancellationToken);
/// <inheritdoc />
public Task<AccountingOfficeConsentResponse> Create(ClientAccessToken token, NewAccountingOfficeConsent accountingOfficeConsent, CancellationToken? cancellationToken = null)
{
if (token is null)
throw new ArgumentNullException(nameof(token));
if (accountingOfficeConsent is null)
throw new ArgumentNullException(nameof(accountingOfficeConsent));
var payload = new JsonApi.Data<AccountingOfficeConsent, object, object, object>
{
Type = "accountingOfficeConsent",
Attributes = accountingOfficeConsent
};
return InternalCreate(token, payload, null, cancellationToken);
}
}
/// <summary>
/// This resource allows an Accounting Software to create a new Accounting Office Consent. This consent allows an Accounting Software to retrieve the documents of clients of an Accounting Office.
/// </summary>
public interface IAccountingOfficeConsents
{
/// <summary>
/// Get Accounting Office Consent
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="id">Accounting Office Consent ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a Accounting Office Consent resource.</returns>
Task<AccountingOfficeConsentResponse> Get(ClientAccessToken token, Guid id, CancellationToken? cancellationToken = null);
/// <summary>
/// Create Accounting Office Consent
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeConsent">An object representing a new Accounting Office Consent</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The created Accounting Office Consent resource</returns>
Task<AccountingOfficeConsentResponse> Create(ClientAccessToken token, NewAccountingOfficeConsent accountingOfficeConsent, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\BankAccountStatements.cs | using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.CodaboxConnect.Models;
namespace Ibanity.Apis.Client.Products.CodaboxConnect
{
/// <inheritdoc cref="IBankAccountStatements" />
public class BankAccountStatements : GuidIdentifiedDocumentsService<BankAccountStatement>, IBankAccountStatements
{
private const string EntityName = "bank-account-statements";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public BankAccountStatements(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) : base(apiClient, accessTokenProvider, urlPrefix, EntityName)
{ }
}
/// <summary>
/// This resource allows an Accounting Software to retrieve a bank account statement for a client of an accounting office.
/// </summary>
public interface IBankAccountStatements
{
/// <summary>
/// Get Bank Account Statement
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Bank account statement's owner</param>
/// <param name="id">Bank Account Statement ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a Bank Account Statement resource.</returns>
Task<BankAccountStatement> Get(ClientAccessToken token, Guid accountingOfficeId, string clientId, Guid id, CancellationToken? cancellationToken = null);
/// <summary>
/// Get Bank Account Statement PDF
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Bank account statement's owner</param>
/// <param name="id">Bank Account Statement ID</param>
/// <param name="target">Destination stream where the PDF document will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a PDF representation of the bank account statement.</returns>
Task GetPdf(ClientAccessToken token, Guid accountingOfficeId, string clientId, Guid id, Stream target, CancellationToken? cancellationToken = null);
/// <summary>
/// Get Bank Account Statement CODA file
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Bank account statement's owner</param>
/// <param name="id">Bank Account Statement ID</param>
/// <param name="target">Destination stream where the PDF document will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns the CODA file of the bank account statement.</returns>
Task GetCoda(ClientAccessToken token, Guid accountingOfficeId, string clientId, Guid id, Stream target, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\CodaboxConnectClient.cs | using Ibanity.Apis.Client.Http;
namespace Ibanity.Apis.Client.Products.CodaboxConnect
{
/// <inheritdoc cref="ICodaboxConnectClient" />
public class CodaboxConnectClient : ProductClient<ITokenProviderWithoutCodeVerifier>, ICodaboxConnectClient
{
/// <summary>
/// Product name used as prefix in Codabox Connect URIs.
/// </summary>
public const string UrlPrefix = "codabox-connect";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="tokenService">Service to generate and refresh access tokens</param>
/// <param name="clientAccessTokenService">Service to generate and refresh client access tokens.</param>
/// <param name="customerTokenService">Service to generate and refresh customer access tokens.</param>
public CodaboxConnectClient(IApiClient apiClient, ITokenProviderWithoutCodeVerifier tokenService, IClientAccessTokenProvider clientAccessTokenService, ICustomerAccessTokenProvider customerTokenService)
: base(apiClient, tokenService, clientAccessTokenService, customerTokenService)
{
AccountingOfficeConsents = new AccountingOfficeConsents(apiClient, clientAccessTokenService, UrlPrefix);
DocumentSearches = new DocumentSearches(apiClient, clientAccessTokenService, UrlPrefix);
BankAccountStatements = new BankAccountStatements(apiClient, clientAccessTokenService, UrlPrefix);
PayrollStatements = new PayrollStatements(apiClient, clientAccessTokenService, UrlPrefix);
CreditCardStatements = new CreditCardStatements(apiClient, clientAccessTokenService, UrlPrefix);
SalesInvoices = new SalesInvoices(apiClient, clientAccessTokenService, UrlPrefix);
PurchaseInvoices = new PurchaseInvoices(apiClient, clientAccessTokenService, UrlPrefix);
}
/// <inheritdoc />
public IAccountingOfficeConsents AccountingOfficeConsents { get; }
/// <inheritdoc />
public IDocumentSearches DocumentSearches { get; }
/// <inheritdoc />
public IBankAccountStatements BankAccountStatements { get; }
/// <inheritdoc />
public IPayrollStatements PayrollStatements { get; }
/// <inheritdoc />
public ICreditCardStatements CreditCardStatements { get; }
/// <inheritdoc />
public ISalesInvoices SalesInvoices { get; }
/// <inheritdoc />
public IPurchaseInvoices PurchaseInvoices { get; }
}
/// <summary>
/// Contains services for all Codabox Connect-related resources.
/// </summary>
public interface ICodaboxConnectClient : IProductClientWithClientAccessToken
{
/// <summary>
/// This resource allows an Accounting Software to create a new Accounting Office Consent. This consent allows an Accounting Software to retrieve the documents of clients of an Accounting Office.
/// </summary>
IAccountingOfficeConsents AccountingOfficeConsents { get; }
/// <summary>
/// This resource allows an Accounting Software to search for documents of clients of an Accounting Office. Documents can be searched by type, for one or multiple clients. Additionally, it is possible to filter documents within a given period of time. This resource supports pagination.
/// </summary>
IDocumentSearches DocumentSearches { get; }
/// <summary>
/// This resource allows an Accounting Software to retrieve a bank account statement for a client of an accounting office.
/// </summary>
IBankAccountStatements BankAccountStatements { get; }
/// <summary>
/// This resource allows an Accounting Software to retrieve a Payroll Statement for a client of an accounting office.
/// </summary>
IPayrollStatements PayrollStatements { get; }
/// <summary>
/// This resource allows an Accounting Software to retrieve a credit card statement for a client of an accounting office.
/// </summary>
ICreditCardStatements CreditCardStatements { get; }
/// <summary>
/// This resource allows an Accounting Software to retrieve a sales invoice or credit note document for a client of an accounting office.
/// </summary>
ISalesInvoices SalesInvoices { get; }
/// <summary>
/// This resource allows an Accounting Software to retrieve a purchase invoice or credit note document for a client of an accounting office.
/// </summary>
IPurchaseInvoices PurchaseInvoices { get; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\CreditCardStatements.cs | using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.CodaboxConnect.Models;
namespace Ibanity.Apis.Client.Products.CodaboxConnect
{
/// <inheritdoc cref="ICreditCardStatements" />
public class CreditCardStatements : DocumentsService<CreditCardStatement, string>, ICreditCardStatements
{
private const string EntityName = "credit-card-statements";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public CreditCardStatements(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) : base(apiClient, accessTokenProvider, urlPrefix, EntityName)
{ }
/// <inheritdoc />
public Task GetCaro(ClientAccessToken token, Guid accountingOfficeId, string clientId, string id, Stream target, CancellationToken? cancellationToken = null) =>
InternalGetToStream(token, new[] { accountingOfficeId.ToString(), clientId }, id, "application/vnd.caro.v1+xml", target, cancellationToken);
/// <inheritdoc />
protected override string ParseId(string id) => id;
}
/// <summary>
/// This resource allows an Accounting Software to retrieve a Payroll Statement for a client of an accounting office.
/// </summary>
public interface ICreditCardStatements
{
/// <summary>
/// Get Credit Card Statement
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Credit Card statement's owner</param>
/// <param name="id">Credit Card Statement ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a Credit Card Statement resource.</returns>
Task<CreditCardStatement> Get(ClientAccessToken token, Guid accountingOfficeId, string clientId, string id, CancellationToken? cancellationToken = null);
/// <summary>
/// Get Credit Card Statement PDF
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Credit Card statement's owner</param>
/// <param name="id">Credit Card Statement ID</param>
/// <param name="target">Destination stream where the PDF document will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a PDF representation of the Credit Card Statement.</returns>
Task GetPdf(ClientAccessToken token, Guid accountingOfficeId, string clientId, string id, Stream target, CancellationToken? cancellationToken = null);
/// <summary>
/// Get Credit Card Statement in a structured format for easier booking
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Credit Card statement's owner</param>
/// <param name="id">Credit Card Statement ID</param>
/// <param name="target">Destination stream where the PDF document will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns the Credit Card Statement in a structured format for easier booking.</returns>
Task GetCaro(ClientAccessToken token, Guid accountingOfficeId, string clientId, string id, Stream target, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\DocumentSearches.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.CodaboxConnect.Models;
namespace Ibanity.Apis.Client.Products.CodaboxConnect
{
/// <inheritdoc cref="IDocumentSearches" />
public class DocumentSearches : ResourceWithParentClient<DocumentSearchResponse, JsonApi.CollectionMeta<JsonApi.CursorBasedPaging>, DocumentSearchRelationshipsResponse, object, ClientAccessToken>, IDocumentSearches
{
private const string ParentEntityName = "accounting-offices";
private const string EntityName = "document-searches";
private readonly IApiClient _apiClient;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public DocumentSearches(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) : base(apiClient, accessTokenProvider, urlPrefix, new[] { ParentEntityName, EntityName }, false) =>
_apiClient = apiClient;
/// <inheritdoc />
public async Task<DocumentSearchResponse> Create(ClientAccessToken token, Guid accountingOfficeId, DocumentSearch documentSearch, IEnumerable<string> clients, int? pageLimit = null, Guid? pageAfter = null, CancellationToken? cancellationToken = null)
{
if (token is null)
throw new ArgumentNullException(nameof(token));
if (documentSearch is null)
throw new ArgumentNullException(nameof(documentSearch));
if (clients is null)
throw new ArgumentNullException(nameof(clients));
var payload = new JsonApi.Data<DocumentSearch, object, DocumentSearchRelationships, object>
{
Type = "documentSearch",
Attributes = documentSearch,
Relationships = new DocumentSearchRelationships
{
Clients = new JsonApi.Relationships
{
Data = clients.Select(client => new JsonApi.Data
{
Type = "client",
Id = client
}).ToArray()
}
}
};
var meta = pageLimit.HasValue || pageAfter.HasValue
? new JsonApi.CollectionMeta<JsonApi.CursorBasedPaging>
{
Paging = new JsonApi.CursorBasedPaging
{
Limit = pageLimit,
After = pageAfter
}
}
: null;
var fullResponse = await _apiClient.Post<JsonApi.Resource<DocumentSearch, object, DocumentSearchRelationships, object>, DocumentSearchFullResponse>(
UrlPrefix + "/" + ParentEntityName + "/" + accountingOfficeId + "/" + EntityName,
await GetAccessToken(token).ConfigureAwait(false),
new JsonApi.Resource<DocumentSearch, object, DocumentSearchRelationships, object> { Data = payload, Meta = meta },
null,
cancellationToken ?? CancellationToken.None).ConfigureAwait(false);
var result = Map(fullResponse.Data);
result.Documents = fullResponse.Included.Documents.Select(d =>
{
switch (d.Attributes)
{
case Document<Guid> typedDocument:
typedDocument.Type = d.Type;
typedDocument.Id = Guid.Parse(d.Id);
typedDocument.Client = d.Relationships.Client.Data.Id;
break;
case Document<string> typedDocument:
typedDocument.Type = d.Type;
typedDocument.Id = d.Id;
typedDocument.Client = d.Relationships.Client.Data.Id;
break;
default:
throw new IbanityException("Unsupported document ID: " + d.Id);
}
return d.Attributes;
}).ToArray();
return result;
}
/// <inheritdoc />
protected override DocumentSearchResponse Map(JsonApi.Data<DocumentSearchResponse, JsonApi.CollectionMeta<JsonApi.CursorBasedPaging>, DocumentSearchRelationshipsResponse, object> data)
{
var result = base.Map(data);
result.Clients = data.Relationships.Clients.Data.Select(c => c.Id).ToArray();
return result;
}
}
/// <summary>
/// This resource allows an Accounting Software to search for documents of clients of an Accounting Office. Documents can be searched by type, for one or multiple clients. Additionally, it is possible to filter documents within a given period of time. This resource supports pagination.
/// </summary>
public interface IDocumentSearches
{
/// <summary>
/// Create Document Search
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="documentSearch">An object representing a new Document Search</param>
/// <param name="clients">Resource identifiers of the clients used to search for documents. Must contain at least one resource identifier and no more than 5000.</param>
/// <param name="pageLimit">Maximum number (1-1000) of resources that might be returned. It is possible that the response contains fewer elements. Defaults to 100</param>
/// <param name="pageAfter">Cursor that specifies the last resource of the previous page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The created Accounting Office Consent resource</returns>
Task<DocumentSearchResponse> Create(ClientAccessToken token, Guid accountingOfficeId, DocumentSearch documentSearch, IEnumerable<string> clients, int? pageLimit = null, Guid? pageAfter = null, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\DocumentsService.cs | using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.JsonApi;
using Ibanity.Apis.Client.Products.CodaboxConnect.Models;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.CodaboxConnect
{
/// <summary>
/// Base class for all documents clients.
/// </summary>
/// <typeparam name="TResource">Resource type</typeparam>
/// <typeparam name="TId">Identifier type</typeparam>
public abstract class DocumentsService<TResource, TId> : ResourceWithParentClient<TResource, object, DocumentRelationships, object, string, TId, ClientAccessToken> where TResource : Document<TId>
{
private const string TopLevelParentEntityName = "accounting-offices";
private const string ParentEntityName = "clients";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
/// <param name="entityName">Last URL component</param>
public DocumentsService(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix, string entityName) : base(apiClient, accessTokenProvider, urlPrefix, new[] { TopLevelParentEntityName, ParentEntityName, entityName }, false)
{ }
/// <inheritdoc />
protected override TResource Map(Data<TResource, object, DocumentRelationships, object> data)
{
var result = base.Map(data);
result.Client = data.Relationships.Client.Data.Id;
return result;
}
/// <summary>
/// Get resource.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Resource's owner</param>
/// <param name="id">Resource ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Resource</returns>
public Task<TResource> Get(ClientAccessToken token, Guid accountingOfficeId, string clientId, TId id, CancellationToken? cancellationToken = null) =>
InternalGet(token, new[] { accountingOfficeId.ToString(), clientId }, id, cancellationToken);
/// <summary>
/// Get PDF document
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Resource's owner</param>
/// <param name="id">Resource ID</param>
/// <param name="target">Destination stream where the PDF document will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a PDF representation of the resource.</returns>
public Task GetPdf(ClientAccessToken token, Guid accountingOfficeId, string clientId, TId id, Stream target, CancellationToken? cancellationToken = null) =>
InternalGetToStream(token, new[] { accountingOfficeId.ToString(), clientId }, id, "application/pdf", target, cancellationToken);
/// <summary>
/// Get resource CODA file
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Resource's owner</param>
/// <param name="id">Resource ID</param>
/// <param name="target">Destination stream where the PDF document will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns the CODA file of the resource.</returns>
public Task GetCoda(ClientAccessToken token, Guid accountingOfficeId, string clientId, TId id, Stream target, CancellationToken? cancellationToken = null) =>
InternalGetToStream(token, new[] { accountingOfficeId.ToString(), clientId }, id, "application/vnd.coda.v1+cod", target, cancellationToken);
/// <summary>
/// Get resource metadata
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Resource's owner</param>
/// <param name="id">Resource ID</param>
/// <param name="target">Destination stream where the PDF document will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns the JSON metadata of the resource.</returns>
public Task GetJsonMetadata(ClientAccessToken token, Guid accountingOfficeId, string clientId, TId id, Stream target, CancellationToken? cancellationToken = null) =>
InternalGetToStream(token, new[] { accountingOfficeId.ToString(), clientId }, id, "application/vnd.api+json", target, cancellationToken);
/// <summary>
/// Get resource as originally received-XML
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Resource's owner</param>
/// <param name="id">Resource ID</param>
/// <param name="target">Destination stream where the PDF document will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a resource in XML format as originally received.</returns>
public Task GetXml(ClientAccessToken token, Guid accountingOfficeId, string clientId, TId id, Stream target, CancellationToken? cancellationToken = null) =>
InternalGetToStream(token, new[] { accountingOfficeId.ToString(), clientId }, id, "application/xml", target, cancellationToken);
}
/// <inheritdoc />
public abstract class GuidIdentifiedDocumentsService<TResource> : DocumentsService<TResource, Guid> where TResource : Document<Guid>
{
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
/// <param name="entityName">Last URL component</param>
protected GuidIdentifiedDocumentsService(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix, string entityName) :
base(apiClient, accessTokenProvider, urlPrefix, entityName)
{
}
/// <inheritdoc />
protected override Guid ParseId(string id) => Guid.Parse(id);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\PayrollStatements.cs | using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.CodaboxConnect.Models;
namespace Ibanity.Apis.Client.Products.CodaboxConnect
{
/// <inheritdoc cref="IPayrollStatements" />
public class PayrollStatements : GuidIdentifiedDocumentsService<PayrollStatement>, IPayrollStatements
{
private const string EntityName = "payroll-statements";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public PayrollStatements(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) : base(apiClient, accessTokenProvider, urlPrefix, EntityName)
{ }
}
/// <summary>
/// This resource allows an Accounting Software to retrieve a Payroll Statement for a client of an accounting office.
/// </summary>
public interface IPayrollStatements
{
/// <summary>
/// Get Payroll Statement
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Payroll statement's owner</param>
/// <param name="id">Payroll Statement ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a Payroll Statement resource.</returns>
Task<PayrollStatement> Get(ClientAccessToken token, Guid accountingOfficeId, string clientId, Guid id, CancellationToken? cancellationToken = null);
/// <summary>
/// Get Payroll Statement PDF
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Payroll statement's owner</param>
/// <param name="id">Payroll Statement ID</param>
/// <param name="target">Destination stream where the PDF document will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a PDF representation of the Payroll Statement.</returns>
Task GetPdf(ClientAccessToken token, Guid accountingOfficeId, string clientId, Guid id, Stream target, CancellationToken? cancellationToken = null);
/// <summary>
/// Get Payroll Statement metadata
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Payroll statement's owner</param>
/// <param name="id">Payroll Statement ID</param>
/// <param name="target">Destination stream where the PDF document will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns the JSON metadata of the Payroll Statement.</returns>
Task GetJsonMetadata(ClientAccessToken token, Guid accountingOfficeId, string clientId, Guid id, Stream target, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\PurchaseInvoices.cs | using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.CodaboxConnect.Models;
namespace Ibanity.Apis.Client.Products.CodaboxConnect
{
/// <inheritdoc cref="IPurchaseInvoices" />
public class PurchaseInvoices : GuidIdentifiedDocumentsService<PurchaseInvoice>, IPurchaseInvoices
{
private const string EntityName = "purchase-invoices";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public PurchaseInvoices(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) : base(apiClient, accessTokenProvider, urlPrefix, EntityName)
{ }
}
/// <summary>
/// This resource allows an Accounting Software to retrieve a purchase invoice or credit note document for a client of an accounting office.
/// </summary>
public interface IPurchaseInvoices
{
/// <summary>
/// Get Purchase Invoice Statement
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Purchase Invoice's owner</param>
/// <param name="id">Purchase Invoice Statement ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a Purchase Invoice Statement resource.</returns>
Task<PurchaseInvoice> Get(ClientAccessToken token, Guid accountingOfficeId, string clientId, Guid id, CancellationToken? cancellationToken = null);
/// <summary>
/// Get Purchase Invoice Statement PDF
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Purchase Invoice's owner</param>
/// <param name="id">Purchase Invoice Statement ID</param>
/// <param name="target">Destination stream where the PDF document will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a PDF representation of the Purchase Invoice Statement.</returns>
Task GetPdf(ClientAccessToken token, Guid accountingOfficeId, string clientId, Guid id, Stream target, CancellationToken? cancellationToken = null);
/// <summary>
/// Get Purchase Invoice as originally received-XML
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Purchase Invoice's owner</param>
/// <param name="id">Purchase Invoice ID</param>
/// <param name="target">Destination stream where the PDF document will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a sales invoice in XML format as originally received.</returns>
Task GetXml(ClientAccessToken token, Guid accountingOfficeId, string clientId, Guid id, Stream target, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\SalesInvoices.cs | using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.CodaboxConnect.Models;
namespace Ibanity.Apis.Client.Products.CodaboxConnect
{
/// <inheritdoc cref="ISalesInvoices" />
public class SalesInvoices : GuidIdentifiedDocumentsService<SalesInvoice>, ISalesInvoices
{
private const string EntityName = "sales-invoices";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public SalesInvoices(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) : base(apiClient, accessTokenProvider, urlPrefix, EntityName)
{ }
}
/// <summary>
/// This resource allows an Accounting Software to retrieve a sales invoice or credit note document for a client of an accounting office.
/// </summary>
public interface ISalesInvoices
{
/// <summary>
/// Get Sales Invoice Statement
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Sales invoice's owner</param>
/// <param name="id">Sales Invoice Statement ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a Sales Invoice Statement resource.</returns>
Task<SalesInvoice> Get(ClientAccessToken token, Guid accountingOfficeId, string clientId, Guid id, CancellationToken? cancellationToken = null);
/// <summary>
/// Get Sales Invoice Statement PDF
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Sales invoice's owner</param>
/// <param name="id">Sales Invoice Statement ID</param>
/// <param name="target">Destination stream where the PDF document will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a PDF representation of the Sales Invoice Statement.</returns>
Task GetPdf(ClientAccessToken token, Guid accountingOfficeId, string clientId, Guid id, Stream target, CancellationToken? cancellationToken = null);
/// <summary>
/// Get Sales Invoice as originally received-XML
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountingOfficeId">Accounting office identifier</param>
/// <param name="clientId">Sales invoice's owner</param>
/// <param name="id">Sales Invoice ID</param>
/// <param name="target">Destination stream where the PDF document will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a sales invoice in XML format as originally received.</returns>
Task GetXml(ClientAccessToken token, Guid accountingOfficeId, string clientId, Guid id, Stream target, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\Models\AccountingOfficeConsent.cs | using System;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.CodaboxConnect.Models
{
/// <summary>
/// This resource allows a Software Partner to create a new Supplier.
/// </summary>
[DataContract]
public class AccountingOfficeConsent
{
/// <summary>
/// The company number of the accounting office.
/// </summary>
/// <value>The company number of the accounting office.</value>
[DataMember(Name = "accountingOfficeCompanyNumber", EmitDefaultValue = true)]
public string AccountingOfficeCompanyNumber { get; set; }
}
/// <inheritdoc />
[DataContract]
public class NewAccountingOfficeConsent : AccountingOfficeConsent
{
/// <summary>
/// Indicates the URI that the accounting office representative will be redirected to once the consent has been confirmed (or rejected).
/// </summary>
/// <value>Indicates the URI that the accounting office representative will be redirected to once the consent has been confirmed (or rejected).</value>
[DataMember(Name = "redirectUri", EmitDefaultValue = true)]
public string RedirectUri { get; set; }
}
/// <inheritdoc />
[DataContract]
public class AccountingOfficeConsentResponse : AccountingOfficeConsent, IIdentified<Guid>
{
/// <inheritdoc />
[DataMember(Name = "id", EmitDefaultValue = false)]
public Guid Id { get; set; }
/// <summary>
/// The id of the accounting office.
/// </summary>
/// <value>The id of the accounting office.</value>
[DataMember(Name = "accountingOfficeId", EmitDefaultValue = false)]
public Guid AccountingOfficeId { get; set; }
/// <summary>
/// Indicates the URI that the accounting office representative will need to go to in order to confirm (or reject) the consent.
/// </summary>
/// <value>Indicates the URI that the accounting office representative will need to go to in order to confirm (or reject) the consent.</value>
[DataMember(Name = "confirmationUri", EmitDefaultValue = false)]
public string ConfirmationUri { get; set; }
/// <summary>
/// When this consent was requested. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec.
/// </summary>
/// <value>When this consent was requested. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec.</value>
[DataMember(Name = "requestedAt", EmitDefaultValue = false)]
public DateTimeOffset RequestedAt { get; set; }
/// <summary>
/// The status of the confirmation process of this consent, for more information see <a href='https://documentation.development.ibanity.net/codabox-connect/products#consent'>Consents</a>.<ul><li><code>unconfirmed</code> The consent was successfully created at CodaBox.</li><li><code>confirmed</code> The consent has been confirmed by the accounting office representative.</li><li><code>denied</code> The consent has been denied by the accounting office representative.</li></ul>
/// </summary>
/// <value>The status of the confirmation process of this consent, for more information see <a href='https://documentation.development.ibanity.net/codabox-connect/products#consent'>Consents</a>.<ul><li><code>unconfirmed</code> The consent was successfully created at CodaBox.</li><li><code>confirmed</code> The consent has been confirmed by the accounting office representative.</li><li><code>denied</code> The consent has been denied by the accounting office representative.</li></ul></value>
[DataMember(Name = "status", EmitDefaultValue = false)]
public string Status { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\Models\BankAccountStatement.cs | using System;
using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.Products.CodaboxConnect.Models
{
/// <summary>
/// This resource allows an Accounting Software to retrieve a bank account statement for a client of an accounting office.
/// </summary>
[DataContract]
public class BankAccountStatement : Document<Guid>
{
/// <summary>
/// When this bank account statement was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec
/// </summary>
/// <value>When this bank account statement was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec</value>
[DataMember(Name = "createdAt", EmitDefaultValue = false)]
public DateTimeOffset CreatedAt { get; set; }
/// <summary>
/// Bank account number of the bank statement.
/// </summary>
/// <value>Bank account number of the bank statement.</value>
[DataMember(Name = "iban", EmitDefaultValue = false)]
public string Iban { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\Models\CreditCardStatement.cs | using System;
using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.Products.CodaboxConnect.Models
{
/// <summary>
/// This resource allows an Accounting Software to retrieve a payroll statement for a client of an accounting office.
/// </summary>
[DataContract]
public class CreditCardStatement : Document<string>
{
/// <summary>
/// The name of the bank issuing the credit card statement.
/// </summary>
/// <value>The name of the bank issuing the credit card statement.</value>
[DataMember(Name = "bankName", EmitDefaultValue = false)]
public string BankName { get; set; }
/// <summary>
/// End of the transaction period for which the statement was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec.
/// </summary>
/// <value>End of the transaction period for which the statement was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec.</value>
[DataMember(Name = "billingPeriod", EmitDefaultValue = false)]
public DateTimeOffset BillingPeriod { get; set; }
/// <summary>
/// The reference of the credit card owner.
/// </summary>
/// <value>The reference of the credit card owner.</value>
[DataMember(Name = "clientReference", EmitDefaultValue = false)]
public string ClientReference { get; set; }
/// <summary>
/// When this credit card statement was received by CodaBox. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec.
/// </summary>
/// <value>When this credit card statement was received by CodaBox. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec.</value>
[DataMember(Name = "receivedAt", EmitDefaultValue = false)]
public DateTimeOffset ReceivedAt { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\Models\Document.cs | using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.CodaboxConnect.Models
{
/// <summary>
/// Resource identifiers of the documents returned by the search.
/// </summary>
[DataContract]
public class Document<TId> : Identified<TId>, IDocument
{
/// <inheritdoc/>
[DataMember(Name = "type", EmitDefaultValue = false)]
public string Type { get; set; }
/// <inheritdoc/>
string IDocument.Id => Id.ToString();
/// <summary>
/// Document's owner
/// </summary>
[DataMember(Name = "client", EmitDefaultValue = false)]
public string Client { get; set; }
}
/// <summary>
/// Resource identifiers of the documents returned by the search.
/// </summary>
public interface IDocument
{
/// <summary>
/// The type of the document. Valid values are: creditCardStatement, purchaseInvoice, salesInvoice, payrollStatement, bankAccountStatement.
/// </summary>
string Type { get; }
/// <summary>
/// The identifier of the document.
/// </summary>
string Id { get; }
/// <summary>
/// Document's owner
/// </summary>
string Client { get; }
}
/// <summary>
/// Link to the client that this document belongs to.
/// </summary>
[DataContract]
public class DocumentRelationships
{
/// <summary>
/// Link to the document's owner.
/// </summary>
[DataMember(Name = "client", EmitDefaultValue = false)]
public JsonApi.Relationship Client { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\Models\DocumentJsonConverter.cs | using System;
using Ibanity.Apis.Client.JsonApi;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Ibanity.Apis.Client.Products.CodaboxConnect.Models
{
/// <summary>
/// Polymorphic documents converter
/// </summary>
public class DocumentJsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType) =>
typeof(Data<IDocument, object, DocumentRelationships, object>).IsAssignableFrom(objectType);
/// <inheritdoc />
public override bool CanRead => true;
/// <inheritdoc />
public override bool CanWrite => false;
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject item = JObject.Load(reader);
var type = item["type"].Value<string>();
switch (type)
{
case "creditCardStatement": return item.ToObject<DocumentData<CreditCardStatement>>();
case "purchaseInvoice": return item.ToObject<DocumentData<PurchaseInvoice>>();
case "salesInvoice": return item.ToObject<DocumentData<SalesInvoice>>();
case "payrollStatement": return item.ToObject<DocumentData<PayrollStatement>>();
case "bankAccountStatement": return item.ToObject<DocumentData<BankAccountStatement>>();
default: return item.ToObject<Document<string>>();
}
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) =>
throw new NotImplementedException();
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\Models\DocumentSearch.cs | using System;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
using Newtonsoft.Json;
namespace Ibanity.Apis.Client.Products.CodaboxConnect.Models
{
/// <summary>
/// This resource allows an Accounting Software to search for documents of clients of an Accounting Office. Documents can be searched by type, for one or multiple clients. Additionally, it is possible to filter documents within a given period of time. This resource supports pagination.
/// </summary>
[DataContract]
public class DocumentSearch
{
/// <summary>
/// The type of the documents to search. Valid values are: <code>creditCardStatement, purchaseInvoice, salesInvoice, payrollStatement, bankAccountStatement</code>.
/// </summary>
/// <value>The type of the documents to search. Valid values are: <code>creditCardStatement, purchaseInvoice, salesInvoice, payrollStatement, bankAccountStatement</code>.</value>
[DataMember(Name = "documentType", EmitDefaultValue = true)]
public string DocumentType { get; set; }
/// <summary>
/// <i>(Optional)</i> Start of the document period scope, a date-time in the <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> format with offset and zone. If not specified, all documents from the past will be returned (up to 2 years max). It is advised to fill this based on the 'to' date used in the previous call. For more information refer to the <a href='products#accounting-documents'>documents</a> workflow.
/// </summary>
/// <value><i>(Optional)</i> Start of the document period scope, a date-time in the <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> format with offset and zone. If not specified, all documents from the past will be returned (up to 2 years max). It is advised to fill this based on the 'to' date used in the previous call. For more information refer to the <a href='products#accounting-documents'>documents</a> workflow.</value>
[DataMember(Name = "from", EmitDefaultValue = true)]
public DateTimeOffset? From { get; set; }
/// <summary>
/// <i>(Optional)</i> End of the document period scope, a date-time in the <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> format with offset and zone. Must be equal to or later than from. If not specified, the current date is used.
/// </summary>
/// <value><i>(Optional)</i> End of the document period scope, a date-time in the <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> format with offset and zone. Must be equal to or later than from. If not specified, the current date is used.</value>
[DataMember(Name = "to", EmitDefaultValue = true)]
public DateTimeOffset? To { get; set; }
}
/// <inheritdoc />
[DataContract]
public class DocumentSearchResponse : DocumentSearch, IIdentified<Guid>
{
/// <inheritdoc />
[DataMember(Name = "id", EmitDefaultValue = false)]
public Guid Id { get; set; }
/// <summary>
/// Resource identifiers of the clients used to search for documents. Must contain at least one resource identifier and no more than 5000.
/// </summary>
public string[] Clients { get; set; }
/// <summary>
/// Resource identifiers of the documents returned by the search.
/// </summary>
public IDocument[] Documents { get; set; }
}
/// <summary>
/// Links to the clients and documents.
/// </summary>
[DataContract]
public class DocumentSearchRelationships
{
/// <summary>
/// Resource identifiers of the clients used to search for documents. Must contain at least one resource identifier and no more than 5000.
/// </summary>
[DataMember(Name = "clients", EmitDefaultValue = false)]
public JsonApi.Relationships Clients { get; set; }
}
/// <inheritdoc />
[DataContract]
public class DocumentSearchRelationshipsResponse : DocumentSearchRelationships
{
/// <summary>
/// Resource identifiers of the documents returned by the search.
/// </summary>
[DataMember(Name = "documents", EmitDefaultValue = false)]
public JsonApi.Relationships Documents { get; set; }
}
/// <summary>
/// Included resources.
/// </summary>
[DataContract]
public class DocumentSearchIncluded
{
/// <summary>
/// Resource identifiers of the documents returned by the search.
/// </summary>
[DataMember(Name = "documents", EmitDefaultValue = false)]
[JsonProperty(ItemConverterType = typeof(DocumentJsonConverter))]
public JsonApi.Data<IDocument, object, DocumentRelationships, object>[] Documents { get; set; }
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
public class DocumentData<T> : JsonApi.Data<IDocument, object, DocumentRelationships, object> where T : IDocument
{
/// <summary>
/// Resource actual content.
/// </summary>
[DataMember(Name = "attributes", EmitDefaultValue = false)]
public T TypedAttributes
{
get => (T)Attributes;
set => Attributes = value;
}
}
/// <summary>
/// Full document search resource.
/// </summary>
public class DocumentSearchFullResponse : JsonApi.Resource<DocumentSearchResponse, JsonApi.CollectionMeta<JsonApi.CursorBasedPaging>, DocumentSearchRelationshipsResponse, object>
{
/// <summary>
/// Resource identifiers of the documents returned by the search.
/// </summary>
[DataMember(Name = "included", EmitDefaultValue = false)]
public DocumentSearchIncluded Included { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\Models\PayrollStatement.cs | using System;
using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.Products.CodaboxConnect.Models
{
/// <summary>
/// This resource allows an Accounting Software to retrieve a payroll statement for a client of an accounting office.
/// </summary>
[DataContract]
public class PayrollStatement : Document<Guid>
{
/// <summary>
/// When this payroll statement was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec
/// </summary>
/// <value>When this payroll statement was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec</value>
[DataMember(Name = "createdAt", EmitDefaultValue = false)]
public DateTimeOffset CreatedAt { get; set; }
/// <summary>
/// Id of social office that issued the payroll statement
/// </summary>
/// <value>Id of social office that issued the payroll statement</value>
[DataMember(Name = "socialOfficeId", EmitDefaultValue = false)]
public string SocialOfficeId { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\Models\PurchaseInvoice.cs | using System;
using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.Products.CodaboxConnect.Models
{
/// <summary>
/// This resource allows an Accounting Software to retrieve a purchase invoice or credit note document for a client of an accounting office.
/// </summary>
[DataContract]
public class PurchaseInvoice : Document<Guid>
{
/// <summary>
/// Format of the response you expect from the call. If present, it must be one of the following: <ul><li><code>application/vnd.api+json</code> a purchase invoice resource.</li><li><code>application/pdf</code> a purchase invoice in its original format.</li><li><code>application/xml</code> a purchase invoice in a structured format for easier booking.</li></ul>Defaults to <code>application/vnd.api+json</code>.
/// </summary>
/// <value>Format of the response you expect from the call. If present, it must be one of the following: <ul><li><code>application/vnd.api+json</code> a purchase invoice resource.</li><li><code>application/pdf</code> a purchase invoice in its original format.</li><li><code>application/xml</code> a purchase invoice in a structured format for easier booking.</li></ul>Defaults to <code>application/vnd.api+json</code>.</value>
[DataMember(Name = "availableContentTypes", EmitDefaultValue = false)]
public string[] AvailableContentTypes { get; set; }
/// <summary>
/// When this purchase invoice was received by CodaBox. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec.
/// </summary>
/// <value>When this purchase invoice was received by CodaBox. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec.</value>
[DataMember(Name = "receivedAt", EmitDefaultValue = false)]
public DateTimeOffset ReceivedAt { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect | raw_data\ibanity-dotnet\src\Client\Products\CodaboxConnect\Models\SalesInvoice.cs | using System;
using System.Runtime.Serialization;
namespace Ibanity.Apis.Client.Products.CodaboxConnect.Models
{
/// <summary>
/// This resource allows an Accounting Software to retrieve a payroll statement for a client of an accounting office.
/// </summary>
[DataContract]
public class SalesInvoice : Document<Guid>
{
/// <summary>
/// When this sales invoice was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec
/// </summary>
/// <value>When this sales invoice was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec</value>
[DataMember(Name = "createdAt", EmitDefaultValue = false)]
public DateTimeOffset CreatedAt { get; set; }
/// <summary>
/// Id of the invoicing software of the sales invoice
/// </summary>
/// <value>Id of the invoicing software of the sales invoice</value>
[DataMember(Name = "invoicingSoftware", EmitDefaultValue = false)]
public string InvoicingSoftware { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\EInvoicingClient.cs | using Ibanity.Apis.Client.Http;
namespace Ibanity.Apis.Client.Products.eInvoicing
{
/// <inheritdoc cref="IEInvoicingClient" />
public class EInvoicingClient : ProductClient<ITokenProviderWithoutCodeVerifier>, IEInvoicingClient
{
/// <summary>
/// Product name used as prefix in eInvoicing URIs.
/// </summary>
public const string UrlPrefix = "einvoicing";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="tokenService">Service to generate and refresh access tokens</param>
/// <param name="clientAccessTokenService">Service to generate and refresh client access tokens.</param>
/// <param name="customerTokenService">Service to generate and refresh customer access tokens.</param>
public EInvoicingClient(IApiClient apiClient, ITokenProviderWithoutCodeVerifier tokenService, IClientAccessTokenProvider clientAccessTokenService, ICustomerAccessTokenProvider customerTokenService)
: base(apiClient, tokenService, clientAccessTokenService, customerTokenService)
{
Suppliers = new Suppliers(apiClient, clientAccessTokenService, UrlPrefix);
PeppolCustomerSearches = new PeppolCustomerSearches(apiClient, clientAccessTokenService, UrlPrefix);
PeppolInvoices = new PeppolInvoices(apiClient, clientAccessTokenService, UrlPrefix);
PeppolCreditNotes = new PeppolCreditNotes(apiClient, clientAccessTokenService, UrlPrefix);
PeppolDocuments = new PeppolDocuments(apiClient, clientAccessTokenService, UrlPrefix);
ZoomitCustomerSearches = new ZoomitCustomerSearches(apiClient, clientAccessTokenService, UrlPrefix);
ZoomitInvoices = new ZoomitInvoices(apiClient, clientAccessTokenService, UrlPrefix);
ZoomitCreditNotes = new ZoomitCreditNotes(apiClient, clientAccessTokenService, UrlPrefix);
ZoomitDocuments = new ZoomitDocuments(apiClient, clientAccessTokenService, UrlPrefix);
}
/// <inheritdoc />
public ISuppliers Suppliers { get; }
/// <inheritdoc />
public IPeppolCustomerSearches PeppolCustomerSearches { get; }
/// <inheritdoc />
public IPeppolInvoices PeppolInvoices { get; }
/// <inheritdoc />
public IPeppolCreditNotes PeppolCreditNotes { get; }
/// <inheritdoc />
public IPeppolDocuments PeppolDocuments { get; }
/// <inheritdoc />
public IZoomitCustomerSearches ZoomitCustomerSearches { get; }
/// <inheritdoc />
public IZoomitInvoices ZoomitInvoices { get; }
/// <inheritdoc />
public IZoomitCreditNotes ZoomitCreditNotes { get; }
/// <inheritdoc />
public IZoomitDocuments ZoomitDocuments { get; }
}
/// <summary>
/// Contains services for all eInvoicing-related resources.
/// </summary>
public interface IEInvoicingClient : IProductClientWithClientAccessToken
{
/// <summary>
/// This resource allows a Software Partner to create a new Supplier.
/// </summary>
ISuppliers Suppliers { get; }
/// <summary>
/// <p>This endpoint allows you to search for a customer on the PEPPOL network and the document types it supports. Based on the response you know:</p>
/// <p>- whether the customer is available on Peppol and is capable to receive documents over Peppol</p>
/// <p>- which UBL document types the customer is capable to receive</p>
/// <p>A list of test receivers can be found in <see href="https://documentation.ibanity.com/einvoicing/products#development-resources">Development Resources</see></p>
/// </summary>
IPeppolCustomerSearches PeppolCustomerSearches { get; }
/// <summary>
/// <p>This is an object representing the invoice that can be sent by a supplier. This document is always an UBL in a format supported by CodaBox.</p>
/// <p>The maximum file size is 100MB.</p>
/// </summary>
IPeppolInvoices PeppolInvoices { get; }
/// <summary>
/// <p>This is an object representing the credit note that can be sent by a supplier. This document is always an UBL in a format supported by CodaBox.</p>
/// <p>The maximum file size is 100MB.</p>
/// </summary>
IPeppolCreditNotes PeppolCreditNotes { get; }
/// <summary>
/// Peppol document
/// </summary>
IPeppolDocuments PeppolDocuments { get; }
/// <summary>
/// <p>This endpoint allows you to search for a customer on the Zoomit network. Based on the response you know whether the customer is reachable on Zoomit or not.</p>
/// <p>A list of test receivers can be found in <see href="https://documentation.ibanity.com/einvoicing/products#development-resources">Development Resources</see></p>
/// </summary>
IZoomitCustomerSearches ZoomitCustomerSearches { get; }
/// <summary>
/// <p>This is an object representing the invoice that can be sent by a supplier. This document is always an UBL in BIS 3 format with additional validations.</p>
/// <p>CodaBox expects the following format for Zoomit invoices: <see href="http://docs.peppol.eu/poacc/billing/3.0/">Peppol BIS 3.0</see></p>
/// <p>CodaBox will verify the compliance of the UBL with XSD and schematron rules (you can find the CodaBox schematron rules <see href="https://documentation.ibanity.com/einvoicing/ZOOMIT-EN16931-UBL.sch">here</see>)</p>
/// <p>In order to send an invoice to Zoomit, some additional fields are required</p>
/// </summary>
IZoomitInvoices ZoomitInvoices { get; }
/// <summary>
/// <p>This is an object representing the credit note that can be sent by a supplier. This document is always an UBL in BIS 3 format with additional validations.</p>
/// <p>CodaBox expects the following format for Zoomit credit notes: <see href="http://docs.peppol.eu/poacc/billing/3.0/">Peppol BIS 3.0</see></p>
/// <p>CodaBox will verify the compliance of the UBL with XSD and schematron rules (you can find the CodaBox schematron rules <see href="https://documentation.ibanity.com/einvoicing/ZOOMIT-EN16931-UBL.sch">here</see>)</p>
/// <p>In order to send a credit note to Zoomit, some additional fields are required</p>
/// </summary>
IZoomitCreditNotes ZoomitCreditNotes { get; }
/// <summary>
/// Zoomit document
/// </summary>
IZoomitDocuments ZoomitDocuments { get; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\PeppolCreditNotes.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.eInvoicing.Models;
namespace Ibanity.Apis.Client.Products.eInvoicing
{
/// <inheritdoc cref="IPeppolCreditNotes" />
public class PeppolCreditNotes : ResourceWithParentClient<PeppolCreditNote, object, object, object, ClientAccessToken>, IPeppolCreditNotes
{
private const string ParentEntityName = "peppol/suppliers";
private const string EntityName = "credit-notes";
private readonly IApiClient _apiClient;
private readonly IAccessTokenProvider<ClientAccessToken> _accessTokenProvider;
private readonly string _urlPrefix;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public PeppolCreditNotes(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, new[] { ParentEntityName, EntityName })
{
_apiClient = apiClient;
_accessTokenProvider = accessTokenProvider;
_urlPrefix = urlPrefix;
}
/// <inheritdoc />
public Task<PeppolCreditNote> Get(ClientAccessToken token, Guid supplierId, Guid id, CancellationToken? cancellationToken = null) =>
InternalGet(token, new[] { supplierId }, id, cancellationToken);
/// <inheritdoc />
public async Task<PeppolCreditNote> Create(ClientAccessToken token, Guid supplierId, string filename, string path, CancellationToken? cancellationToken = null)
{
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
return await Create(token, supplierId, filename, stream, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<PeppolCreditNote> Create(ClientAccessToken token, Guid supplierId, string filename, Stream xmlContent, CancellationToken? cancellationToken = null)
{
var result = await _apiClient.PostInline<JsonApi.Resource<PeppolCreditNote, object, object, object>>(
$"{_urlPrefix}/{ParentEntityName}/{supplierId}/{EntityName}",
(await _accessTokenProvider.RefreshToken(token ?? throw new ArgumentNullException(nameof(token))).ConfigureAwait(false)).AccessToken,
new Dictionary<string, string>(),
filename,
xmlContent,
"application/xml",
cancellationToken ?? CancellationToken.None).ConfigureAwait(false);
return Map(result.Data);
}
}
/// <summary>
/// <p>This is an object representing the credit note that can be sent by a supplier. This document is always an UBL in a format supported by CodaBox.</p>
/// <p>The maximum file size is 100MB.</p>
/// </summary>
public interface IPeppolCreditNotes
{
/// <summary>
/// Get Peppol Credit Note
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="supplierId">Supplier ID</param>
/// <param name="id">Credit Note ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The specified Peppol Credit Note resource</returns>
Task<PeppolCreditNote> Get(ClientAccessToken token, Guid supplierId, Guid id, CancellationToken? cancellationToken = null);
/// <summary>
/// Create Peppol Credit Note
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="supplierId">Supplier ID</param>
/// <param name="filename">Your filename</param>
/// <param name="path">Local path the the XML file to upload</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a Peppol Credit Note resource</returns>
Task<PeppolCreditNote> Create(ClientAccessToken token, Guid supplierId, string filename, string path, CancellationToken? cancellationToken = null);
/// <summary>
/// Create Peppol Credit Note
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="supplierId">Supplier ID</param>
/// <param name="filename">Your filename</param>
/// <param name="xmlContent">XML content to upload</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a Peppol Credit Note resource</returns>
Task<PeppolCreditNote> Create(ClientAccessToken token, Guid supplierId, string filename, Stream xmlContent, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\PeppolCustomerSearches.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.eInvoicing.Models;
namespace Ibanity.Apis.Client.Products.eInvoicing
{
/// <inheritdoc cref="IPeppolCustomerSearches" />
public class PeppolCustomerSearches : ResourceClient<PeppolCustomerSearchResponse, object, object, object, ClientAccessToken>, IPeppolCustomerSearches
{
private const string EntityName = "peppol/customer-searches";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public PeppolCustomerSearches(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) : base(apiClient, accessTokenProvider, urlPrefix, EntityName, false)
{ }
/// <inheritdoc />
public Task<PeppolCustomerSearchResponse> Create(ClientAccessToken token, PeppolCustomerSearch peppolCustomerSearch, CancellationToken? cancellationToken = null)
{
if (token is null)
throw new ArgumentNullException(nameof(token));
if (peppolCustomerSearch is null)
throw new ArgumentNullException(nameof(peppolCustomerSearch));
var payload = new JsonApi.Data<PeppolCustomerSearch, object, object, object>
{
Type = "peppolCustomerSearch",
Attributes = peppolCustomerSearch
};
return InternalCreate(token, payload, null, cancellationToken);
}
}
/// <summary>
/// <p>This endpoint allows you to search for a customer on the PEPPOL network and the document types it supports. Based on the response you know:</p>
/// <p>- whether the customer is available on Peppol and is capable to receive documents over Peppol</p>
/// <p>- which UBL document types the customer is capable to receive</p>
/// <p>A list of test receivers can be found in <see href="https://documentation.ibanity.com/einvoicing/products#development-resources">Development Resources</see></p>
/// </summary>
public interface IPeppolCustomerSearches
{
/// <summary>
/// Create Supplier
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="peppolCustomerSearch">An object representing a new Peppol Customer search</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The created supplier resource</returns>
Task<PeppolCustomerSearchResponse> Create(ClientAccessToken token, PeppolCustomerSearch peppolCustomerSearch, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\PeppolDocuments.cs | using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.eInvoicing.Models;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.eInvoicing
{
/// <inheritdoc cref="IPeppolDocuments" />
public class PeppolDocuments : ResourceClient<PeppolDocument, object, object, object, ClientAccessToken>, IPeppolDocuments
{
private const string EntityName = "peppol/documents";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public PeppolDocuments(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, EntityName)
{ }
/// <inheritdoc />
public Task<EInvoicingCollection<PeppolDocument>> List(ClientAccessToken token, DateTimeOffset? fromStatusChanged, DateTimeOffset? toStatusChanged, long? pageNumber = null, int? pageSize = null, CancellationToken? cancellationToken = null)
{
var parameters = new List<(string, string)>();
if (fromStatusChanged.HasValue)
parameters.Add(("fromStatusChanged", fromStatusChanged.Value.ToString("o")));
if (toStatusChanged.HasValue)
parameters.Add(("toStatusChanged", toStatusChanged.Value.ToString("o")));
return InternalPageBasedList(token, null, parameters, pageNumber, pageSize, cancellationToken);
}
}
/// <summary>
/// Peppol document
/// </summary>
public interface IPeppolDocuments
{
/// <summary>
/// List Accounts
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="fromStatusChanged">Start of the document status change period scope. Must be within 7 days of the toStatusChanged date-time.</param>
/// <param name="toStatusChanged">End of the document status change period scope. Must be equal to or later than fromStatusChanged. Defaults to the current date-time.</param>
/// <param name="pageNumber">Number of page that should be returned. Must be included to use page-based pagination.</param>
/// <param name="pageSize">Number (1-2000) of document resources that you want to be returned. Defaults to 2000.</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A list of Peppol Document resources</returns>
Task<EInvoicingCollection<PeppolDocument>> List(ClientAccessToken token, DateTimeOffset? fromStatusChanged, DateTimeOffset? toStatusChanged, long? pageNumber = null, int? pageSize = null, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\PeppolInvoices.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.eInvoicing.Models;
namespace Ibanity.Apis.Client.Products.eInvoicing
{
/// <inheritdoc cref="IPeppolInvoices" />
public class PeppolInvoices : ResourceWithParentClient<PeppolInvoice, object, object, object, ClientAccessToken>, IPeppolInvoices
{
private const string ParentEntityName = "peppol/suppliers";
private const string EntityName = "invoices";
private readonly IApiClient _apiClient;
private readonly IAccessTokenProvider<ClientAccessToken> _accessTokenProvider;
private readonly string _urlPrefix;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public PeppolInvoices(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, new[] { ParentEntityName, EntityName })
{
_apiClient = apiClient;
_accessTokenProvider = accessTokenProvider;
_urlPrefix = urlPrefix;
}
/// <inheritdoc />
public Task<PeppolInvoice> Get(ClientAccessToken token, Guid supplierId, Guid id, CancellationToken? cancellationToken = null) =>
InternalGet(token, new[] { supplierId }, id, cancellationToken);
/// <inheritdoc />
public async Task<PeppolInvoice> Create(ClientAccessToken token, Guid supplierId, string filename, string path, CancellationToken? cancellationToken = null)
{
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
return await Create(token, supplierId, filename, stream, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<PeppolInvoice> Create(ClientAccessToken token, Guid supplierId, string filename, Stream xmlContent, CancellationToken? cancellationToken = null)
{
var result = await _apiClient.PostInline<JsonApi.Resource<PeppolInvoice, object, object, object>>(
$"{_urlPrefix}/{ParentEntityName}/{supplierId}/{EntityName}",
(await _accessTokenProvider.RefreshToken(token ?? throw new ArgumentNullException(nameof(token))).ConfigureAwait(false)).AccessToken,
new Dictionary<string, string>(),
filename,
xmlContent,
"application/xml",
cancellationToken ?? CancellationToken.None).ConfigureAwait(false);
return Map(result.Data);
}
}
/// <summary>
/// <p>This is an object representing the invoice that can be sent by a supplier. This document is always an UBL in a format supported by CodaBox.</p>
/// <p>The maximum file size is 100MB.</p>
/// </summary>
public interface IPeppolInvoices
{
/// <summary>
/// Get Peppol Invoice
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="supplierId">Supplier ID</param>
/// <param name="id">Invoice ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The specified invoice resource</returns>
Task<PeppolInvoice> Get(ClientAccessToken token, Guid supplierId, Guid id, CancellationToken? cancellationToken = null);
/// <summary>
/// Create Peppol Invoice
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="supplierId">Supplier ID</param>
/// <param name="filename">Your filename</param>
/// <param name="path">Local path the the XML file to upload</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a Peppol Invoice resource</returns>
Task<PeppolInvoice> Create(ClientAccessToken token, Guid supplierId, string filename, string path, CancellationToken? cancellationToken = null);
/// <summary>
/// Create Peppol Invoice
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="supplierId">Supplier ID</param>
/// <param name="filename">Your filename</param>
/// <param name="xmlContent">XML content to upload</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a Peppol Invoice resource</returns>
Task<PeppolInvoice> Create(ClientAccessToken token, Guid supplierId, string filename, Stream xmlContent, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\Suppliers.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.eInvoicing.Models;
namespace Ibanity.Apis.Client.Products.eInvoicing
{
/// <inheritdoc cref="ISuppliers" />
public class Suppliers : ResourceClient<SupplierResponse, object, object, object, ClientAccessToken>, ISuppliers
{
private const string EntityName = "suppliers";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public Suppliers(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) : base(apiClient, accessTokenProvider, urlPrefix, EntityName, false)
{ }
/// <inheritdoc />
public Task<SupplierResponse> Get(ClientAccessToken token, Guid id, CancellationToken? cancellationToken = null) =>
InternalGet(token, id, cancellationToken);
/// <inheritdoc />
public Task<SupplierResponse> Create(ClientAccessToken token, NewSupplier supplier, CancellationToken? cancellationToken = null)
{
if (token is null)
throw new ArgumentNullException(nameof(token));
if (supplier is null)
throw new ArgumentNullException(nameof(supplier));
var payload = new JsonApi.Data<NewSupplier, object, object, object>
{
Type = "supplier",
Attributes = supplier
};
return InternalCreate(token, payload, null, cancellationToken);
}
/// <inheritdoc />
public Task<SupplierResponse> Update(ClientAccessToken token, Guid id, Supplier supplier, CancellationToken? cancellationToken = null)
{
if (token is null)
throw new ArgumentNullException(nameof(token));
if (supplier is null)
throw new ArgumentNullException(nameof(supplier));
var payload = new JsonApi.Data<Supplier, object, object, object>
{
Id = id.ToString(),
Type = "supplier",
Attributes = supplier
};
return InternalUpdate(token, id, payload, null, cancellationToken);
}
/// <inheritdoc />
public Task Delete(ClientAccessToken token, Guid id, CancellationToken? cancellationToken = null) =>
InternalDelete(token, id, cancellationToken);
}
/// <summary>
/// This resource allows a Software Partner to create a new Supplier.
/// </summary>
public interface ISuppliers
{
/// <summary>
/// Get Supplier
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="id">Supplier ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a supplier resource.</returns>
Task<SupplierResponse> Get(ClientAccessToken token, Guid id, CancellationToken? cancellationToken = null);
/// <summary>
/// Create Supplier
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="supplier">An object representing a new supplier</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The created supplier resource</returns>
Task<SupplierResponse> Create(ClientAccessToken token, NewSupplier supplier, CancellationToken? cancellationToken = null);
/// <summary>
/// Update Supplier
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="id">Financial institution transaction ID</param>
/// <param name="supplier">An object representing a supplier</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The updated supplier resource</returns>
Task<SupplierResponse> Update(ClientAccessToken token, Guid id, Supplier supplier, CancellationToken? cancellationToken = null);
/// <summary>
/// Delete Supplier
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="id">Supplier ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
Task Delete(ClientAccessToken token, Guid id, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\ZoomitCreditNotes.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.eInvoicing.Models;
namespace Ibanity.Apis.Client.Products.eInvoicing
{
/// <inheritdoc cref="IZoomitCreditNotes" />
public class ZoomitCreditNotes : ResourceWithParentClient<ZoomitCreditNote, object, object, object, ClientAccessToken>, IZoomitCreditNotes
{
private const string ParentEntityName = "zoomit/suppliers";
private const string EntityName = "credit-notes";
private readonly IApiClient _apiClient;
private readonly IAccessTokenProvider<ClientAccessToken> _accessTokenProvider;
private readonly string _urlPrefix;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public ZoomitCreditNotes(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, new[] { ParentEntityName, EntityName })
{
_apiClient = apiClient;
_accessTokenProvider = accessTokenProvider;
_urlPrefix = urlPrefix;
}
/// <inheritdoc />
public Task<ZoomitCreditNote> Get(ClientAccessToken token, Guid supplierId, Guid id, CancellationToken? cancellationToken = null) =>
InternalGet(token, new[] { supplierId }, id, cancellationToken);
/// <inheritdoc />
public async Task<ZoomitCreditNote> Create(ClientAccessToken token, Guid supplierId, string filename, string path, CancellationToken? cancellationToken = null)
{
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
return await Create(token, supplierId, filename, stream, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<ZoomitCreditNote> Create(ClientAccessToken token, Guid supplierId, string filename, Stream xmlContent, CancellationToken? cancellationToken = null)
{
var result = await _apiClient.PostInline<JsonApi.Resource<ZoomitCreditNote, object, object, object>>(
$"{_urlPrefix}/{ParentEntityName}/{supplierId}/{EntityName}",
(await _accessTokenProvider.RefreshToken(token ?? throw new ArgumentNullException(nameof(token))).ConfigureAwait(false)).AccessToken,
new Dictionary<string, string>(),
filename,
xmlContent,
"application/xml",
cancellationToken ?? CancellationToken.None).ConfigureAwait(false);
return Map(result.Data);
}
}
/// <summary>
/// <p>This is an object representing the credit note that can be sent by a supplier. This document is always an UBL in BIS 3 format with additional validations.</p>
/// <p>CodaBox expects the following format for Zoomit credit notes: <see href="http://docs.peppol.eu/poacc/billing/3.0/">Peppol BIS 3.0</see></p>
/// <p>CodaBox will verify the compliance of the UBL with XSD and schematron rules (you can find the CodaBox schematron rules <see href="https://documentation.ibanity.com/einvoicing/ZOOMIT-EN16931-UBL.sch">here</see>)</p>
/// <p>In order to send a credit note to Zoomit, some additional fields are required</p>
/// </summary>
public interface IZoomitCreditNotes
{
/// <summary>
/// Get Zoomit Credit Note
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="supplierId">Supplier ID</param>
/// <param name="id">Credit Note ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The specified Zoomit Credit Note resource</returns>
Task<ZoomitCreditNote> Get(ClientAccessToken token, Guid supplierId, Guid id, CancellationToken? cancellationToken = null);
/// <summary>
/// Create Zoomit Credit Note
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="supplierId">Supplier ID</param>
/// <param name="filename">Your filename</param>
/// <param name="path">Local path the the XML file to upload</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a Zoomit Credit Note resource</returns>
Task<ZoomitCreditNote> Create(ClientAccessToken token, Guid supplierId, string filename, string path, CancellationToken? cancellationToken = null);
/// <summary>
/// Create Zoomit Credit Note
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="supplierId">Supplier ID</param>
/// <param name="filename">Your filename</param>
/// <param name="xmlContent">XML content to upload</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a Zoomit Credit Note resource</returns>
Task<ZoomitCreditNote> Create(ClientAccessToken token, Guid supplierId, string filename, Stream xmlContent, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\ZoomitCustomerSearches.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.eInvoicing.Models;
namespace Ibanity.Apis.Client.Products.eInvoicing
{
/// <inheritdoc cref="IZoomitCustomerSearches" />
public class ZoomitCustomerSearches : ResourceWithParentClient<ZoomitCustomerSearchResponse, object, object, object, ClientAccessToken>, IZoomitCustomerSearches
{
private const string ParentEntityName = "zoomit/suppliers";
private const string EntityName = "customer-searches";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public ZoomitCustomerSearches(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, new[] { ParentEntityName, EntityName }, false)
{ }
/// <inheritdoc />
public Task<ZoomitCustomerSearchResponse> Create(ClientAccessToken token, Guid supplierId, ZoomitCustomerSearch zoomitCustomerSearch, CancellationToken? cancellationToken = null)
{
if (token is null)
throw new ArgumentNullException(nameof(token));
if (zoomitCustomerSearch is null)
throw new ArgumentNullException(nameof(zoomitCustomerSearch));
var payload = new JsonApi.Data<ZoomitCustomerSearch, object, object, object>
{
Type = "zoomitCustomerSearch",
Attributes = zoomitCustomerSearch
};
return InternalCreate(token, new[] { supplierId }, payload, null, cancellationToken);
}
}
/// <summary>
/// <p>This endpoint allows you to search for a customer on the Zoomit network. Based on the response you know whether the customer is reachable on Zoomit or not.</p>
/// <p>A list of test receivers can be found in <see href="https://documentation.ibanity.com/einvoicing/products#development-resources">Development Resources</see></p>
/// </summary>
public interface IZoomitCustomerSearches
{
/// <summary>
/// Create Supplier
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="supplierId">Supplier ID</param>
/// <param name="zoomitCustomerSearch">An object representing a new Zoomit Customer search</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The created supplier resource</returns>
Task<ZoomitCustomerSearchResponse> Create(ClientAccessToken token, Guid supplierId, ZoomitCustomerSearch zoomitCustomerSearch, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\ZoomitDocuments.cs | using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.eInvoicing.Models;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.eInvoicing
{
/// <inheritdoc cref="IZoomitDocuments" />
public class ZoomitDocuments : ResourceClient<ZoomitDocument, object, object, object, ClientAccessToken>, IZoomitDocuments
{
private const string EntityName = "zoomit/documents";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public ZoomitDocuments(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, EntityName)
{ }
/// <inheritdoc />
public Task<EInvoicingCollection<ZoomitDocument>> List(ClientAccessToken token, DateTimeOffset? fromStatusChanged, DateTimeOffset? toStatusChanged, long? pageNumber = null, int? pageSize = null, CancellationToken? cancellationToken = null)
{
var parameters = new List<(string, string)>();
if (fromStatusChanged.HasValue)
parameters.Add(("fromStatusChanged", fromStatusChanged.Value.ToString("o")));
if (toStatusChanged.HasValue)
parameters.Add(("toStatusChanged", toStatusChanged.Value.ToString("o")));
return InternalPageBasedList(token, null, parameters, pageNumber, pageSize, cancellationToken);
}
}
/// <summary>
/// Zoomit document
/// </summary>
public interface IZoomitDocuments
{
/// <summary>
/// List Accounts
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="fromStatusChanged">Start of the document status change period scope. Must be within 7 days of the toStatusChanged date-time.</param>
/// <param name="toStatusChanged">End of the document status change period scope. Must be equal to or later than fromStatusChanged. Defaults to the current date-time.</param>
/// <param name="pageNumber">Number of page that should be returned. Must be included to use page-based pagination.</param>
/// <param name="pageSize">Number (1-2000) of document resources that you want to be returned. Defaults to 2000.</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A list of Zoomit Document resources</returns>
Task<EInvoicingCollection<ZoomitDocument>> List(ClientAccessToken token, DateTimeOffset? fromStatusChanged, DateTimeOffset? toStatusChanged, long? pageNumber = null, int? pageSize = null, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\ZoomitInvoices.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.eInvoicing.Models;
namespace Ibanity.Apis.Client.Products.eInvoicing
{
/// <inheritdoc cref="IZoomitInvoices" />
public class ZoomitInvoices : ResourceWithParentClient<ZoomitInvoice, object, object, object, ClientAccessToken>, IZoomitInvoices
{
private const string ParentEntityName = "zoomit/suppliers";
private const string EntityName = "invoices";
private readonly IApiClient _apiClient;
private readonly IAccessTokenProvider<ClientAccessToken> _accessTokenProvider;
private readonly string _urlPrefix;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public ZoomitInvoices(IApiClient apiClient, IAccessTokenProvider<ClientAccessToken> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, new[] { ParentEntityName, EntityName })
{
_apiClient = apiClient;
_accessTokenProvider = accessTokenProvider;
_urlPrefix = urlPrefix;
}
/// <inheritdoc />
public Task<ZoomitInvoice> Get(ClientAccessToken token, Guid supplierId, Guid id, CancellationToken? cancellationToken = null) =>
InternalGet(token, new[] { supplierId }, id, cancellationToken);
/// <inheritdoc />
public async Task<ZoomitInvoice> Create(ClientAccessToken token, Guid supplierId, string filename, string path, CancellationToken? cancellationToken = null)
{
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
return await Create(token, supplierId, filename, stream, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<ZoomitInvoice> Create(ClientAccessToken token, Guid supplierId, string filename, Stream xmlContent, CancellationToken? cancellationToken = null)
{
var result = await _apiClient.PostInline<JsonApi.Resource<ZoomitInvoice, object, object, object>>(
$"{_urlPrefix}/{ParentEntityName}/{supplierId}/{EntityName}",
(await _accessTokenProvider.RefreshToken(token ?? throw new ArgumentNullException(nameof(token))).ConfigureAwait(false)).AccessToken,
new Dictionary<string, string>(),
filename,
xmlContent,
"application/xml",
cancellationToken ?? CancellationToken.None).ConfigureAwait(false);
return Map(result.Data);
}
}
/// <summary>
/// <p>This is an object representing the invoice that can be sent by a supplier. This document is always an UBL in BIS 3 format with additional validations.</p>
/// <p>CodaBox expects the following format for Zoomit invoices: <see href="http://docs.peppol.eu/poacc/billing/3.0/">Peppol BIS 3.0</see></p>
/// <p>CodaBox will verify the compliance of the UBL with XSD and schematron rules (you can find the CodaBox schematron rules <see href="https://documentation.ibanity.com/einvoicing/ZOOMIT-EN16931-UBL.sch">here</see>)</p>
/// <p>In order to send an invoice to Zoomit, some additional fields are required</p>
/// </summary>
public interface IZoomitInvoices
{
/// <summary>
/// Get Zoomit Invoice
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="supplierId">Supplier ID</param>
/// <param name="id">Invoice ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The specified invoice resource</returns>
Task<ZoomitInvoice> Get(ClientAccessToken token, Guid supplierId, Guid id, CancellationToken? cancellationToken = null);
/// <summary>
/// Create Zoomit Invoice
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="supplierId">Supplier ID</param>
/// <param name="filename">Your filename</param>
/// <param name="path">Local path the the XML file to upload</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a Zoomit Invoice resource</returns>
Task<ZoomitInvoice> Create(ClientAccessToken token, Guid supplierId, string filename, string path, CancellationToken? cancellationToken = null);
/// <summary>
/// Create Zoomit Invoice
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="supplierId">Supplier ID</param>
/// <param name="filename">Your filename</param>
/// <param name="xmlContent">XML content to upload</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a Zoomit Invoice resource</returns>
Task<ZoomitInvoice> Create(ClientAccessToken token, Guid supplierId, string filename, Stream xmlContent, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\eInvoicing | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\Models\PeppolCreditNote.cs | using System;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.eInvoicing.Models
{
/// <summary>
/// <p>This is an object representing the credit note that can be sent by a supplier. This document is always an UBL in a format supported by CodaBox.</p>
/// <p>The maximum file size is 100MB.</p>
/// </summary>
[DataContract]
public class PeppolCreditNote : Identified<Guid>
{
/// <summary>
/// When this peppol credit note was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec
/// </summary>
/// <value>When this peppol credit note was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec</value>
[DataMember(Name = "createdAt", EmitDefaultValue = false)]
public DateTimeOffset CreatedAt { get; set; }
/// <summary>
/// <p>Provides extra information to help you identify what went wrong.</p><ul><li> <code>invalid-malicious</code> The integrity of the document could not be verified.</li><li> <code>invalid-format</code> The format of the document is not supported or the document is not a credit note.</li><li> <code>invalid-xsd</code> The XSD validation failed for the document.</li><li> <code>invalid-schematron</code> The schematron validation failed for the document.</li><li><code>invalid-identifiers</code> The supplier data in the document could not be verified.</li><li> <code>invalid-size</code> The size of the document exceeds 100MB.</li><li> <code>invalid-type</code> The document is not an xml.</li><li> <code>error-customer-not-registered</code> The receiver of the document could not be found on the PEPPOL network.</li><li> <code>error-document-type-not-supported</code> The receiver does not support the type of document that was sent.</li><li> <code>error-customer-access-point-issue</code> There was an issue with the access point of the receiver.</li><li> <code>error-general</code>Unspecified error.</li></ul>
/// </summary>
/// <value><p>Provides extra information to help you identify what went wrong.</p><ul><li> <code>invalid-malicious</code> The integrity of the document could not be verified.</li><li> <code>invalid-format</code> The format of the document is not supported or the document is not a credit note.</li><li> <code>invalid-xsd</code> The XSD validation failed for the document.</li><li> <code>invalid-schematron</code> The schematron validation failed for the document.</li><li><code>invalid-identifiers</code> The supplier data in the document could not be verified.</li><li> <code>invalid-size</code> The size of the document exceeds 100MB.</li><li> <code>invalid-type</code> The document is not an xml.</li><li> <code>error-customer-not-registered</code> The receiver of the document could not be found on the PEPPOL network.</li><li> <code>error-document-type-not-supported</code> The receiver does not support the type of document that was sent.</li><li> <code>error-customer-access-point-issue</code> There was an issue with the access point of the receiver.</li><li> <code>error-general</code>Unspecified error.</li></ul></value>
[DataMember(Name = "errors", EmitDefaultValue = false)]
public Object Errors { get; set; }
/// <summary>
/// <p>The status of the credit note.</p><p>Possible values</p><ul><li><code>created</code> The credit note was successfully received by CodaBox and will be processed.</li><li><code>sending</code> The credit note is valid and will be sent to the customer.</li><li><code>sent</code> The credit note is sent to the access point of the customer. In this case you will receive a transmissionId.</li><li><code>invalid</code> The credit note is not valid, you will receive an error object containing a code and a message explaining what went wrong (see below).</li><li><code>send-error</code> The credit note could not be sent to the customer, you will receive an error object containing a code and a message explaining what went wrong (see below). </li></ul><p>In case of an unspecified error or an issue with the receiving access point, you can try to resend the credit note. CodaBox will not automatically resend the credit note, send-error is a final state of a document.</p>
/// </summary>
/// <value><p>The status of the credit note.</p><p>Possible values</p><ul><li><code>created</code> The credit note was successfully received by CodaBox and will be processed.</li><li><code>sending</code> The credit note is valid and will be sent to the customer.</li><li><code>sent</code> The credit note is sent to the access point of the customer. In this case you will receive a transmissionId.</li><li><code>invalid</code> The credit note is not valid, you will receive an error object containing a code and a message explaining what went wrong (see below).</li><li><code>send-error</code> The credit note could not be sent to the customer, you will receive an error object containing a code and a message explaining what went wrong (see below). </li></ul><p>In case of an unspecified error or an issue with the receiving access point, you can try to resend the credit note. CodaBox will not automatically resend the credit note, send-error is a final state of a document.</p></value>
[DataMember(Name = "status", EmitDefaultValue = false)]
public string Status { get; set; }
/// <summary>
/// This is a unique identifier used within the Peppol network. In case of an issue this can be used in communication with the receiving party.
/// </summary>
/// <value>This is a unique identifier used within the Peppol network. In case of an issue this can be used in communication with the receiving party.</value>
[DataMember(Name = "transmissionId", EmitDefaultValue = false)]
public string TransmissionId { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\eInvoicing | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\Models\PeppolCustomerSearch.cs | using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.eInvoicing.Models
{
/// <summary>
/// <p>This endpoint allows you to search for a customer on the PEPPOL network and the document types it supports. Based on the response you know:</p>
/// <p>- whether the customer is available on Peppol and is capable to receive documents over Peppol</p>
/// <p>- which UBL document types the customer is capable to receive</p>
/// <p>A list of test receivers can be found in <see href="https://documentation.ibanity.com/einvoicing/products#development-resources">Development Resources</see></p>
/// </summary>
[DataContract]
public class PeppolCustomerSearch
{
/// <summary>
/// <p>Customer reference identifier of the customer.</p><p>The <code>customerReference</code> should be of type Electronic Address Scheme (EAS), for more information see <a href=\"http://docs.peppol.eu/poacc/billing/3.0/codelist/eas/\">http://docs.peppol.eu/poacc/billing/3.0/codelist/eas/</a></p><p>Belgian participants are registered with the Belgian company number, for which identifier 0208 can be used. Optionally, the customer can be registered with their VAT number, for which identifier 9925 can be used.</p>
/// </summary>
/// <value><p>Customer reference identifier of the customer.</p><p>The <code>customerReference</code> should be of type Electronic Address Scheme (EAS), for more information see <a href=\"http://docs.peppol.eu/poacc/billing/3.0/codelist/eas/\">http://docs.peppol.eu/poacc/billing/3.0/codelist/eas/</a></p><p>Belgian participants are registered with the Belgian company number, for which identifier 0208 can be used. Optionally, the customer can be registered with their VAT number, for which identifier 9925 can be used.</p></value>
[DataMember(Name = "customerReference", EmitDefaultValue = false)]
public string CustomerReference { get; set; }
}
/// <inheritdoc cref="PeppolCustomerSearch" />
[DataContract]
public class PeppolCustomerSearchResponse : PeppolCustomerSearch, IIdentified<Guid>
{
/// <summary>
/// Supported document formats
/// </summary>
[DataMember(Name = "supportedDocumentFormats", EmitDefaultValue = false)]
public List<SupportedDocumentFormat> SupportedDocumentFormats { get; set; }
/// <inheritdoc />
[DataMember(Name = "id", EmitDefaultValue = false)]
public Guid Id { get; set; }
}
/// <summary>
/// Supported document format
/// </summary>
[DataContract]
public class SupportedDocumentFormat
{
/// <summary>
/// The root namespace of the document.
/// </summary>
[DataMember(Name = "rootNamespace", EmitDefaultValue = false)]
public string RootNamespace { get; set; }
/// <summary>
/// Type of document, Invoice or Credit Note.
/// </summary>
[DataMember(Name = "localName", EmitDefaultValue = false)]
public string LocalName { get; set; }
/// <summary>
/// An identification of the specification containing the total set of rules regarding semantic content, cardinalities and business rules to which the data contained in the instance document conforms.
/// </summary>
[DataMember(Name = "customizationId", EmitDefaultValue = false)]
public string CustomizationId { get; set; }
/// <summary>
/// Version of the UBL.
/// </summary>
[DataMember(Name = "ublVersionId", EmitDefaultValue = false)]
public string UblVersionId { get; set; }
/// <summary>
/// Identifies the business process context in which the transaction appears, to enable the Buyer to process the Invoice in an appropriate way.
/// </summary>
[DataMember(Name = "profileId", EmitDefaultValue = false)]
public string ProfileId { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\eInvoicing | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\Models\PeppolDocument.cs | using System;
using System.Globalization;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.eInvoicing.Models
{
/// <summary>
/// Peppol document
/// </summary>
[DataContract]
public class PeppolDocument : Identified<Guid>
{
/// <summary>
/// When this peppol document was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec
/// </summary>
/// <value>When this peppol document was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec</value>
[DataMember(Name = "createdAt", EmitDefaultValue = false)]
public string CreatedAtString { get; set; }
/// <summary>
/// When this peppol document was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec
/// </summary>
/// <value>When this peppol document was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec</value>
public DateTimeOffset CreatedAt =>
DateTimeOffset.TryParse(CreatedAtString, out var createdDate)
? createdDate
: DateTimeOffset.ParseExact(CreatedAtString.Replace(" 00:00", "+00:00"), "yyyy-MM-ddTHH:mm:ss.fffffffzzz", CultureInfo.InvariantCulture);
/// <summary>
/// <p>The status of the document.</p><p>Possible values</p><ul><li><code>created</code> The document was successfully received by CodaBox and will be processed.</li><li><code>sending</code> The document is valid and will be sent to the customer.</li><li><code>sent</code> The document is available for the customer in Zoomit. In this case you receive a transactionId.</li><li><code>invalid</code> The document is not valid, you will receive an error object containing a code and a message explaining what went wrong (see below).</li><li><code>send-error</code> The document could not be sent to the customer, you will receive an error object containing a code and a message explaining what went wrong (see below). </li></ul><p>In case of an unspecified error or an issue with the receiving access point, you can try to resend the the document. CodaBox will not automatically resend the the document, send-error is a final state of a document.</p>
/// </summary>
/// <value><p>The status of the document.</p><p>Possible values</p><ul><li><code>created</code> The document was successfully received by CodaBox and will be processed.</li><li><code>sending</code> The document is valid and will be sent to the customer.</li><li><code>sent</code> The document is available for the customer in Zoomit. In this case you receive a transactionId.</li><li><code>invalid</code> The document is not valid, you will receive an error object containing a code and a message explaining what went wrong (see below).</li><li><code>send-error</code> The document could not be sent to the customer, you will receive an error object containing a code and a message explaining what went wrong (see below). </li></ul><p>In case of an unspecified error or an issue with the receiving access point, you can try to resend the the document. CodaBox will not automatically resend the the document, send-error is a final state of a document.</p></value>
[DataMember(Name = "status", EmitDefaultValue = false)]
public string Status { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\eInvoicing | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\Models\PeppolInvoice.cs | using System;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.eInvoicing.Models
{
/// <summary>
/// <p>This is an object representing the invoice that can be sent by a supplier. This document is always an UBL in a format supported by CodaBox.</p>
/// <p>The maximum file size is 100MB.</p>
/// </summary>
[DataContract]
public class PeppolInvoice : Identified<Guid>
{
/// <summary>
/// When this peppol invoice was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec
/// </summary>
/// <value>When this peppol invoice was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec</value>
[DataMember(Name = "createdAt", EmitDefaultValue = false)]
public DateTimeOffset CreatedAt { get; set; }
/// <summary>
/// <p>Provides extra information to help you identify what went wrong.</p><ul><li> <code>invalid-malicious</code> The integrity of the document could not be verified.</li><li> <code>invalid-format</code> The format of the document is not supported or the document is not a credit note.</li><li> <code>invalid-xsd</code> The XSD validation failed for the document.</li><li> <code>invalid-schematron</code> The schematron validation failed for the document.</li><li><code>invalid-identifiers</code> The supplier data in the document could not be verified.</li><li> <code>invalid-size</code> The size of the document exceeds 100MB.</li><li> <code>invalid-type</code> The document is not an xml.</li><li> <code>error-customer-not-registered</code> The receiver of the document could not be found on the PEPPOL network.</li><li> <code>error-document-type-not-supported</code> The receiver does not support the type of document that was sent.</li><li> <code>error-customer-access-point-issue</code> There was an issue with the access point of the receiver.</li><li> <code>error-general</code>Unspecified error.</li></ul>
/// </summary>
/// <value><p>Provides extra information to help you identify what went wrong.</p><ul><li> <code>invalid-malicious</code> The integrity of the document could not be verified.</li><li> <code>invalid-format</code> The format of the document is not supported or the document is not a credit note.</li><li> <code>invalid-xsd</code> The XSD validation failed for the document.</li><li> <code>invalid-schematron</code> The schematron validation failed for the document.</li><li><code>invalid-identifiers</code> The supplier data in the document could not be verified.</li><li> <code>invalid-size</code> The size of the document exceeds 100MB.</li><li> <code>invalid-type</code> The document is not an xml.</li><li> <code>error-customer-not-registered</code> The receiver of the document could not be found on the PEPPOL network.</li><li> <code>error-document-type-not-supported</code> The receiver does not support the type of document that was sent.</li><li> <code>error-customer-access-point-issue</code> There was an issue with the access point of the receiver.</li><li> <code>error-general</code>Unspecified error.</li></ul></value>
[DataMember(Name = "errors", EmitDefaultValue = false)]
public Object Errors { get; set; }
/// <summary>
/// <p>The status of the invoice.</p><p>Possible values</p><ul><li><code>created</code> The invoice was successfully received by CodaBox and will be processed.</li><li><code>sending</code> The invoice is valid and will be sent to the customer.</li><li><code>sent</code> The invoice is sent to the access point of the customer. In this case you will receive a transmissionId.</li><li><code>invalid</code> The invoice is not valid, you will receive an error object containing a code and a message explaining what went wrong (see below).</li><li><code>send-error</code> The invoice could not be sent to the customer, you will receive an error object containing a code and a message explaining what went wrong (see below). </li></ul><p>In case of an unspecified error or an issue with the receiving access point, you can try to resend the invoice. CodaBox will not automatically resend the invoice, send-error is a final state of a document.</p>
/// </summary>
/// <value><p>The status of the invoice.</p><p>Possible values</p><ul><li><code>created</code> The invoice was successfully received by CodaBox and will be processed.</li><li><code>sending</code> The invoice is valid and will be sent to the customer.</li><li><code>sent</code> The invoice is sent to the access point of the customer. In this case you will receive a transmissionId.</li><li><code>invalid</code> The invoice is not valid, you will receive an error object containing a code and a message explaining what went wrong (see below).</li><li><code>send-error</code> The invoice could not be sent to the customer, you will receive an error object containing a code and a message explaining what went wrong (see below). </li></ul><p>In case of an unspecified error or an issue with the receiving access point, you can try to resend the invoice. CodaBox will not automatically resend the invoice, send-error is a final state of a document.</p></value>
[DataMember(Name = "status", EmitDefaultValue = false)]
public string Status { get; set; }
/// <summary>
/// This is a unique identifier used within the Peppol network. In case of an issue this can be used in communication with the receiving party.
/// </summary>
/// <value>This is a unique identifier used within the Peppol network. In case of an issue this can be used in communication with the receiving party.</value>
[DataMember(Name = "transmissionId", EmitDefaultValue = false)]
public string TransmissionId { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\eInvoicing | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\Models\Supplier.cs | using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.eInvoicing.Models
{
/// <summary>
/// This resource allows a Software Partner to create a new Supplier.
/// </summary>
[DataContract]
public class Supplier
{
/// <summary>
/// The city where the supplier is located.
/// </summary>
/// <value>The city where the supplier is located.</value>
[DataMember(Name = "city", EmitDefaultValue = false)]
public string City { get; set; }
/// <summary>
/// The company number of the supplier.
/// </summary>
/// <value>The company number of the supplier.</value>
[DataMember(Name = "companyNumber", EmitDefaultValue = false)]
public string CompanyNumber { get; set; }
/// <summary>
/// A person or department for CodaBox to contact in case of problems.
/// </summary>
/// <value>A person or department for CodaBox to contact in case of problems.</value>
[DataMember(Name = "contactEmail", EmitDefaultValue = false)]
public string ContactEmail { get; set; }
/// <summary>
/// The country where the supplier is located.
/// </summary>
/// <value>The country where the supplier is located.</value>
[DataMember(Name = "country", EmitDefaultValue = false)]
public string Country { get; set; }
/// <summary>
/// When this supplier was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec
/// </summary>
/// <value>When this supplier was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec</value>
[DataMember(Name = "createdAt", EmitDefaultValue = false)]
public DateTimeOffset CreatedAt { get; set; }
/// <summary>
/// The contact email of the supplier.
/// </summary>
/// <value>The contact email of the supplier.</value>
[DataMember(Name = "email", EmitDefaultValue = false)]
public string Email { get; set; }
/// <summary>
/// An object containing the identifying numbers of the supplier<br>For Belgian enterprises<ul><li><code>enterpriseNumber</code> use the enterprise number as it appears in the Crossroads Bank for Enterprises. (10 digits starting with 0 or 1)</li><li><code>vatNumber</code> a valid Belgian VAT number (\"BE\" + 10 digits)</li></ul><br>For Luxembourgish enterprises (at least one these must be provided)<ul><li><code>nationalIdentificationNumber</code> Legal entity national identification number: (11 digits)</li><li><code>vatNumber</code> a valid Luxembourgish VAT number (\"LU\" + 8 digits)</li></ul><br>For Dutch enterprises (at least one of these must be provided)<ul><li><code>kvkNumber</code> the number you've received as proof of your registration at the Netherlands Chamber of Commerce KVK (8 digits)</li><li><code>vatNumbers</code> a list of valid Dutch VAT numbers (\"NL\" + 9 digits + \"B\" + 2 digits)</li></ul><br>For German enterprises, <code>vatNumber</code> a valid German VAT number (\"DE\" + 9 digits)
/// </summary>
/// <value>An object containing the identifying numbers of the supplier<br>For Belgian enterprises<ul><li><code>enterpriseNumber</code> use the enterprise number as it appears in the Crossroads Bank for Enterprises. (10 digits starting with 0 or 1)</li><li><code>vatNumber</code> a valid Belgian VAT number (\"BE\" + 10 digits)</li></ul><br>For Luxembourgish enterprises (at least one these must be provided)<ul><li><code>nationalIdentificationNumber</code> Legal entity national identification number: (11 digits)</li><li><code>vatNumber</code> a valid Luxembourgish VAT number (\"LU\" + 8 digits)</li></ul><br>For Dutch enterprises (at least one of these must be provided)<ul><li><code>kvkNumber</code> the number you've received as proof of your registration at the Netherlands Chamber of Commerce KVK (8 digits)</li><li><code>vatNumbers</code> a list of valid Dutch VAT numbers (\"NL\" + 9 digits + \"B\" + 2 digits)</li></ul><br>For German enterprises, <code>vatNumber</code> a valid German VAT number (\"DE\" + 9 digits)</value>
[DataMember(Name = "enterpriseIdentification", EmitDefaultValue = false)]
public SupplierEnterpriseIdentification EnterpriseIdentification { get; set; }
/// <summary>
/// The homepage of the website of the supplier.
/// </summary>
/// <value>The homepage of the website of the supplier.</value>
[DataMember(Name = "homepage", EmitDefaultValue = false)]
public string Homepage { get; set; }
/// <summary>
/// An array of objects representing the IBANs of the supplier.<ul><li><code>id</code>An uuid of the IBAN number of the supplier.</li><li><code>value</code>The supplier IBAN of the supplier.</li></ul>
/// </summary>
/// <value>An array of objects representing the IBANs of the supplier.<ul><li><code>id</code>An uuid of the IBAN number of the supplier.</li><li><code>value</code>The supplier IBAN of the supplier.</li></ul></value>
[DataMember(Name = "ibans", EmitDefaultValue = false)]
public List<SupplierIban> Ibans { get; set; }
/// <summary>
/// An array of objects representing the company names of the supplier.<ul><li><code>id</code>An uuid of the company name of the supplier.</li><li><code>value</code>The company name of the supplier.</li></ul>
/// </summary>
/// <value>An array of objects representing the company names of the supplier.<ul><li><code>id</code>An uuid of the company name of the supplier.</li><li><code>value</code>The company name of the supplier.</li></ul></value>
[DataMember(Name = "names", EmitDefaultValue = false)]
public List<SupplierName> Names { get; set; }
/// <summary>
/// The status of the onboarding process of this supplier, for more information see <a href=\"https://documentation.ibanity.com/einvoicing/products#suppliers\">Suppliers</a>.<ul><li><code>created</code>The supplier was successfully created at CodaBox.</li><li><code>approved</code>The supplier information was validated by CodaBox and the supplier will be onboarded on the einvoicing network(s).</li><li><code>rejected</code>There was a problem with the supplier information and CodaBox could not accept the supplier.</li><li><code>onboarded</code>The supplier is now fully onboarded, you can now start sending documents for this supplier.</li><li><code>offboarded</code>The supplier was successfully offboarded, you can no longer send documents for this supplier.</li></ul>
/// </summary>
/// <value>The status of the onboarding process of this supplier, for more information see <a href=\"https://documentation.ibanity.com/einvoicing/products#suppliers\">Suppliers</a>.<ul><li><code>created</code>The supplier was successfully created at CodaBox.</li><li><code>approved</code>The supplier information was validated by CodaBox and the supplier will be onboarded on the einvoicing network(s).</li><li><code>rejected</code>There was a problem with the supplier information and CodaBox could not accept the supplier.</li><li><code>onboarded</code>The supplier is now fully onboarded, you can now start sending documents for this supplier.</li><li><code>offboarded</code>The supplier was successfully offboarded, you can no longer send documents for this supplier.</li></ul></value>
[DataMember(Name = "onboardingStatus", EmitDefaultValue = false)]
public string OnboardingStatus { get; set; }
/// <summary>
/// The phonenumber of the supplier.
/// </summary>
/// <value>The phonenumber of the supplier.</value>
[DataMember(Name = "phoneNumber", EmitDefaultValue = false)]
public string PhoneNumber { get; set; }
/// <summary>
/// The street name of the address where the supplier is located.
/// </summary>
/// <value>The street name of the address where the supplier is located.</value>
[DataMember(Name = "street", EmitDefaultValue = false)]
public string Street { get; set; }
/// <summary>
/// The street number of the address where the supplier is located.
/// </summary>
/// <value>The street number of the address where the supplier is located.</value>
[DataMember(Name = "streetNumber", EmitDefaultValue = false)]
public string StreetNumber { get; set; }
/// <summary>
/// <i>(Optional)</i> The support email address of the supplier. Can be used in case this differs from the general email.
/// </summary>
/// <value><i>(Optional)</i> The support email address of the supplier. Can be used in case this differs from the general email.</value>
[DataMember(Name = "supportEmail", EmitDefaultValue = false)]
public string SupportEmail { get; set; }
/// <summary>
/// <i>(Optional)</i> The support phone number of the supplier.
/// </summary>
/// <value><i>(Optional)</i> The support phone number of the supplier.</value>
[DataMember(Name = "supportPhone", EmitDefaultValue = false)]
public string SupportPhone { get; set; }
/// <summary>
/// <i>(Optional)</i> The support URL of the supplier.
/// </summary>
/// <value><i>(Optional)</i> The support URL of the supplier.</value>
[DataMember(Name = "supportUrl", EmitDefaultValue = false)]
public string SupportUrl { get; set; }
/// <summary>
/// The zipcode of the city where the supplier is located.
/// </summary>
/// <value>The zipcode of the city where the supplier is located.</value>
[DataMember(Name = "zip", EmitDefaultValue = false)]
public string Zip { get; set; }
}
/// <inheritdoc cref="Supplier" />
[DataContract]
public class SupplierResponse : Supplier, IIdentified<Guid>
{
/// <inheritdoc />
[DataMember(Name = "id", EmitDefaultValue = false)]
public Guid Id { get; set; }
}
/// <inheritdoc />
public class NewSupplier : Supplier
{
/// <summary>
/// The picture of the front of the identity card of the legal representative of the company. Base64-encoded string. Supported formats are <code>image/jpeg</code>, <code>image/png</code>, <code>application/pdf</code>. This picture will only be used for the KYC check, afterwards it will be deleted. Please do not share a picture of the back of the identity card.
/// </summary>
/// <value>The picture of the front of the identity card of the legal representative of the company. Base64-encoded string. Supported formats are <code>image/jpeg</code>, <code>image/png</code>, <code>application/pdf</code>. This picture will only be used for the KYC check, afterwards it will be deleted. Please do not share a picture of the back of the identity card.</value>
[DataMember(Name = "representativeIdScan", EmitDefaultValue = false)]
public string RepresentativeIdScan { get; set; }
/// <summary>
/// The scan of the company's entry in the business registration directory of that company's country.. Base64-encoded string. Supported formats are <code>image/jpeg</code>, <code>image/png</code>, <code>application/pdf</code>. This picture will only be used for the KYC check, afterwards it will be deleted. Only for non-Belgian companies. Maximum file size: 1MiB..
/// </summary>
/// <value>The scan of the company's entry in the business registration directory of that company's country. Base64-encoded string. Supported formats are <code>image/jpeg</code>, <code>image/png</code>, <code>application/pdf</code>. This picture will only be used for the KYC check, afterwards it will be deleted. Only for non-Belgian companies. Maximum file size: 1MiB..</value>
[DataMember(Name = "businessRegisterScan", EmitDefaultValue = false)]
public string BusinessRegisterScan { get; set; }
}
/// <summary>
/// IBAN of the supplier.
/// </summary>
[DataContract]
public class SupplierIban
{
/// <summary>
/// An uuid of the IBAN number of the supplier.
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public Guid Id { get; set; }
/// <summary>
/// The supplier IBAN of the supplier.
/// </summary>
[DataMember(Name = "value", EmitDefaultValue = false)]
public string Value { get; set; }
}
/// <summary>
/// Name of the supplier.
/// </summary>
[DataContract]
public class SupplierName
{
/// <summary>
/// An uuid of the company name of the supplier.
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public Guid Id { get; set; }
/// <summary>
/// The company name of the supplier.
/// </summary>
[DataMember(Name = "value", EmitDefaultValue = false)]
public string Value { get; set; }
}
/// <summary>
/// Name of the supplier.
/// </summary>
[DataContract]
public class SupplierEnterpriseIdentification
{
/// <summary>
/// Enterprise number.
/// </summary>
[DataMember(Name = "enterpriseNumber", EmitDefaultValue = false)]
public string EnterpriseNumber { get; set; }
/// <summary>
/// VAT number.
/// </summary>
[DataMember(Name = "vatNumber", EmitDefaultValue = false)]
public string VatNumber { get; set; }
/// <summary>
/// National identification number.
/// </summary>
[DataMember(Name = "nationalIdentificationNumber", EmitDefaultValue = false)]
public string NationalIdentificationNumber { get; set; }
/// <summary>
/// KVK number.
/// </summary>
[DataMember(Name = "kvkNumber", EmitDefaultValue = false)]
public string KvkNumber { get; set; }
/// <summary>
/// A list of VAT numbers.
/// </summary>
[DataMember(Name = "vatNumbers", EmitDefaultValue = false)]
public List<string> VatNumbers { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\eInvoicing | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\Models\ZoomitCreditNote.cs | using System;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.eInvoicing.Models
{
/// <summary>
/// <p>This is an object representing the credit note that can be sent by a supplier. This document is always an UBL in BIS 3 format with additional validations.</p>
/// <p>CodaBox expects the following format for Zoomit credit notes: <see href="http://docs.peppol.eu/poacc/billing/3.0/">Peppol BIS 3.0</see></p>
/// <p>CodaBox will verify the compliance of the UBL with XSD and schematron rules (you can find the CodaBox schematron rules <see href="https://documentation.ibanity.com/einvoicing/ZOOMIT-EN16931-UBL.sch">here</see>)</p>
/// <p>In order to send a credit note to Zoomit, some additional fields are required</p>
/// </summary>
[DataContract]
public class ZoomitCreditNote : Identified<Guid>
{
/// <summary>
/// When this zoomit credit note was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec
/// </summary>
/// <value>When this zoomit credit note was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec</value>
[DataMember(Name = "createdAt", EmitDefaultValue = false)]
public DateTimeOffset CreatedAt { get; set; }
/// <summary>
/// <p>The status of the credit note.</p><p>Possible values</p><ul><li><code>created</code> The credit note was successfully received by CodaBox and will be processed.</li><li><code>sending</code> The credit note is valid and will be sent to the customer.</li><li><code>sent</code> The credit note is available for the customer in Zoomit. In this case you receive a transactionId.</li><li><code>invalid</code> The credit note is not valid, you will receive an error object containing a code and a message explaining what went wrong (see below).</li><li><code>send-error</code> The credit note could not be sent to the customer, you will receive an error object containing a code and a message explaining what went wrong (see below). </li></ul><p>In case of an unspecified error or an issue with the receiving access point, you can try to resend the credit note. CodaBox will not automatically resend the credit note, send-error is a final state of a document.</p>
/// </summary>
/// <value><p>The status of the credit note.</p><p>Possible values</p><ul><li><code>created</code> The credit note was successfully received by CodaBox and will be processed.</li><li><code>sending</code> The credit note is valid and will be sent to the customer.</li><li><code>sent</code> The credit note is available for the customer in Zoomit. In this case you receive a transactionId.</li><li><code>invalid</code> The credit note is not valid, you will receive an error object containing a code and a message explaining what went wrong (see below).</li><li><code>send-error</code> The credit note could not be sent to the customer, you will receive an error object containing a code and a message explaining what went wrong (see below). </li></ul><p>In case of an unspecified error or an issue with the receiving access point, you can try to resend the credit note. CodaBox will not automatically resend the credit note, send-error is a final state of a document.</p></value>
[DataMember(Name = "status", EmitDefaultValue = false)]
public string Status { get; set; }
/// <summary>
/// Identifier for the associated transaction
/// </summary>
/// <value>Identifier for the associated transaction</value>
[DataMember(Name = "transactionId", EmitDefaultValue = false)]
public Guid TransactionId { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\eInvoicing | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\Models\ZoomitCustomerSearch.cs | using System;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.eInvoicing.Models
{
/// <summary>
/// <p>This endpoint allows you to search for a customer on the Zoomit network. Based on the response you know whether the customer is reachable on Zoomit or not.</p>
/// <p>A list of test receivers can be found in <see href="https://documentation.ibanity.com/einvoicing/products#development-resources">Development Resources</see></p>
/// </summary>
[DataContract]
public class ZoomitCustomerSearch
{
/// <summary>
/// <p>The reference of the customer (IBAN).</p><p>Zoomit participants are registered with their IBAN. </p><p>The customerId should be of type Electronic Address Scheme (EAS), for more information see <a href=\"http://docs.peppol.eu/poacc/billing/3.0/codelist/eas/\">http://docs.peppol.eu/poacc/billing/3.0/codelist/eas/</a></p><p>To search for a customer based on its IBAN you need to use the identifier <code>0193</code> which is the UBL.BE identifier and the IBAN should start with <code>IBN_</code> Example: <code>0193:IBN_BE22977000014401</code>.</p>
/// </summary>
/// <value><p>The reference of the customer (IBAN).</p><p>Zoomit participants are registered with their IBAN. </p><p>The customerId should be of type Electronic Address Scheme (EAS), for more information see <a href=\"http://docs.peppol.eu/poacc/billing/3.0/codelist/eas/\">http://docs.peppol.eu/poacc/billing/3.0/codelist/eas/</a></p><p>To search for a customer based on its IBAN you need to use the identifier <code>0193</code> which is the UBL.BE identifier and the IBAN should start with <code>IBN_</code> Example: <code>0193:IBN_BE22977000014401</code>.</p></value>
[DataMember(Name = "customerReference", EmitDefaultValue = false)]
public string CustomerReference { get; set; }
/// <summary>
/// <p>The status of the customer.</p><p>Possible values</p><ul><li> <code>active</code> The customer is using Zoomit and wants to receive your documents.</li><li> <code>potential</code> The customer can be reached on Zoomit, but did not yet confirm to receive your documents in Zoomit. To make sure your customer receives your documents, you should send the documents via Zoomit and an extra channel (eg email) until he accepts to receive your documents in Zoomit only.</li><li> <code>not-reachable</code> The customer is not available on Zoomit.</li></ul>
/// </summary>
/// <value><p>The status of the customer.</p><p>Possible values</p><ul><li> <code>active</code> The customer is using Zoomit and wants to receive your documents.</li><li> <code>potential</code> The customer can be reached on Zoomit, but did not yet confirm to receive your documents in Zoomit. To make sure your customer receives your documents, you should send the documents via Zoomit and an extra channel (eg email) until he accepts to receive your documents in Zoomit only.</li><li> <code>not-reachable</code> The customer is not available on Zoomit.</li></ul></value>
[DataMember(Name = "status", EmitDefaultValue = false)]
public string Status { get; set; }
}
/// <inheritdoc cref="ZoomitCustomerSearch" />
[DataContract]
public class ZoomitCustomerSearchResponse : ZoomitCustomerSearch, IIdentified<Guid>
{
/// <inheritdoc />
[DataMember(Name = "id", EmitDefaultValue = false)]
public Guid Id { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\eInvoicing | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\Models\ZoomitDocument.cs | using System;
using System.Globalization;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.eInvoicing.Models
{
/// <summary>
/// Zoomit document
/// </summary>
[DataContract]
public class ZoomitDocument : Identified<Guid>
{
/// <summary>
/// When this zoomit document was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec
/// </summary>
/// <value>When this zoomit document was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec</value>
[DataMember(Name = "createdAt", EmitDefaultValue = false)]
public string CreatedAtString { get; set; }
/// <summary>
/// When this zoomit document was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec
/// </summary>
/// <value>When this zoomit document was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec</value>
public DateTimeOffset CreatedAt =>
DateTimeOffset.TryParse(CreatedAtString, out var createdDate)
? createdDate
: DateTimeOffset.ParseExact(CreatedAtString.Replace(" 00:00", "+00:00"), "yyyy-MM-ddTHH:mm:ss.fffffffzzz", CultureInfo.InvariantCulture);
/// <summary>
/// <p>The status of the document.</p><p>Possible values</p><ul><li><code>created</code> The document was successfully received by CodaBox and will be processed.</li><li><code>sending</code> The document is valid and will be sent to the customer.</li><li><code>sent</code> The document is available for the customer in Zoomit. In this case you receive a transactionId.</li><li><code>invalid</code> The document is not valid, you will receive an error object containing a code and a message explaining what went wrong (see below).</li><li><code>send-error</code> The document could not be sent to the customer, you will receive an error object containing a code and a message explaining what went wrong (see below). </li></ul><p>In case of an unspecified error or an issue with the receiving access point, you can try to resend the the document. CodaBox will not automatically resend the the document, send-error is a final state of a document.</p>
/// </summary>
/// <value><p>The status of the document.</p><p>Possible values</p><ul><li><code>created</code> The document was successfully received by CodaBox and will be processed.</li><li><code>sending</code> The document is valid and will be sent to the customer.</li><li><code>sent</code> The document is available for the customer in Zoomit. In this case you receive a transactionId.</li><li><code>invalid</code> The document is not valid, you will receive an error object containing a code and a message explaining what went wrong (see below).</li><li><code>send-error</code> The document could not be sent to the customer, you will receive an error object containing a code and a message explaining what went wrong (see below). </li></ul><p>In case of an unspecified error or an issue with the receiving access point, you can try to resend the the document. CodaBox will not automatically resend the the document, send-error is a final state of a document.</p></value>
[DataMember(Name = "status", EmitDefaultValue = false)]
public string Status { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\eInvoicing | raw_data\ibanity-dotnet\src\Client\Products\eInvoicing\Models\ZoomitInvoice.cs | using System;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.eInvoicing.Models
{
/// <summary>
/// <p>This is an object representing the invoice that can be sent by a supplier. This document is always an UBL in BIS 3 format with additional validations.</p>
/// <p>CodaBox expects the following format for Zoomit invoices: <see href="http://docs.peppol.eu/poacc/billing/3.0/">Peppol BIS 3.0</see></p>
/// <p>CodaBox will verify the compliance of the UBL with XSD and schematron rules (you can find the CodaBox schematron rules <see href="https://documentation.ibanity.com/einvoicing/ZOOMIT-EN16931-UBL.sch">here</see>)</p>
/// <p>In order to send an invoice to Zoomit, some additional fields are required</p>
/// </summary>
[DataContract]
public class ZoomitInvoice : Identified<Guid>
{
/// <summary>
/// When this zoomit invoice was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec
/// </summary>
/// <value>When this zoomit invoice was created. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec</value>
[DataMember(Name = "createdAt", EmitDefaultValue = false)]
public DateTimeOffset CreatedAt { get; set; }
/// <summary>
/// This is the reachability status of a customer.
/// </summary>
/// <value>This is the reachability status of a customer.</value>
[DataMember(Name = "customerStatus", EmitDefaultValue = false)]
public string CustomerStatus { get; set; }
/// <summary>
/// <p>Provides extra information to help you identify what went wrong.</p><ul><li><code>invalid-malicious</code> The integrity of the document could not be verified.</li><li><code>invalid-format</code> The format of the document is not supported or the document is not a credit note.</li><li><code>invalid-xsd</code> The XSD validation failed for the document.</li><li><code>invalid-schematron</code> The schematron validation failed for the document.</li><li><code>invalid-identifiers</code> The supplier data in the document could not be verified.</li><li><code>invalid-size</code> The size of the document exceeds 100MB.</li><li><code>invalid-type</code> The document is not an xml.</li><li><code>error-customer-not-registered</code> The receiver is not reachable on Zoomit.</li><li><code>error-general</code>Unspecified error.</li></ul>
/// </summary>
/// <value><p>Provides extra information to help you identify what went wrong.</p><ul><li><code>invalid-malicious</code> The integrity of the document could not be verified.</li><li><code>invalid-format</code> The format of the document is not supported or the document is not a credit note.</li><li><code>invalid-xsd</code> The XSD validation failed for the document.</li><li><code>invalid-schematron</code> The schematron validation failed for the document.</li><li><code>invalid-identifiers</code> The supplier data in the document could not be verified.</li><li><code>invalid-size</code> The size of the document exceeds 100MB.</li><li><code>invalid-type</code> The document is not an xml.</li><li><code>error-customer-not-registered</code> The receiver is not reachable on Zoomit.</li><li><code>error-general</code>Unspecified error.</li></ul></value>
[DataMember(Name = "errors", EmitDefaultValue = false)]
public Object Errors { get; set; }
/// <summary>
/// <p>The status of the invoice.</p><p>Possible values</p><ul><li><code>created</code> The invoice was successfully received by CodaBox and will be processed.</li><li><code>sending</code> The invoice is valid and will be sent to the customer.</li><li><code>sent</code> The invoice note is available for the customer in Zoomit. In this case you receive a transactionId.</li><li><code>paid</code> The user initiated the payment through Zoomit.</li><li><code>invalid</code> The invoice is not valid, you will receive an error object containing a code and a message explaining what went wrong (see below).</li><li><code>send-error</code> The invoice could not be sent to the customer, you will receive an error object containing a code and a message explaining what went wrong (see below). </li></ul><p>In case of an unspecified error or an issue with the receiving access point, you can try to resend the invoice. CodaBox will not automatically resend the invoice, send-error is a final state of a document.</p>
/// </summary>
/// <value><p>The status of the invoice.</p><p>Possible values</p><ul><li><code>created</code> The invoice was successfully received by CodaBox and will be processed.</li><li><code>sending</code> The invoice is valid and will be sent to the customer.</li><li><code>sent</code> The invoice note is available for the customer in Zoomit. In this case you receive a transactionId.</li><li><code>paid</code> The user initiated the payment through Zoomit.</li><li><code>invalid</code> The invoice is not valid, you will receive an error object containing a code and a message explaining what went wrong (see below).</li><li><code>send-error</code> The invoice could not be sent to the customer, you will receive an error object containing a code and a message explaining what went wrong (see below). </li></ul><p>In case of an unspecified error or an issue with the receiving access point, you can try to resend the invoice. CodaBox will not automatically resend the invoice, send-error is a final state of a document.</p></value>
[DataMember(Name = "status", EmitDefaultValue = false)]
public string Status { get; set; }
/// <summary>
/// Identifier for the associated transaction
/// </summary>
/// <value>Identifier for the associated transaction</value>
[DataMember(Name = "transactionId", EmitDefaultValue = false)]
public Guid TransactionId { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect\AccountReports.cs | using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.IsabelConnect.Models;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.IsabelConnect
{
/// <summary>
/// <para>This object provides details about an account report. From the list endpoint, you will receive a collection of the account report objects for the corresponding customer.</para>
/// <para>Unlike other endpoints, the get endpoint will return the contents of the account report file instead of a json object. You can also find a link to the report in the account report object links.</para>
/// </summary>
public class AccountReports : ResourceClient<AccountReport, object, object, object, string, Token>, IAccountReports
{
private const string EntityName = "account-reports";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public AccountReports(IApiClient apiClient, IAccessTokenProvider<Token> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, EntityName)
{ }
/// <inheritdoc />
public Task<IsabelCollection<AccountReport>> List(Token token, long? pageOffset = null, int? pageSize = null, string after = null, CancellationToken? cancellationToken = null) =>
InternalOffsetBasedList(
token,
null,
string.IsNullOrWhiteSpace(after) ? null : new[] { ("after", after) },
pageOffset,
pageSize,
cancellationToken);
/// <inheritdoc />
public Task Get(Token token, string id, Stream target, CancellationToken? cancellationToken = null) =>
InternalGetToStream(token, id, null, target, cancellationToken);
/// <inheritdoc />
protected override string ParseId(string id) => id;
}
/// <summary>
/// <para>This object provides details about an account report. From the list endpoint, you will receive a collection of the account report objects for the corresponding customer.</para>
/// <para>Unlike other endpoints, the get endpoint will return the contents of the account report file instead of a json object. You can also find a link to the report in the account report object links.</para>
/// </summary>
public interface IAccountReports
{
/// <summary>
/// List Account Reports.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="pageOffset">Defines the start position of the results by giving the number of records to be skipped</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="after">Identifier of an account report that serves as a cursor, limiting results to account reports which have been received and processed after it. In practice, you can provide your last-processed ID to retrieve only the newer account reports.</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A list of transaction resources</returns>
Task<IsabelCollection<AccountReport>> List(Token token, long? pageOffset = null, int? pageSize = null, string after = null, CancellationToken? cancellationToken = null);
/// <summary>
/// Get Account Report.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="id">Account Report ID</param>
/// <param name="target">Destination stream where the account report will be written</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <remarks>Result will be written to the provided stream.</remarks>
Task Get(Token token, string id, Stream target, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect\Accounts.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.JsonApi;
using Ibanity.Apis.Client.Products.IsabelConnect.Models;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.IsabelConnect
{
/// <summary>
/// <para>This is an object representing a customer account. This object will provide details about the account, including the reference and the currency.</para>
/// <para>An account has related transactions and balances.</para>
/// <para>The account API endpoints are customer specific and therefore can only be accessed by providing the corresponding access token.</para>
/// </summary>
public class Accounts : ResourceClient<Account, object, object, object, string, Token>, IAccounts
{
private const string EntityName = "accounts";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public Accounts(IApiClient apiClient, IAccessTokenProvider<Token> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, EntityName)
{ }
/// <inheritdoc />
protected override string ParseId(string id) => id;
/// <inheritdoc />
protected override Account Map(Data<Account, object, object, object> data)
{
if (data.Attributes == null)
data.Attributes = new Account();
return base.Map(data);
}
/// <inheritdoc />
public Task<IsabelCollection<Account>> List(Token token, long? pageOffset, int? pageSize, CancellationToken? cancellationToken) =>
InternalOffsetBasedList(
token ?? throw new ArgumentNullException(nameof(token)),
null,
null,
pageOffset,
pageSize,
cancellationToken);
/// <inheritdoc />
public Task<IsabelCollection<Account>> List(Token token, ContinuationToken continuationToken, CancellationToken? cancellationToken) =>
InternalOffsetBasedList(
token ?? throw new ArgumentNullException(nameof(token)),
continuationToken ?? throw new ArgumentNullException(nameof(continuationToken)),
cancellationToken);
/// <inheritdoc />
public Task<Account> Get(Token token, string id, CancellationToken? cancellationToken = null) =>
InternalGet(token, id, cancellationToken);
}
/// <summary>
/// <para>This is an object representing a customer account. This object will provide details about the account, including the reference and the currency.</para>
/// <para>An account has related transactions and balances.</para>
/// <para>The account API endpoints are customer specific and therefore can only be accessed by providing the corresponding access token.</para>
/// </summary>
public interface IAccounts
{
/// <summary>
/// List Accounts
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="pageOffset">Defines the start position of the results by giving the number of records to be skipped</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A list of account resources</returns>
Task<IsabelCollection<Account>> List(Token token, long? pageOffset = null, int? pageSize = null, CancellationToken? cancellationToken = null);
/// <summary>
/// List Accounts
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="continuationToken">Token referencing the page to request</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A list of account resources</returns>
Task<IsabelCollection<Account>> List(Token token, ContinuationToken continuationToken, CancellationToken? cancellationToken = null);
/// <summary>
/// Get Account
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="id">Account ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The specified account resource</returns>
Task<Account> Get(Token token, string id, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect\Balances.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.IsabelConnect.Models;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.IsabelConnect
{
/// <summary>
/// This is an object representing a balance related to a customer's account.
/// </summary>
public class Balances : ResourceWithParentClient<BalanceWithFakeId, object, object, object, string, string, Token>, IBalances
{
private const string ParentEntityName = "accounts";
private const string EntityName = "balances";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public Balances(IApiClient apiClient, IAccessTokenProvider<Token> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, new[] { ParentEntityName, EntityName })
{ }
/// <inheritdoc />
public async Task<IsabelCollection<Balance>> List(Token token, string accountId, DateTimeOffset? from = null, DateTimeOffset? to = null, long? pageOffset = null, int? pageSize = null, CancellationToken? cancellationToken = null)
{
var timespanParameters = new List<(string, string)>();
if (from.HasValue)
timespanParameters.Add(("from", from.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
if (to.HasValue)
timespanParameters.Add(("to", to.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
var result = await InternalOffsetBasedList(token, new[] { accountId }, null, timespanParameters, pageOffset, pageSize, cancellationToken).ConfigureAwait(false);
return new IsabelCollection<Balance>
{
Offset = result.Offset,
Total = result.Total,
Items = result.Items.Select(b => new Balance(b)).ToList(),
ContinuationToken = result.ContinuationToken
};
}
/// <inheritdoc />
protected override string ParseId(string id) => id;
}
/// <summary>
/// This is an object representing a balance related to a customer's account.
/// </summary>
public interface IBalances
{
/// <summary>
/// List Accounts Balances
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountId">Customer's account ID</param>
/// <param name="from">Start of the period scope. Mandatory if to is present. If not provided, the most recent balance of each type is returned.</param>
/// <param name="to">End of the period scope. Must be equal to or later than from value. Defaults to today's date.</param>
/// <param name="pageOffset">Defines the start position of the results by giving the number of records to be skipped</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A list of balance resources</returns>
/// <remarks>The range may contain maximum 31 calendar days (e.g. 2020-10-01-2020-10-31).</remarks>
Task<IsabelCollection<Balance>> List(Token token, string accountId, DateTimeOffset? from = null, DateTimeOffset? to = null, long? pageOffset = null, int? pageSize = null, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect\BulkPaymentInitiationRequests.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.IsabelConnect.Models;
namespace Ibanity.Apis.Client.Products.IsabelConnect
{
/// <summary>
/// <para>This is an object representing a bulk payment initiation request. When you want to request the initiation of payments on behalf of one of your customers, you can create one to start the authorization flow.</para>
/// <para>When creating the request, you should provide the payment information by uploading a PAIN xml file. <see href="https://documentation.ibanity.com/isabel-connect/products#bulk-payment-initiation">Learn more about the supported formats in Isabel Connect</see>.</para>
/// </summary>
public class BulkPaymentInitiationRequests : ResourceClient<BulkPaymentInitiationRequest, object, object, object, string, Token>, IBulkPaymentInitiationRequests
{
private const string EntityName = "bulk-payment-initiation-requests";
private readonly IApiClient _apiClient;
private readonly IAccessTokenProvider<Token> _accessTokenProvider;
private readonly string _urlPrefix;
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public BulkPaymentInitiationRequests(IApiClient apiClient, IAccessTokenProvider<Token> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, EntityName)
{
_apiClient = apiClient;
_accessTokenProvider = accessTokenProvider;
_urlPrefix = urlPrefix;
}
/// <inheritdoc />
public Task<BulkPaymentInitiationRequest> Get(Token token, string id, CancellationToken? cancellationToken = null) =>
InternalGet(token, id, cancellationToken);
/// <inheritdoc />
public async Task<BulkPaymentInitiationRequest> Create(Token token, string filename, string path, bool? isShared = null, bool? hideDetails = null, CancellationToken? cancellationToken = null)
{
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
return await Create(token, filename, stream, isShared, hideDetails, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<BulkPaymentInitiationRequest> Create(Token token, string filename, Stream xmlContent, bool? isShared = null, bool? hideDetails = null, CancellationToken? cancellationToken = null)
{
var headers = new Dictionary<string, string>();
if (isShared.HasValue)
headers.Add("Is-Shared", isShared.Value.ToString().ToLowerInvariant());
if (hideDetails.HasValue)
headers.Add("Hide-Details", hideDetails.Value.ToString().ToLowerInvariant());
var result = await _apiClient.PostInline<JsonApi.Resource<BulkPaymentInitiationRequest, object, object, object>>(
$"{_urlPrefix}/{EntityName}",
(await _accessTokenProvider.RefreshToken(token ?? throw new ArgumentNullException(nameof(token))).ConfigureAwait(false)).AccessToken,
headers,
filename,
xmlContent,
"application/xml",
cancellationToken ?? CancellationToken.None).ConfigureAwait(false);
return Map(result.Data);
}
/// <inheritdoc />
protected override string ParseId(string id) => id;
}
/// <summary>
/// <para>This is an object representing a bulk payment initiation request. When you want to request the initiation of payments on behalf of one of your customers, you can create one to start the authorization flow.</para>
/// <para>When creating the request, you should provide the payment information by uploading a PAIN xml file. <see href="https://documentation.ibanity.com/isabel-connect/products#bulk-payment-initiation">Learn more about the supported formats in Isabel Connect</see>.</para>
/// </summary>
public interface IBulkPaymentInitiationRequests
{
/// <summary>
/// Get Bulk Payment Initiation Request
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="id">Bulk Payment Initiation Request ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a bulk payment initiation request resource</returns>
Task<BulkPaymentInitiationRequest> Get(Token token, string id, CancellationToken? cancellationToken = null);
/// <summary>
/// Create Bulk Payment Initiation Request
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="filename">As shown to the user in Isabel 6</param>
/// <param name="path">Local path the the XML file to upload</param>
/// <param name="isShared">Defines if the payment file can be accessed by the other users having the right mandate on Isabel 6. Defaults to <c>true</c>.</param>
/// <param name="hideDetails">Defines if the details (on single transactions) within the payment file can be viewed by other users on Isabel 6 or not. Defaults to <c>false</c>.</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a bulk payment initiation request resource</returns>
Task<BulkPaymentInitiationRequest> Create(Token token, string filename, string path, bool? isShared = null, bool? hideDetails = null, CancellationToken? cancellationToken = null);
/// <summary>
/// Create Bulk Payment Initiation Request
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="filename">As shown to the user in Isabel 6</param>
/// <param name="xmlContent">XML content to upload</param>
/// <param name="isShared">Defines if the payment file can be accessed by the other users having the right mandate on Isabel 6. Defaults to <c>true</c>.</param>
/// <param name="hideDetails">Defines if the details (on single transactions) within the payment file can be viewed by other users on Isabel 6 or not. Defaults to <c>false</c>.</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>Returns a bulk payment initiation request resource</returns>
Task<BulkPaymentInitiationRequest> Create(Token token, string filename, Stream xmlContent, bool? isShared = null, bool? hideDetails = null, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect\IntradayTransactions.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.IsabelConnect.Models;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.IsabelConnect
{
/// <summary>
/// <para>This is an object representing an intraday account transaction. This object will give you the details of the intraday transaction, including its amount and execution date.</para>
/// <para>At the end of the day, intraday transactions will be converted to transactions by the financial institution. The transactions will never be available as transactions and intraday transactions at the same time.</para>
/// <para>Important: The ID of the intraday transaction will NOT be the same as the ID of the corresponding transaction.</para>
/// </summary>
public class IntradayTransactions : ResourceWithParentClient<IntradayTransaction, object, object, object, string, string, Token>, IIntradayTransactions
{
private const string ParentEntityName = "accounts";
private const string EntityName = "intraday-transactions";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public IntradayTransactions(IApiClient apiClient, IAccessTokenProvider<Token> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, new[] { ParentEntityName, EntityName })
{ }
/// <inheritdoc />
public Task<IsabelCollection<IntradayTransaction>> List(Token token, string accountId, long? pageOffset = null, int? pageSize = null, CancellationToken? cancellationToken = null) =>
InternalOffsetBasedList(token, new[] { accountId }, null, null, pageOffset, pageSize, cancellationToken);
/// <inheritdoc />
protected override string ParseId(string id) => id;
}
/// <summary>
/// <para>This is an object representing an intraday account transaction. This object will give you the details of the intraday transaction, including its amount and execution date.</para>
/// <para>At the end of the day, intraday transactions will be converted to transactions by the financial institution. The transactions will never be available as transactions and intraday transactions at the same time.</para>
/// <para>Important: The ID of the intraday transaction will NOT be the same as the ID of the corresponding transaction.</para>
/// </summary>
public interface IIntradayTransactions
{
/// <summary>
/// List intraday transactions.
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountId">Customer's account ID</param>
/// <param name="pageOffset">Defines the start position of the results by giving the number of records to be skipped</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A list of transaction resources</returns>
Task<IsabelCollection<IntradayTransaction>> List(Token token, string accountId, long? pageOffset = null, int? pageSize = null, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect\IsabelConnectClient.cs | using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.IsabelConnect.Models;
namespace Ibanity.Apis.Client.Products.IsabelConnect
{
/// <inheritdoc cref="IIsabelConnectClient" />
public class IsabelConnectClient : ProductClient<ITokenProviderWithoutCodeVerifier>, IIsabelConnectClient
{
/// <summary>
/// Product name used as prefix in Isabel Connect URIs.
/// </summary>
public const string UrlPrefix = "isabel-connect";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="tokenService">Service to generate and refresh access tokens</param>
/// <param name="clientAccessTokenService">Service to generate and refresh client access tokens.</param>
/// <param name="customerTokenService">Service to generate and refresh customer access tokens.</param>
public IsabelConnectClient(IApiClient apiClient, ITokenProviderWithoutCodeVerifier tokenService, IClientAccessTokenProvider clientAccessTokenService, ICustomerAccessTokenProvider customerTokenService)
: base(apiClient, tokenService, clientAccessTokenService, customerTokenService)
{
Accounts = new Accounts(apiClient, tokenService, UrlPrefix);
Transactions = new Transactions(apiClient, tokenService, UrlPrefix);
Balances = new Balances(apiClient, tokenService, UrlPrefix);
IntradayTransactions = new IntradayTransactions(apiClient, tokenService, UrlPrefix);
AccountReports = new AccountReports(apiClient, tokenService, UrlPrefix);
BulkPaymentInitiationRequests = new BulkPaymentInitiationRequests(apiClient, tokenService, UrlPrefix);
}
/// <inheritdoc />
public IAccounts Accounts { get; }
/// <inheritdoc />
public IBalances Balances { get; }
/// <inheritdoc />
public ITransactions Transactions { get; }
/// <inheritdoc />
public IIntradayTransactions IntradayTransactions { get; }
/// <inheritdoc />
public IAccountReports AccountReports { get; }
/// <inheritdoc />
public IBulkPaymentInitiationRequests BulkPaymentInitiationRequests { get; }
}
/// <summary>
/// Contains services for all Isabel Connect-related resources.
/// </summary>
public interface IIsabelConnectClient : IProductWithRefreshTokenClient<ITokenProviderWithoutCodeVerifier>
{
/// <summary>
/// <para>This is an object representing a customer account. This object will provide details about the account, including the reference and the currency.</para>
/// <para>An account has related transactions and balances.</para>
/// <para>The account API endpoints are customer specific and therefore can only be accessed by providing the corresponding access token.</para>
/// </summary>
IAccounts Accounts { get; }
/// <summary>
/// This is an object representing a balance related to a customer's account.
/// </summary>
IBalances Balances { get; }
/// <summary>
/// <para>This is an object representing an account transaction. This object will give you the details of the financial transaction, including its amount and execution date.</para>
/// <para>Unlike an <see cref="IntradayTransaction" />, this is an end-of-day object which will not change.</para>
/// </summary>
ITransactions Transactions { get; }
/// <summary>
/// <para>This is an object representing an intraday account transaction. This object will give you the details of the intraday transaction, including its amount and execution date.</para>
/// <para>At the end of the day, intraday transactions will be converted to transactions by the financial institution. The transactions will never be available as transactions and intraday transactions at the same time.</para>
/// <para>Important: The ID of the intraday transaction will NOT be the same as the ID of the corresponding transaction.</para>
/// </summary>
IIntradayTransactions IntradayTransactions { get; }
/// <summary>
/// <para>This object provides details about an account report. From the list endpoint, you will receive a collection of the account report objects for the corresponding customer.</para>
/// <para>Unlike other endpoints, the get endpoint will return the contents of the account report file instead of a json object. You can also find a link to the report in the account report object links.</para>
/// </summary>
IAccountReports AccountReports { get; }
/// <summary>
/// <para>This is an object representing a bulk payment initiation request. When you want to request the initiation of payments on behalf of one of your customers, you can create one to start the authorization flow.</para>
/// <para>When creating the request, you should provide the payment information by uploading a PAIN xml file. <see href="https://documentation.ibanity.com/isabel-connect/products#bulk-payment-initiation">Learn more about the supported formats in Isabel Connect</see>.</para>
/// </summary>
IBulkPaymentInitiationRequests BulkPaymentInitiationRequests { get; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect\Transactions.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.IsabelConnect.Models;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.IsabelConnect
{
/// <summary>
/// <para>This is an object representing an account transaction. This object will give you the details of the financial transaction, including its amount and execution date.</para>
/// <para>Unlike an <see cref="IntradayTransaction" />, this is an end-of-day object which will not change.</para>
/// </summary>
public class Transactions : ResourceWithParentClient<Transaction, object, object, object, string, string, Token>, ITransactions
{
private const string ParentEntityName = "accounts";
private const string EntityName = "transactions";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public Transactions(IApiClient apiClient, IAccessTokenProvider<Token> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, new[] { ParentEntityName, EntityName })
{ }
/// <inheritdoc />
public Task<IsabelCollection<Transaction>> List(Token token, string accountId, DateTimeOffset? from = null, DateTimeOffset? to = null, long? pageOffset = null, int? pageSize = null, CancellationToken? cancellationToken = null)
{
var timespanParameters = new List<(string, string)>();
if (from.HasValue)
timespanParameters.Add(("from", from.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
if (to.HasValue)
timespanParameters.Add(("to", to.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
return InternalOffsetBasedList(token, new[] { accountId }, null, timespanParameters, pageOffset, pageSize, cancellationToken);
}
/// <inheritdoc />
protected override string ParseId(string id) => id;
}
/// <summary>
/// <para>This is an object representing an account transaction. This object will give you the details of the financial transaction, including its amount and execution date.</para>
/// <para>Unlike an <see cref="IntradayTransaction" />, this is an end-of-day object which will not change.</para>
/// </summary>
public interface ITransactions
{
/// <summary>
/// List Transactions
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountId">Customer's account ID</param>
/// <param name="from">Start of the period scope, in the ISO8601 format YYYY-MM-DD. Mandatory if to is present. Defaults to today's date. Must be within 365 days of today's date and within 200 days of the to date.</param>
/// <param name="to">End of the period scope, in the ISO8601 format YYYY-MM-DD. Must be equal to or later than from value. Defaults to today's date.</param>
/// <param name="pageOffset">Defines the start position of the results by giving the number of records to be skipped</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A list of transaction resources</returns>
Task<IsabelCollection<Transaction>> List(Token token, string accountId, DateTimeOffset? from = null, DateTimeOffset? to = null, long? pageOffset = null, int? pageSize = null, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect | raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect\Models\Account.cs | using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.IsabelConnect.Models
{
/// <summary>
/// <p>This is an object representing a customer account. This object will provide details about the account, including the reference and the currency.</p>
/// <p>An account has related transactions and balances.</p>
/// <p>The account API endpoints are customer specific and therefore can only be accessed by providing the corresponding access token.</p>
/// </summary>
[DataContract]
public class Account : Identified<string>
{
/// <summary>
/// Country of the account, same as the country of the financial institution where the account is held
/// </summary>
/// <value>Country of the account, same as the country of the financial institution where the account is held</value>
[DataMember(Name = "country", EmitDefaultValue = false)]
public string Country { get; set; }
/// <summary>
/// Currency of the account, in <a href='https://en.wikipedia.org/wiki/ISO_4217'>ISO4217</a> format
/// </summary>
/// <value>Currency of the account, in <a href='https://en.wikipedia.org/wiki/ISO_4217'>ISO4217</a> format</value>
[DataMember(Name = "currency", EmitDefaultValue = false)]
public string Currency { get; set; }
/// <summary>
/// Description of the account
/// </summary>
/// <value>Description of the account</value>
[DataMember(Name = "description", EmitDefaultValue = false)]
public string Description { get; set; }
/// <summary>
/// BIC for the account's financial institution
/// </summary>
/// <value>BIC for the account's financial institution</value>
[DataMember(Name = "financialInstitutionBic", EmitDefaultValue = false)]
public string FinancialInstitutionBic { get; set; }
/// <summary>
/// Address of the account holder
/// </summary>
/// <value>Address of the account holder</value>
[DataMember(Name = "holderAddress", EmitDefaultValue = false)]
public string HolderAddress { get; set; }
/// <summary>
/// Country of the account holder's address
/// </summary>
/// <value>Country of the account holder's address</value>
[DataMember(Name = "holderAddressCountry", EmitDefaultValue = false)]
public string HolderAddressCountry { get; set; }
/// <summary>
/// Name of the account holder
/// </summary>
/// <value>Name of the account holder</value>
[DataMember(Name = "holderName", EmitDefaultValue = false)]
public string HolderName { get; set; }
/// <summary>
/// Financial institution's internal reference for this account
/// </summary>
/// <value>Financial institution's internal reference for this account</value>
[DataMember(Name = "reference", EmitDefaultValue = false)]
public string Reference { get; set; }
/// <summary>
/// Type of financial institution reference (either <code>IBAN</code> or <code>unknown</code>)
/// </summary>
/// <value>Type of financial institution reference (either <code>IBAN</code> or <code>unknown</code>)</value>
[DataMember(Name = "referenceType", EmitDefaultValue = false)]
public string ReferenceType { get; set; }
/// <inheritdoc />
public override string ToString() => $"Account {Id}";
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect | raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect\Models\AccountReport.cs | using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.IsabelConnect.Models
{
/// <summary>
/// <p>This object provides details about an account report. From the list endpoint, you will receive a collection of the account report objects for the corresponding customer.</p>
/// <p>Unlike other endpoints, the get endpoint will return the contents of the account report file instead of a json object. You can also find a link to the report in the account report object links.</p>
/// </summary>
[DataContract]
public class AccountReport : Identified<string>
{
/// <summary>
/// References of the corresponding accounts
/// </summary>
/// <value>References of the corresponding accounts</value>
[DataMember(Name = "accountReferences", EmitDefaultValue = false)]
public List<string> AccountReferences { get; set; }
/// <summary>
/// Format of the corresponding account report file. Possible values are <code>CODA</code>, <code>MT940</code>, <code>MT940N</code>, <code>MT940E</code>, <code>MT941</code>, <code>MT942</code>, <code>MT942N</code>, <code>MT942E</code>, <code>CAMT52</code>, <code>CAMT53</code>, <code>CAMT54</code>
/// </summary>
/// <value>Format of the corresponding account report file. Possible values are <code>CODA</code>, <code>MT940</code>, <code>MT940N</code>, <code>MT940E</code>, <code>MT941</code>, <code>MT942</code>, <code>MT942N</code>, <code>MT942E</code>, <code>CAMT52</code>, <code>CAMT53</code>, <code>CAMT54</code></value>
[DataMember(Name = "fileFormat", EmitDefaultValue = false)]
public string FileFormat { get; set; }
/// <summary>
/// Name of the corresponding account report file
/// </summary>
/// <value>Name of the corresponding account report file</value>
[DataMember(Name = "fileName", EmitDefaultValue = false)]
public string FileName { get; set; }
/// <summary>
/// Size of the corresponding account report file, in bytes
/// </summary>
/// <value>Size of the corresponding account report file, in bytes</value>
[DataMember(Name = "fileSize", EmitDefaultValue = false)]
public decimal FileSize { get; set; }
/// <summary>
/// Name of the corresponding account's financial institution
/// </summary>
/// <value>Name of the corresponding account's financial institution</value>
[DataMember(Name = "financialInstitutionName", EmitDefaultValue = false)]
public string FinancialInstitutionName { get; set; }
/// <summary>
/// When the account report was received by Isabel 6. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec
/// </summary>
/// <value>When the account report was received by Isabel 6. Formatted according to <a href='https://en.wikipedia.org/wiki/ISO_8601'>ISO8601</a> spec</value>
[DataMember(Name = "receivedAt", EmitDefaultValue = false)]
public DateTimeOffset ReceivedAt { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect | raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect\Models\Balance.cs | using System;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.IsabelConnect.Models
{
/// <summary>
/// This is an object representing a balance related to a customer's account.
/// </summary>
[DataContract]
public class Balance
{
/// <summary>
/// Build a new instance.
/// </summary>
public Balance() { }
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="from">Source instance</param>
/// <remarks>Copy constructor.</remarks>
public Balance(Balance from)
{
if (from is null)
throw new ArgumentNullException(nameof(from));
Amount = from.Amount;
Datetime = from.Datetime;
Subtype = from.Subtype;
}
/// <summary>
/// Amount of the balance. Can be positive or negative
/// </summary>
/// <value>Amount of the balance. Can be positive or negative</value>
[DataMember(Name = "amount", EmitDefaultValue = false)]
public decimal Amount { get; set; }
/// <summary>
/// When this balance was effective
/// </summary>
/// <value>When this balance was effective</value>
[DataMember(Name = "datetime", EmitDefaultValue = false)]
public DateTimeOffset Datetime { get; set; }
/// <summary>
/// Type of balance. The possible values are <code>CLBD</code> (Closing Balance), <code>CLAV</code> (Closing Available Balance), <code>ITBD</code> (Intraday Balance), <code>ITAV</code> (Intraday Available Balance), or <code>INFO</code> if derived from the previous statement.
/// </summary>
/// <value>Type of balance. The possible values are <code>CLBD</code> (Closing Balance), <code>CLAV</code> (Closing Available Balance), <code>ITBD</code> (Intraday Balance), <code>ITAV</code> (Intraday Available Balance), or <code>INFO</code> if derived from the previous statement.</value>
[DataMember(Name = "subtype", EmitDefaultValue = false)]
public string Subtype { get; set; }
}
/// <summary>
/// Technical-only object, prefer <see cref="Balance" /> usage.
/// </summary>
[DataContract]
public class BalanceWithFakeId : Balance, IIdentified<string>
{
/// <summary>
/// Fake field.
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public string Id { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect | raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect\Models\BulkPaymentInitiationRequest.cs | using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.IsabelConnect.Models
{
/// <summary>
/// <p>This is an object representing a bulk payment initiation request. When you want to request the initiation of payments on behalf of one of your customers, you can create one to start the authorization flow.</p>
/// <p>When creating the request, you should provide the payment information by uploading a PAIN xml file. <see href="https://documentation.ibanity.com/isabel-connect/products#bulk-payment-initiation">Learn more about the supported formats in Isabel Connect.</see></p>
/// </summary>
[DataContract]
public class BulkPaymentInitiationRequest : Identified<string>
{
/// <summary>
/// Status of the bulk payment initiation request. <a href='/isabel-connect/products#bulk-payment-statuses'>See possible statuses</a>.
/// </summary>
/// <value>Status of the bulk payment initiation request. <a href='/isabel-connect/products#bulk-payment-statuses'>See possible statuses</a>.</value>
[DataMember(Name = "status", EmitDefaultValue = false)]
public string Status { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect | raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect\Models\IntradayTransaction.cs | using System;
using System.Globalization;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.IsabelConnect.Models
{
/// <summary>
/// <p>This is an object representing an intraday account transaction. This object will give you the details of the intraday transaction, including its amount and execution date.</p>
/// <p>At the end of the day, intraday transactions will be converted to transactions by the financial institution. The transactions will never be available as transactions and intraday transactions at the same time.</p>
/// <p>Important: The ID of the intraday transaction will NOT be the same as the ID of the corresponding <see cref="Transaction" />.</p>
/// </summary>
[DataContract]
public class IntradayTransaction : Identified<string>
{
/// <summary>
/// Additional transaction-related information provided from the financial institution to the customer
/// </summary>
/// <value>Additional transaction-related information provided from the financial institution to the customer</value>
[DataMember(Name = "additionalInformation", EmitDefaultValue = false)]
public string AdditionalInformation { get; set; }
/// <summary>
/// Amount of the intraday transaction. Can be positive or negative
/// </summary>
/// <value>Amount of the intraday transaction. Can be positive or negative</value>
[DataMember(Name = "amount", EmitDefaultValue = false)]
public decimal Amount { get; set; }
/// <summary>
/// Number representing the counterpart's account
/// </summary>
/// <value>Number representing the counterpart's account</value>
[DataMember(Name = "counterpartAccountReference", EmitDefaultValue = false)]
public string CounterpartAccountReference { get; set; }
/// <summary>
/// BIC for the counterpart's financial institution
/// </summary>
/// <value>BIC for the counterpart's financial institution</value>
[DataMember(Name = "counterpartFinancialInstitutionBic", EmitDefaultValue = false)]
public string CounterpartFinancialInstitutionBic { get; set; }
/// <summary>
/// Legal name of the counterpart
/// </summary>
/// <value>Legal name of the counterpart</value>
[DataMember(Name = "counterpartName", EmitDefaultValue = false)]
public string CounterpartName { get; set; }
/// <summary>
/// Unique identification assigned by the initiating party to unambiguously identify the transaction. This identification is passed on, unchanged, throughout the entire end-to-end chain.
/// </summary>
/// <value>Unique identification assigned by the initiating party to unambiguously identify the transaction. This identification is passed on, unchanged, throughout the entire end-to-end chain.</value>
[DataMember(Name = "endToEndId", EmitDefaultValue = false)]
public string EndToEndId { get; set; }
/// <summary>
/// Date representing the moment the intraday transaction has been recorded
/// </summary>
/// <value>Date representing the moment the intraday transaction has been recorded</value>
[DataMember(Name = "executionDate", EmitDefaultValue = false)]
public string ExecutionDateString
{
get => ExecutionDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
set => ExecutionDate = DateTimeOffset.Parse(value, CultureInfo.InvariantCulture);
}
/// <summary>
/// Date representing the moment the intraday transaction has been recorded
/// </summary>
/// <value>Date representing the moment the intraday transaction has been recorded</value>
public DateTimeOffset ExecutionDate { get; set; }
/// <summary>
/// Financial institution's reference for the transaction
/// </summary>
/// <value>Financial institution's reference for the transaction</value>
[DataMember(Name = "internalId", EmitDefaultValue = false)]
public string InternalId { get; set; }
/// <summary>
/// Content of the remittance information (aka communication)
/// </summary>
/// <value>Content of the remittance information (aka communication)</value>
[DataMember(Name = "remittanceInformation", EmitDefaultValue = false)]
public string RemittanceInformation { get; set; }
/// <summary>
/// Type of remittance information, can be <code>structured</code> or <code>unstructured</code>
/// </summary>
/// <value>Type of remittance information, can be <code>structured</code> or <code>unstructured</code></value>
[DataMember(Name = "remittanceInformationType", EmitDefaultValue = false)]
public string RemittanceInformationType { get; set; }
/// <summary>
/// Current status of the account information access request. Possible values are <code>received</code>, <code>started</code>, <code>rejected</code>, <code>succeeded</code>, <code>partially-succeeded</code>, and <code>failed</code>. <a href='/xs2a/products#aiar-status-codes'>See status definitions.</a>
/// </summary>
/// <value>Current status of the account information access request. Possible values are <code>received</code>, <code>started</code>, <code>rejected</code>, <code>succeeded</code>, <code>partially-succeeded</code>, and <code>failed</code>. <a href='/xs2a/products#aiar-status-codes'>See status definitions.</a></value>
[DataMember(Name = "status", EmitDefaultValue = false)]
public string Status { get; set; }
/// <summary>
/// Date representing the moment the intraday transaction is considered effective
/// </summary>
/// <value>Date representing the moment the intraday transaction is considered effective</value>
[DataMember(Name = "valueDate", EmitDefaultValue = false)]
public string ValueDateString
{
get => ValueDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
set => ValueDate = DateTimeOffset.Parse(value, CultureInfo.InvariantCulture);
}
/// <summary>
/// Date representing the moment the intraday transaction is considered effective
/// </summary>
/// <value>Date representing the moment the intraday transaction is considered effective</value>
public DateTimeOffset ValueDate { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect | raw_data\ibanity-dotnet\src\Client\Products\IsabelConnect\Models\Transaction.cs | using System;
using System.Globalization;
using System.Runtime.Serialization;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.IsabelConnect.Models
{
/// <summary>
/// <p>This is an object representing an account transaction. This object will give you the details of the financial transaction, including its amount and execution date.</p>
/// <p>Unlike an intraday transaction, this is an end-of-day object which will not change.</p>
/// </summary>
[DataContract]
public class Transaction : Identified<string>
{
/// <summary>
/// Additional transaction-related information provided from the financial institution to the customer
/// </summary>
/// <value>Additional transaction-related information provided from the financial institution to the customer</value>
[DataMember(Name = "additionalInformation", EmitDefaultValue = false)]
public string AdditionalInformation { get; set; }
/// <summary>
/// Amount of the transaction. Can be positive or negative
/// </summary>
/// <value>Amount of the transaction. Can be positive or negative</value>
[DataMember(Name = "amount", EmitDefaultValue = false)]
public decimal Amount { get; set; }
/// <summary>
/// Number representing the counterpart's account
/// </summary>
/// <value>Number representing the counterpart's account</value>
[DataMember(Name = "counterpartAccountReference", EmitDefaultValue = false)]
public string CounterpartAccountReference { get; set; }
/// <summary>
/// BIC for the counterpart's financial institution
/// </summary>
/// <value>BIC for the counterpart's financial institution</value>
[DataMember(Name = "counterpartFinancialInstitutionBic", EmitDefaultValue = false)]
public string CounterpartFinancialInstitutionBic { get; set; }
/// <summary>
/// Legal name of the counterpart
/// </summary>
/// <value>Legal name of the counterpart</value>
[DataMember(Name = "counterpartName", EmitDefaultValue = false)]
public string CounterpartName { get; set; }
/// <summary>
/// Unique identification assigned by the initiating party to unambiguously identify the transaction. This identification is passed on, unchanged, throughout the entire end-to-end chain.
/// </summary>
/// <value>Unique identification assigned by the initiating party to unambiguously identify the transaction. This identification is passed on, unchanged, throughout the entire end-to-end chain.</value>
[DataMember(Name = "endToEndId", EmitDefaultValue = false)]
public string EndToEndId { get; set; }
/// <summary>
/// Date representing the moment the transaction has been recorded
/// </summary>
/// <value>Date representing the moment the transaction has been recorded</value>
[DataMember(Name = "executionDate", EmitDefaultValue = false)]
public string ExecutionDateString
{
get => ExecutionDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
set => ExecutionDate = DateTimeOffset.Parse(value, CultureInfo.InvariantCulture);
}
/// <summary>
/// Date representing the moment the transaction has been recorded
/// </summary>
/// <value>Date representing the moment the transaction has been recorded</value>
public DateTimeOffset ExecutionDate { get; set; }
/// <summary>
/// Financial institution's reference for the transaction
/// </summary>
/// <value>Financial institution's reference for the transaction</value>
[DataMember(Name = "internalId", EmitDefaultValue = false)]
public string InternalId { get; set; }
/// <summary>
/// Content of the remittance information (aka communication)
/// </summary>
/// <value>Content of the remittance information (aka communication)</value>
[DataMember(Name = "remittanceInformation", EmitDefaultValue = false)]
public string RemittanceInformation { get; set; }
/// <summary>
/// Type of remittance information. Can be <code>structured-be</code>, <code>structured-eu</code>, or <code>unstructured</code>
/// </summary>
/// <value>Type of remittance information. Can be <code>structured-be</code>, <code>structured-eu</code>, or <code>unstructured</code></value>
[DataMember(Name = "remittanceInformationType", EmitDefaultValue = false)]
public string RemittanceInformationType { get; set; }
/// <summary>
/// Current status of the transaction. Possible values are <code>booked</code>, <code>information</code>, or <code>pending</code>
/// </summary>
/// <value>Current status of the transaction. Possible values are <code>booked</code>, <code>information</code>, or <code>pending</code></value>
[DataMember(Name = "status", EmitDefaultValue = false)]
public string Status { get; set; }
/// <summary>
/// Date representing the moment the transaction is considered effective
/// </summary>
/// <value>Date representing the moment the transaction is considered effective</value>
[DataMember(Name = "valueDate", EmitDefaultValue = false)]
public string ValueDateString
{
get => ValueDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
set => ValueDate = DateTimeOffset.Parse(value, CultureInfo.InvariantCulture);
}
/// <summary>
/// Date representing the moment the transaction is considered effective
/// </summary>
/// <value>Date representing the moment the transaction is considered effective</value>
public DateTimeOffset ValueDate { get; set; }
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\PontoConnect\Accounts.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.PontoConnect.Models;
using Ibanity.Apis.Client.Utils;
namespace Ibanity.Apis.Client.Products.PontoConnect
{
/// <summary>
/// <para>This is an object representing a user's account. This object will provide details about the account, including the balance and the currency.</para>
/// <para>An account has related transactions and belongs to a financial institution.</para>
/// <para>An account may be revoked from an integration using the revoke account endpoint. To recover access, the user must add the account back to the integration in their Ponto Dashboard or in a new authorization flow.</para>
/// </summary>
public class Accounts : ResourceClient<AccountResponse, AccountMeta, object, object, Token>, IAccounts
{
private const string EntityName = "accounts";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public Accounts(IApiClient apiClient, IAccessTokenProvider<Token> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, EntityName)
{ }
/// <inheritdoc />
public Task<IbanityCollection<AccountResponse>> List(Token token, int? pageSize, Guid? pageBefore, Guid? pageAfter, CancellationToken? cancellationToken) =>
InternalCursorBasedList(
token ?? throw new ArgumentNullException(nameof(token)),
null,
pageSize,
pageBefore,
pageAfter,
cancellationToken);
/// <inheritdoc />
public Task<IbanityCollection<AccountResponse>> List(Token token, ContinuationToken continuationToken, CancellationToken? cancellationToken) =>
InternalCursorBasedList(
token ?? throw new ArgumentNullException(nameof(token)),
continuationToken ?? throw new ArgumentNullException(nameof(continuationToken)),
cancellationToken);
/// <inheritdoc />
public Task<AccountResponse> Get(Token token, Guid id, CancellationToken? cancellationToken) =>
InternalGet(token, id, cancellationToken);
/// <inheritdoc />
public Task Revoke(Token token, Guid id, CancellationToken? cancellationToken = null) =>
InternalDelete(token, id, cancellationToken);
/// <inheritdoc />
protected override AccountResponse Map(JsonApi.Data<AccountResponse, AccountMeta, object, object> data)
{
var result = base.Map(data);
result.SynchronizedAt = data.Meta.SynchronizedAt;
result.Availability = data.Meta.Availability;
result.LatestSynchronization = data.Meta.LatestSynchronization.Attributes;
result.LatestSynchronization.Id = Guid.Parse(data.Meta.LatestSynchronization.Id);
return result;
}
}
/// <summary>
/// <para>This is an object representing a user's account. This object will provide details about the account, including the balance and the currency.</para>
/// <para>An account has related transactions and belongs to a financial institution.</para>
/// <para>An account may be revoked from an integration using the revoke account endpoint. To recover access, the user must add the account back to the integration in their Ponto Dashboard or in a new authorization flow.</para>
/// </summary>
public interface IAccounts
{
/// <summary>
/// List Accounts
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="pageSize">Number of items by page</param>
/// <param name="pageBefore">Cursor that specifies the first resource of the next page</param>
/// <param name="pageAfter">Cursor that specifies the last resource of the previous page</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A list of account resources</returns>
Task<IbanityCollection<AccountResponse>> List(Token token, int? pageSize = null, Guid? pageBefore = null, Guid? pageAfter = null, CancellationToken? cancellationToken = null);
/// <summary>
/// List Accounts
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="continuationToken">Token referencing the page to request</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>A list of account resources</returns>
Task<IbanityCollection<AccountResponse>> List(Token token, ContinuationToken continuationToken, CancellationToken? cancellationToken = null);
/// <summary>
/// Get Account
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="id">Account ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The specified account resource</returns>
Task<AccountResponse> Get(Token token, Guid id, CancellationToken? cancellationToken = null);
/// <summary>
/// Revoke Account
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="id">Account ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
Task Revoke(Token token, Guid id, CancellationToken? cancellationToken = null);
}
}
| 0 |
raw_data\ibanity-dotnet\src\Client\Products | raw_data\ibanity-dotnet\src\Client\Products\PontoConnect\BulkPayments.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Ibanity.Apis.Client.Http;
using Ibanity.Apis.Client.Products.PontoConnect.Models;
namespace Ibanity.Apis.Client.Products.PontoConnect
{
/// <summary>
/// <para>This is an object representing a bulk payment. When you want to initiate a bulk payment from one of your user's accounts, you have to create one to start the authorization flow.</para>
/// <para>If you provide a redirect URI when creating the bulk payment, you will receive a redirect link to send your customer to to start the authorization flow. Note that for live bulk payments, your user must have already requested and been granted payment service for their organization to use this flow.</para>
/// <para>Otherwise, the user can sign the bulk payment in the Ponto Dashboard.</para>
/// <para>When authorizing bulk payment initiation in the sandbox, you should use the pre-filled credentials and 123456 as the digipass response.</para>
/// </summary>
public class BulkPayments : ResourceWithParentClient<BulkPaymentResponse, object, object, PaymentLinks, Token>, IBulkPayments
{
private const string ParentEntityName = "accounts";
private const string EntityName = "bulk-payments";
/// <summary>
/// Build a new instance.
/// </summary>
/// <param name="apiClient">Generic API client</param>
/// <param name="accessTokenProvider">Service to refresh access tokens</param>
/// <param name="urlPrefix">Beginning of URIs, composed by Ibanity API endpoint, followed by product name</param>
public BulkPayments(IApiClient apiClient, IAccessTokenProvider<Token> accessTokenProvider, string urlPrefix) :
base(apiClient, accessTokenProvider, urlPrefix, new[] { ParentEntityName, EntityName })
{ }
/// <inheritdoc />
public Task<BulkPaymentResponse> Create(Token token, Guid accountId, BulkPaymentRequest payment, Guid? idempotencyKey, CancellationToken? cancellationToken)
{
if (token is null)
throw new ArgumentNullException(nameof(token));
if (payment is null)
throw new ArgumentNullException(nameof(payment));
var payload = new JsonApi.Data<BulkPaymentRequest, object, object, object>
{
Type = "bulkPayment",
Attributes = payment
};
return InternalCreate(token, new[] { accountId }, payload, idempotencyKey, cancellationToken);
}
/// <inheritdoc />
public Task<BulkPaymentResponse> Get(Token token, Guid accountId, Guid id, CancellationToken? cancellationToken) =>
InternalGet(token, new[] { accountId }, id, cancellationToken);
/// <inheritdoc />
public Task Delete(Token token, Guid accountId, Guid id, CancellationToken? cancellationToken) =>
InternalDelete(token, new[] { accountId }, id, cancellationToken);
/// <inheritdoc />
protected override BulkPaymentResponse Map(JsonApi.Data<BulkPaymentResponse, object, object, PaymentLinks> data)
{
var result = base.Map(data);
result.RedirectUri = data.Links?.RedirectString;
return result;
}
}
/// <summary>
/// <para>This is an object representing a bulk payment. When you want to initiate a bulk payment from one of your user's accounts, you have to create one to start the authorization flow.</para>
/// <para>If you provide a redirect URI when creating the bulk payment, you will receive a redirect link to send your customer to to start the authorization flow. Note that for live bulk payments, your user must have already requested and been granted payment service for their organization to use this flow.</para>
/// <para>Otherwise, the user can sign the bulk payment in the Ponto Dashboard.</para>
/// <para>When authorizing bulk payment initiation in the sandbox, you should use the pre-filled credentials and 123456 as the digipass response.</para>
/// </summary>
public interface IBulkPayments
{
/// <summary>
/// Create Bulk Payment
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountId">Account ID</param>
/// <param name="payment">An object representing a bulk payment</param>
/// <param name="idempotencyKey">Several requests with the same idempotency key will be executed only once</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The created bulk payment resource</returns>
Task<BulkPaymentResponse> Create(Token token, Guid accountId, BulkPaymentRequest payment, Guid? idempotencyKey = null, CancellationToken? cancellationToken = null);
/// <summary>
/// Get Bulk Payment
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountId">Account ID</param>
/// <param name="id">Bulk payment ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
/// <returns>The specified bulk payment resource</returns>
Task<BulkPaymentResponse> Get(Token token, Guid accountId, Guid id, CancellationToken? cancellationToken = null);
/// <summary>
/// Delete Bulk Payment
/// </summary>
/// <param name="token">Authentication token</param>
/// <param name="accountId">Account ID</param>
/// <param name="id">Bulk payment ID</param>
/// <param name="cancellationToken">Allow to cancel a long-running task</param>
Task Delete(Token token, Guid accountId, Guid id, CancellationToken? cancellationToken = null);
}
}
| 0 |