Initial commit

pull/2/head
Matija Koželj 2 years ago
parent 6e9576620f
commit 54502060f6

@ -0,0 +1,21 @@
using Common.Types.TaxRates;
using Connected.Startup;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Common.Types;
public class ClientBootstrapper : IStartup
{
public async Task Configure(WebAssemblyHost host)
{
await Task.CompletedTask;
}
public async Task ConfigureServices(IServiceCollection services)
{
services.Add(ServiceDescriptor.Scoped(typeof(ITaxRateService), typeof(TaxRateService)));
await Task.CompletedTask;
}
}

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>Common.Types</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Connected\Connected.Client\Connected.Client.csproj" />
<ProjectReference Include="..\Common.Types.Model\Common.Types.Model.csproj" />
</ItemGroup>
</Project>

@ -0,0 +1,13 @@
using Connected.Data;
namespace Common.Types.TaxRates;
/// <summary>
/// This is the client implementation if the <see cref="ITaxRate"/>.
/// </summary>
public class TaxRate : PrimaryKey<int>, ITaxRate
{
public string? Name { get; init; }
public float Rate { get; init; }
public Status Status { get; init; } = Status.Enabled;
}

@ -0,0 +1,56 @@
using System.Collections.Immutable;
using Connected.Net;
using Connected.Remote;
using Connected.ServiceModel;
using Connected.Services;
namespace Common.Types.TaxRates;
/// <summary>
/// This is the client implementation of the <see cref="ITaxRateService"/>.
/// </summary>
internal class TaxRateService : EntityService<int>, ITaxRateService, IRemoteService
{
public TaxRateService(IHttpService http)
{
Http = http;
}
private IHttpService Http { get; }
public async Task Delete(PrimaryKeyArgs<int> e)
{
await Http.Post("http://localhost:5063/management/commonTypes/taxRates/delete", e);
}
public async Task<int> Insert(InsertTaxRateArgs e)
{
return await Http.Post<int>("http://localhost:5063/management/commonTypes/taxRates/insert", e);
}
public async Task<ImmutableList<ITaxRate>?> Query(PrimaryKeyListArgs<int> e)
{
return (await Http.Post<List<TaxRate>?>("http://localhost:5063/management/commonTypes/taxRates/select", e)).ToImmutableList<ITaxRate>();
}
public async Task<ImmutableList<ITaxRate>?> Query(QueryArgs? args)
{
return (await Http.Post<List<TaxRate>?>("http://localhost:5063/management/commonTypes/taxRates/query", args ?? QueryArgs.NoPaging)).ToImmutableList<ITaxRate>();
}
public async Task<ITaxRate?> Select(PrimaryKeyArgs<int> e)
{
return await Http.Post<TaxRate>("http://localhost:5063/management/commonTypes/taxRates/select", e);
}
public async Task<ITaxRate?> Select(TaxRateArgs e)
{
return await Http.Post<TaxRate>("http://localhost:5063/management/commonTypes/taxRates/select", e);
}
public async Task Update(UpdateTaxRateArgs e)
{
await Http.Post<TaxRate>("http://localhost:5063/management/commonTypes/taxRates/update", e);
}
}

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>Common.Types</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Framework\Connected.Middleware\Connected.Middleware.csproj" />
<ProjectReference Include="..\Common.Types.Model\Common.Types.Model.csproj" />
</ItemGroup>
</Project>

@ -0,0 +1,9 @@
using Common.Types.Currencies;
using Connected;
namespace Common.Types.Middleware.Currencies;
public interface ICurrencyFormatterMiddleware<TValue> : IMiddleware
{
Task<string?> Format(TValue value, ICurrency currency, string format);
}

@ -0,0 +1,32 @@
using Connected.Annotations;
using Connected.Data;
using Connected.ServiceModel;
using System.ComponentModel.DataAnnotations;
namespace Common.Types.BankAccounts;
public class BankAccountInsertArgs : Dto
{
[MinValue(1)]
public int Bank { get; set; }
[Required]
[MaxLength(128)]
public string? Iban { get; set; }
[Required]
[MaxLength(128)]
public string? Type { get; set; }
[Required]
[MaxLength(128)]
public string? PrimaryKey { get; set; }
public Status Status { get; set; } = Status.Enabled;
}
public sealed class BankAccountUpdateArgs : BankAccountInsertArgs
{
[MinValue(1)]
public int Id { get; set; }
}

@ -0,0 +1,12 @@
using Connected.Data;
namespace Common.Types.BankAccounts;
public interface IBankAccount : IPrimaryKey<int>
{
string Iban { get; init; }
Status Status { get; init; }
int Bank { get; init; }
string Type { get; init; }
string PrimaryKey { get; init; }
}

@ -0,0 +1,32 @@
using Connected.Annotations;
using Connected.Notifications;
using Connected.ServiceModel;
using System.Collections.Immutable;
namespace Common.Types.BankAccounts;
[Service]
[ServiceUrl(Routes.BankAccounts)]
public interface IBankAccountService : IServiceNotifications<int>
{
[ServiceMethod(ServiceMethodVerbs.Get)]
Task<ImmutableList<IBankAccount>?> Query();
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ImmutableList<IBankAccount>?> Query(PrimaryKeyArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ImmutableList<IBankAccount>?> Query(PrimaryKeyListArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<IBankAccount?> Select(PrimaryKeyArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Delete)]
Task Delete(PrimaryKeyArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Put)]
Task<int> Insert(BankAccountInsertArgs args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Put | ServiceMethodVerbs.Patch)]
Task Update(BankAccountUpdateArgs args);
}

@ -0,0 +1,28 @@
using Connected.Annotations;
using Connected.Data;
using Connected.ServiceModel;
using System.ComponentModel.DataAnnotations;
namespace Common.Types.Banks;
public class InsertBankArgs : Dto
{
[Required]
[MaxLength(128)]
public string? Name { get; set; }
[MinValue(1)]
public int Country { get; set; }
[Required]
[MaxLength(128)]
public string? Bic { get; set; }
public Status Status { get; set; } = Status.Enabled;
}
public class UpdateBankArgs : InsertBankArgs
{
[MinValue(1)]
public int Id { get; set; }
}

@ -0,0 +1,11 @@
using Connected.Data;
namespace Common.Types.Banks;
public interface IBank : IPrimaryKey<int>
{
string Name { get; init; }
int Country { get; init; }
string Bic { get; init; }
Status Status { get; init; }
}

@ -0,0 +1,29 @@
using Connected.Annotations;
using Connected.Notifications;
using Connected.ServiceModel;
using System.Collections.Immutable;
namespace Common.Types.Banks;
[Service]
[ServiceUrl(Routes.Banks)]
public interface IBankService : IServiceNotifications<int>
{
[ServiceMethod(ServiceMethodVerbs.Get)]
Task<ImmutableList<IBank>?> Query();
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ImmutableList<IBank>?> Query(PrimaryKeyListArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<IBank?> Select(PrimaryKeyArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Put)]
Task<int> Insert(InsertBankArgs args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Put | ServiceMethodVerbs.Patch)]
Task Update(UpdateBankArgs args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Delete)]
Task Delete(PrimaryKeyArgs<int> args);
}

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Common\Common.Model\Common.Model.csproj" />
<ProjectReference Include="..\..\Connected\Connected\Connected.csproj" />
</ItemGroup>
</Project>

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>Common.Types</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Common\Common.Model\Common.Model.csproj" />
<ProjectReference Include="..\..\Connected\Connected\Connected.csproj" />
</ItemGroup>
</Project>

@ -0,0 +1,18 @@
using Connected.Annotations;
using Connected.ServiceModel;
using System.ComponentModel.DataAnnotations;
namespace Common.Types.Continent;
public class InsertContinentArgs : Dto
{
[Required]
[MaxLength(128)]
public string? Name { get; set; }
}
public sealed class UpdateContitentArgs : InsertContinentArgs
{
[MinValue(1)]
public int Id { get; set; }
}

@ -0,0 +1,13 @@
using Connected.Annotations;
using Connected.ServiceModel;
namespace Common.Types.Continent.Countries;
public class InsertContinentCountryArgs : Dto
{
[MinValue(1)]
public int Continent { get; set; }
[MinValue(1)]
public int Country { get; set; }
}

@ -0,0 +1,9 @@
using Connected.Data;
namespace Common.Types.Continent.Countries;
public interface IContinentCountry : IPrimaryKey<int>
{
int Continent { get; init; }
int Country { get; init; }
}

@ -0,0 +1,34 @@
using Connected.Annotations;
using Connected.Notifications;
using Connected.ServiceModel;
using System.Collections.Immutable;
namespace Common.Types.Continent.Countries;
[Service]
[ServiceUrl(Routes.ContinentCountries)]
public interface IContinentCountryService : IServiceNotifications<int>
{
[ServiceMethod(ServiceMethodVerbs.Get)]
Task<ImmutableList<IContinentCountry>?> Query();
/// <summary>
/// Queries countries for the specified continent id.
/// </summary>
/// <param name="args">The id fo the continent.</param>
/// <returns>The list of countries.</returns>
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ImmutableList<IContinentCountry>?> QueryCountries(PrimaryKeyArgs<int> args);
/// <summary>
/// Select a <see cref="IContinentCountry"/> entity for the specified country id.
/// </summary>
/// <param name="args">The country id.</param>
/// <returns>The <see cref="IContinentCountry"/> entity if exists, <code>null</code> otherwise.</returns>
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<IContinentCountry> SelectCountry(PrimaryKeyArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Put)]
Task<int> Insert(InsertContinentCountryArgs args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Delete)]
Task Delete(PrimaryKeyArgs<int> args);
}

@ -0,0 +1,8 @@
using Connected.Data;
namespace Common.Types.Continent;
public interface IContinent : IPrimaryKey<int>
{
string Name { get; init; }
}

@ -0,0 +1,29 @@
using Connected.Annotations;
using Connected.Notifications;
using Connected.ServiceModel;
using System.Collections.Immutable;
namespace Common.Types.Continent;
[Service]
[ServiceUrl(Routes.Continents)]
public interface IContinentService : IServiceNotifications<int>
{
[ServiceMethod(ServiceMethodVerbs.Get)]
Task<ImmutableList<IContinent>?> Query();
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ImmutableList<IContinent>> Query(PrimaryKeyListArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<IContinent> Select(PrimaryKeyArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Put | ServiceMethodVerbs.Post)]
Task<int> Insert(InsertContinentArgs args);
[ServiceMethod(ServiceMethodVerbs.Put | ServiceMethodVerbs.Post | ServiceMethodVerbs.Patch)]
Task Update(UpdateContitentArgs args);
[ServiceMethod(ServiceMethodVerbs.Delete | ServiceMethodVerbs.Post)]
Task Delete(PrimaryKeyArgs<int> args);
}

@ -0,0 +1,27 @@
using Connected.Annotations;
using Connected.Data;
using Connected.ServiceModel;
using System.ComponentModel.DataAnnotations;
namespace Common.Types.Countries;
public class InsertCountryArgs : Dto
{
[Required]
[MaxLength(128)]
public string Name { get; set; }
[MinValue(0)]
public int Lcid { get; set; }
[MaxLength(128)]
public string? IsoCode { get; set; }
public Status Status { get; set; } = Status.Enabled;
}
public class UpdateCountryArgs : InsertCountryArgs
{
[MinValue(1)]
public int Id { get; set; }
}

@ -0,0 +1,11 @@
using Connected.Data;
namespace Common.Types.Countries;
public interface ICountry : IPrimaryKey<int>
{
string Name { get; init; }
int Lcid { get; init; }
string IsoCode { get; init; }
Status Status { get; init; }
}

@ -0,0 +1,33 @@
using Connected.Annotations;
using Connected.Notifications;
using Connected.ServiceModel;
using System.Collections.Immutable;
namespace Common.Types.Countries;
[Service]
[ServiceUrl(Routes.Countries)]
public interface ICountryService : IServiceNotifications<int>
{
[ServiceMethod(ServiceMethodVerbs.Get)]
Task<ImmutableList<ICountry>?> Query();
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ImmutableList<ICountry>?> Query(PrimaryKeyListArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ICountry?> Select(PrimaryKeyArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ICountry?> Select(NameArgs args);
[ServiceMethod(ServiceMethodVerbs.Delete | ServiceMethodVerbs.Post)]
Task Delete(PrimaryKeyArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Put | ServiceMethodVerbs.Post)]
Task<int> Insert(InsertCountryArgs args);
[ServiceMethod(ServiceMethodVerbs.Put | ServiceMethodVerbs.Post | ServiceMethodVerbs.Patch)]
Task Update(UpdateCountryArgs args);
}

@ -0,0 +1,40 @@
using Connected.Annotations;
using Connected.Data;
using Connected.ServiceModel;
using System.ComponentModel.DataAnnotations;
namespace Common.Types.Currencies;
public class CurrencyInsertArgs : Dto
{
[Required]
[MaxLength(128)]
public string? Name { get; set; }
[Required]
[MaxLength(32)]
public string? Code { get; set; }
[Required]
[MaxLength(8)]
public string? Symbol { get; set; }
[MinValue(0)]
public int Lcid { get; set; }
public Status Status { get; set; } = Status.Enabled;
}
public sealed class CurrencyUpdateArgs : CurrencyInsertArgs
{
[MinValue(1)]
public int Id { get; set; }
}
public sealed class CurrencyFormatArgs : Dto
{
[Range(0, int.MaxValue)]
public int Currency { get; set; }
public double Value { get; set; }
}

@ -0,0 +1,12 @@
using Connected.Data;
namespace Common.Types.Currencies;
public interface ICurrency : IPrimaryKey<int>
{
string Name { get; init; }
string Code { get; init; }
string Symbol { get; init; }
int Lcid { get; init; }
Status Status { get; init; }
}

@ -0,0 +1,32 @@
using Connected.Annotations;
using Connected.Notifications;
using Connected.ServiceModel;
using System.Collections.Immutable;
namespace Common.Types.Currencies;
[Service]
[ServiceUrl(Routes.Currencies)]
public interface ICurrencyService : IServiceNotifications<int>
{
[ServiceMethod(ServiceMethodVerbs.Get)]
Task<ImmutableList<ICurrency>> Query();
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ImmutableList<ICurrency>> Query(PrimaryKeyListArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ICurrency> Select(PrimaryKeyArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<string> Format(CurrencyFormatArgs args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Put)]
Task<int> Insert(CurrencyInsertArgs args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Patch | ServiceMethodVerbs.Put)]
Task Update(CurrencyUpdateArgs args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Delete)]
Task Delete(PrimaryKeyArgs<int> args);
}

@ -0,0 +1,11 @@
using Connected.Data;
namespace Common.Types.MeasureUnits;
public interface IMeasureUnit : IPrimaryKey<int>
{
string Name { get; init; }
string Code { get; init; }
byte Precision { get; init; }
Status Status { get; init; }
}

@ -0,0 +1,29 @@
using Connected.Annotations;
using Connected.Notifications;
using Connected.ServiceModel;
using System.Collections.Immutable;
namespace Common.Types.MeasureUnits;
[Service]
[ServiceUrl(Routes.MeasureUnits)]
public interface IMeasureUnitService : IServiceNotifications<int>
{
[ServiceMethod(ServiceMethodVerbs.Get)]
Task<ImmutableList<IMeasureUnit>?> Query();
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ImmutableList<IMeasureUnit>?> Query(PrimaryKeyListArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<IMeasureUnit?> Select(PrimaryKeyArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Delete)]
Task Delete(PrimaryKeyArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Put)]
Task<int> Insert(MeasureUnitInsertArgs args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Put | ServiceMethodVerbs.Patch)]
Task Update(MeasureUnitUpdateArgs args);
}

@ -0,0 +1,27 @@
using Connected.Data;
using Connected.ServiceModel;
using System.ComponentModel.DataAnnotations;
namespace Common.Types.MeasureUnits;
public class MeasureUnitInsertArgs : Dto
{
[Required]
[MaxLength(128)]
public string? Name { get; set; }
[Required]
[MaxLength(8)]
public string? Code { get; set; }
[Range(0, 32)]
public byte Precision { get; set; }
public Status Status { get; set; } = Status.Enabled;
}
public sealed class MeasureUnitUpdateArgs : MeasureUnitInsertArgs
{
[Range(1, int.MaxValue)]
public int Id { get; set; }
}

@ -0,0 +1,7 @@
using System.Runtime.CompilerServices;
using Connected.Annotations;
[assembly: MicroService(MicroServiceType.Contract)]
[assembly: InternalsVisibleTo("Common.Types.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

@ -0,0 +1,11 @@
using Connected.Data;
namespace Common.Types.PostalCodes;
public interface IPostalCode : IPrimaryKey<int>
{
int Country { get; init; }
string Name { get; init; }
string Code { get; init; }
Status Status { get; init; }
}

@ -0,0 +1,35 @@
using Connected.Annotations;
using Connected.Notifications;
using Connected.ServiceModel;
using System.Collections.Immutable;
namespace Common.Types.PostalCodes;
[Service]
[ServiceUrl(Routes.PostalCodes)]
public interface IPostalCodeService : IServiceNotifications<int>
{
[ServiceMethod(ServiceMethodVerbs.Get)]
Task<ImmutableList<IPostalCode>?> Query();
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ImmutableList<IPostalCode>?> Query(PrimaryKeyListArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ImmutableList<IPostalCode>?> Query(PrimaryKeyArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ImmutableList<IPostalCode>?> Search(PostalCodeSearchArgs args);
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<IPostalCode> Select(PrimaryKeyArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Delete)]
Task Delete(PrimaryKeyArgs<int> args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Put)]
Task<int> Insert(PostalCodeInsertArgs args);
[ServiceMethod(ServiceMethodVerbs.Post | ServiceMethodVerbs.Put | ServiceMethodVerbs.Patch)]
Task Update(PostalCodeInsertArgs args);
}

@ -0,0 +1,40 @@
using Connected.Annotations;
using Connected.Data;
using Connected.ServiceModel;
using System.ComponentModel.DataAnnotations;
namespace Common.Types.PostalCodes;
public class PostalCodeInsertArgs : Dto
{
[MinValue(1)]
public int Country { get; set; }
[Required]
[MaxLength(128)]
public string? Name { get; set; }
[Required]
[MaxLength(16)]
public string? Code { get; set; }
public Status Status { get; set; } = Status.Enabled;
}
public sealed class PostalCodeUpdateArgs : PostalCodeInsertArgs
{
[Range(1, int.MaxValue)]
public int Id { get; set; }
}
public sealed class PostalCodeSearchArgs : Dto
{
[Range(0, int.MaxValue)]
public int Country { get; set; }
[MaxLength(128)]
public string? Name { get; set; }
[MaxLength(16)]
public string? Code { get; set; }
}

@ -0,0 +1,19 @@
using C = Common.CommonRoutes;
namespace Common.Types
{
public static class Routes
{
public const string CommonTypes = "commonTypes";
public const string TaxRates = $"{C.Management}/{CommonTypes}/taxRates";
public const string Countries = $"{C.Management}/{CommonTypes}/countries";
public const string Continents = $"{C.Management}/{CommonTypes}/continents";
public const string ContinentCountries = $"{C.Management}/{CommonTypes}/continents/countries";
public const string Banks = $"{C.Management}/{CommonTypes}/banks";
public const string BankAccounts = $"{C.Management}/{CommonTypes}/bankAccounts";
public const string Currencies = $"{C.Management}/{CommonTypes}/currencies";
public const string PostalCodes = $"{C.Management}/{CommonTypes}/postalCodes";
public const string MeasureUnits = $"{C.Management}/{CommonTypes}/measureUnits";
}
}

@ -0,0 +1,36 @@
using Connected.Data;
namespace Common.Types.TaxRates;
/// <summary>
/// Represents an entity which contains information about tax rate.
/// </summary>
/// <remarks>
/// Every Tax system has one or more tax rates, for example one tax rate is for
/// products and the other is for servies. This entity enables the environment
/// to manage different tax rates.
/// </remarks>
public interface ITaxRate : IPrimaryKey<int>
{
/// <summary>
/// The name of the tax rate.
/// </summary>
/// <remarks>
/// Define this value as descriptive as possible so users can
/// quickly recognize whyt kind of tax rate defines each record.
/// </remarks>
string? Name { get; init; }
/// <summary>
/// The rate or value of the tax rate. Should be a positive number.
/// </summary>
/// <remarks>
/// Avoid updating this value. Create a new <see cref="ITaxRate"/> entity instead
/// and disable the previous entity by setting its <see cref="Status"/> value to <see cref="Status.Disabled"/>.
/// </remarks>
float Rate { get; init; }
/// <summary>
/// The status of tax rate. Tax rates that are not used in the environment should be marked
/// as <see cref="Status.Disabled"/> so users can use only valid records.
/// </summary>
Status Status { get; init; }
}

@ -0,0 +1,63 @@
using System.Collections.Immutable;
using Connected.Annotations;
using Connected.Notifications;
using Connected.ServiceModel;
namespace Common.Types.TaxRates;
/// <summary>
/// The service used to manipulate with the <see cref="ITaxRate"/> entity.
/// </summary>
[Service]
[ServiceUrl(Routes.TaxRates)]
public interface ITaxRateService : IServiceNotifications<int>
{
/// <summary>
/// Queries all valid <see cref="ITaxRate"/> entities.
/// </summary>
/// <returns>An <see cref="ImmutableList{T}"/> representing all valid entities.</returns>
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ImmutableList<ITaxRate>?> Query(QueryArgs? args);
/// <summary>
/// Performs a lookup on <see cref="ITaxRate"/> entities for the specified list of ids.
/// </summary>
/// <param name="e">The List of the ids for which the perform a query.</param>
/// <returns>An <see cref="ImmutableList{T}"/> of <see cref="ITaxRate"/> entities that matches
/// the passed ids.</returns>
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ImmutableList<ITaxRate>?> Query(PrimaryKeyListArgs<int> e);
/// <summary>
/// Selects an <see cref="ITaxRate"/> entity for the specified id.
/// </summary>
/// <param name="e">The <see cref="IPrimaryKeyArgs{T}"/> which contains id.</param>
/// <returns>First <see cref="ITaxRate"/> that matches the arguments. </returns>
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ITaxRate?> Select(PrimaryKeyArgs<int> e);
/// <summary>
/// Selects an <see cref="ITaxRate"/> for the specified <see cref="TaxRateArgs"/> arguments.
/// </summary>
/// <param name="e">The <see cref="TaxRateArgs"/> arguments for which the <see cref="ITaxRate"/> entity
/// will be returned.</param>
/// <returns>First <see cref="ITaxRate"/> that matches the arguments.</returns>
[ServiceMethod(ServiceMethodVerbs.Get | ServiceMethodVerbs.Post)]
Task<ITaxRate?> Select(TaxRateArgs e);
/// <summary>
/// Inserts a new <see cref="ITaxRate"/> entity.
/// </summary>
/// <returns>
/// An Id of the newly inserted entity.
/// </returns>
[ServiceMethod(ServiceMethodVerbs.Post)]
Task<int> Insert(InsertTaxRateArgs e);
/// <summary>
/// Updates <see cref="ITaxRate"/> entity.
/// </summary>
/// <param name="e">The <see cref="TaxRateArgs"/> containing values to be updated.</param>
[ServiceMethod(ServiceMethodVerbs.Post)]
Task Update(UpdateTaxRateArgs e);
/// <summary>
/// Deletes <see cref="ITaxRate"/> entity.
/// </summary>
[ServiceMethod(ServiceMethodVerbs.Delete | ServiceMethodVerbs.Post)]
Task Delete(PrimaryKeyArgs<int> e);
}

@ -0,0 +1,45 @@
using Connected.Annotations;
using Connected.ServiceModel;
using System.ComponentModel.DataAnnotations;
namespace Common.Types.TaxRates;
/// <summary>
/// The arguments class for <see cref="ITaxRateService"/> methods.
/// </summary>
public class TaxRateArgs : Dto
{
/// <summary>
/// The <see cref="ITaxRate"/> name.
/// </summary>
/// <remarks>
/// This is a required property with its max length of 128 characters.
/// </remarks>
[Required]
[MaxLength(128)]
public string? Name { get; set; }
/// <summary>
/// The <see cref="ITaxRate"/> rate.
/// </summary>
/// <remarks>
/// This is a required property with it min value of 0.
/// </remarks>
[MinValue(0)]
public float Rate { get; set; }
}
/// <summary>
/// The arguments used when inserting a new <see cref="ITaxRate"/> entity.
/// This is only a markup class serving primary for validation distinction.
/// </summary>
public sealed class InsertTaxRateArgs : TaxRateArgs
{
}
/// <summary>
/// The arguments class used when updating <see cref="ITaxRate"/> entity.
/// </summary>
public class UpdateTaxRateArgs : TaxRateArgs
{
[MinValue(0)]
public int Id { get; set; }
}

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<RootNamespace>Common.Types</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.2.0" />
<PackageReference Include="moq" Version="4.18.2" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.10" />
<PackageReference Include="MSTest.TestFramework" Version="2.2.10" />
<PackageReference Include="coverlet.collector" Version="3.1.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common.Types\Common.Types.csproj" />
</ItemGroup>
</Project>

@ -0,0 +1,61 @@
using Moq;
namespace Common.Types;
internal class InstanceFaker<T>
{
private readonly Dictionary<Type, Mock> _mocks = new();
private bool _mocksGenerated = false;
public InstanceFaker()
{
if (typeof(T).GetConstructors().Length > 1)
throw new Exception($"Multiple constructors for type {typeof(T).FullName} found. Auto resolve not possible.");
GenerateMocks();
}
private void GenerateMocks()
{
if (_mocksGenerated)
return;
_mocksGenerated = true;
var constructor = typeof(T).GetConstructors()[0];
var parameters = constructor.GetParameters();
foreach (var parameter in parameters)
{
if (!parameter.ParameterType.IsInterface)
throw new Exception($"Constructor parameter {parameter.Name} of type {parameter.ParameterType.FullName} is not an interface, cannot mock.");
_mocks.Add(parameter.ParameterType, CreateMock(parameter.ParameterType));
}
}
private T ProcessType()
{
GenerateMocks();
var constructor = typeof(T).GetConstructors()[0];
var mocks = _mocks.Select(e => e.Value.Object);
return (T)constructor.Invoke(mocks.Cast<object>().ToArray());
}
private Mock? CreateMock(Type type)
{
var creator = typeof(Mock<>).MakeGenericType(type);
return Activator.CreateInstance(creator) as Mock;
}
public Mock<T>? GetMock<T>()
where T : class => _mocks.GetValueOrDefault(typeof(T)) as Mock<T>;
private T _instance;
public T Instance => _instance ??= ProcessType();
}

@ -0,0 +1,189 @@
using Connected.Entities;
using Connected.Entities.Storage;
using Connected.Notifications.Events;
using Connected.ServiceModel;
using Connected.ServiceModel.Transactions;
using Moq;
using static Common.Types.TaxRates.TaxRateOps;
namespace Common.Types.TaxRates.Ops;
public class DeleteTests
{
[TestClass]
public class OnInvoke
{
[TestMethod("Delete invoke calls update with state as deleted")]
public async Task Delete_Invoke_CallsUpdateWithStateDeleted()
{
/*
* Setup
*/
var expectedValue = State.Deleted;
var actualValue = (State)0;
/*
* Required services
*/
var instanceFaker = new InstanceFaker<Delete>();
var databaseContextProviderFake = instanceFaker.GetMock<IStorageProvider>()!;
_ = databaseContextProviderFake
.Setup(e => e.Open<TaxRate>().Update(It.IsAny<TaxRate>()))
.Callback<TaxRate>(e => actualValue = e.State)
.ReturnsAsync(new TaxRate { Id = 1 });
/*
* Arguments play no role for this test
*/
var args = new PrimaryKeyArgs<int>(1);
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
await serviceFunction.Invoke(args);
/*
* Assert
*/
databaseContextProviderFake.Verify(e => e.Open<TaxRate>().Update(It.IsAny<TaxRate>()), Times.Exactly(1));
Assert.AreEqual(expectedValue, actualValue);
}
[TestMethod("Delete invoke correctly maps values to entity")]
public async Task Delete_Invoke_MapsArgumentsCorrectly()
{
/*
* Setup
*/
var expectedId = 1;
var actualValue = int.MinValue;
/*
* Required services
*/
var instanceFaker = new InstanceFaker<Delete>();
var databaseContextProviderFake = instanceFaker.GetMock<IStorageProvider>()!;
_ = databaseContextProviderFake
.Setup(e => e.Open<TaxRate>().Update(It.IsAny<TaxRate>()))
.Callback<TaxRate>(e => actualValue = e.Id)
.ReturnsAsync(new TaxRate { Id = expectedId });
/*
* Arguments play no role for this test
*/
var args = new PrimaryKeyArgs<int>(expectedId);
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
await serviceFunction.Invoke(args);
/*
* Assert
*/
databaseContextProviderFake.Verify(e => e.Open<TaxRate>().Update(It.IsAny<TaxRate>()), Times.Exactly(1));
Assert.AreEqual(expectedId, actualValue);
}
}
[TestClass]
public class OnCommit
{
[TestMethod("Delete commit invokes deleted event exactly once")]
public async Task Delete_Commit_InvokedDeleted_ExactlyOnce()
{
/*
* Setup
*/
var instanceFaker = new InstanceFaker<Delete>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
_ = taxRateCacheFake.Setup(e => e.Refresh(It.IsAny<int>()));
var eventServiceFake = instanceFaker.GetMock<IEventService>()!;
_ = eventServiceFake.SetupEvent<ITaxRateService, int>(ServiceEvents.Deleted);
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
serviceFunction.SetArguments(new PrimaryKeyArgs<int>(1));
await ((ITransactionClient)serviceFunction).Commit();
/*
* Assert
*/
eventServiceFake.VerifyEvent<ITaxRateService, int>(ServiceEvents.Deleted);
}
[TestMethod("Delete commit removes cache exactly once")]
public async Task Delete_Commit_RemovesCache_ExactlyOnce()
{
/*
* Setup
*/
var instanceFaker = new InstanceFaker<Delete>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
_ = taxRateCacheFake.Setup(e => e.Remove(It.IsAny<int>()));
var eventServiceFake = instanceFaker.GetMock<IEventService>()!;
_ = eventServiceFake.SetupEvent<ITaxRateService, int>(ServiceEvents.Deleted);
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
serviceFunction.SetArguments(new PrimaryKeyArgs<int>(1));
await ((ITransactionClient)serviceFunction).Commit();
/*
* Assert
*/
taxRateCacheFake.Verify(e => e.Remove(It.IsAny<int>()), Times.Exactly(1));
}
[TestMethod("Delete commit fires deleted event after notifying cache")]
public async Task Delete_Commit_InvokedDeletedEvent_AfterNotifyingCache()
{
/*
* Setup
*
* If you receive an error about function calls not properly set up, and function
* calls look ok, it's probably the sequence throwing the exception. This is a
* failure in user code, not the test.
*/
var sequence = new MockSequence();
var instanceFaker = new InstanceFaker<Delete>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
_ = taxRateCacheFake
.InSequence(sequence)
.Setup(e => e.Remove(It.IsAny<int>()));
var eventServiceFake = instanceFaker.GetMock<IEventService>()!;
_ = eventServiceFake
.InSequence(sequence)
.SetupEvent<ITaxRateService, int>(ServiceEvents.Deleted);
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
serviceFunction.SetArguments(new PrimaryKeyArgs<int>(1));
await ((ITransactionClient)serviceFunction).Commit();
/*
* Assert
*/
taxRateCacheFake.Verify(e => e.Remove(It.IsAny<int>()), Times.Exactly(1));
eventServiceFake.VerifyEvent<ITaxRateService, int>(ServiceEvents.Deleted);
}
}
}

@ -0,0 +1,269 @@
using Connected.Data;
using Connected.Entities;
using Connected.Entities.Annotations;
using Connected.Entities.Storage;
using Connected.Notifications.Events;
using Connected.ServiceModel;
using Connected.ServiceModel.Transactions;
using Moq;
using System.Reflection;
using static Common.Types.TaxRates.TaxRateOps;
namespace Common.Types.TaxRates.Ops;
public class InsertTests
{
[TestClass]
public class OnInvoke
{
[TestMethod("Insert invoke returns inserted id")]
public async Task Insert_Invoke_ReturnsInsertedId()
{
/*
* Setup
*/
var expectedId = 1;
/*
* Required services
*/
var instanceFaker = new InstanceFaker<Insert>();
var databaseContextProviderFake = instanceFaker.GetMock<IStorageProvider>()!;
_ = databaseContextProviderFake
.Setup(e => e.Open<TaxRate>().Update(It.IsAny<TaxRate>()))
.ReturnsAsync(new TaxRate { Id = expectedId });
/*
* Arguments play no role for this test
*/
var args = new InsertTaxRateArgs { };
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.AreEqual(result, expectedId);
databaseContextProviderFake.Verify(e => e.Open<TaxRate>().Update(It.IsAny<TaxRate>()), Times.Exactly(1));
}
[TestMethod("Insert invoke inserts exactly one new value")]
public async Task Insert_Invoke_InsertsNewValue_ExactlyOnce()
{
/*
* Setup
*/
var expectedId = 1;
/*
* Required services
*/
var instanceFaker = new InstanceFaker<Insert>();
var databaseContextProviderFake = instanceFaker.GetMock<IStorageProvider>()!;
_ = databaseContextProviderFake
.Setup(e => e.Open<TaxRate>().Update(It.Is<TaxRate>(e => e.State == State.New)))
.ReturnsAsync(new TaxRate { Id = expectedId });
/*
* Arguments play no role for this test
*/
var args = new InsertTaxRateArgs();
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
databaseContextProviderFake.Verify(e => e.Open<TaxRate>().Update(It.IsAny<TaxRate>()), Times.Exactly(1));
}
[TestMethod("Insert invoke correctly maps values to entity")]
public async Task Insert_Invoke_MapsArgumentsCorrectly()
{
/*
* Setup
*/
var expectedEntity = new TaxRate
{
Name = "TaxRate",
Rate = 1.0f,
};
/*
* Required services
*/
var actualEntity = null as TaxRate;
var instanceFaker = new InstanceFaker<Insert>();
var databaseContextProviderFake = instanceFaker.GetMock<IStorageProvider>()!;
_ = databaseContextProviderFake
.Setup(e => e.Open<TaxRate>().Update(It.IsAny<TaxRate>()))
.Callback<TaxRate>(e => actualEntity = e)
.ReturnsAsync(expectedEntity with { Id = 1 });
var args = new InsertTaxRateArgs
{
Name = expectedEntity.Name,
Rate = expectedEntity.Rate
};
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
databaseContextProviderFake.Verify(e => e.Open<TaxRate>().Update(It.IsAny<TaxRate>()), Times.Exactly(1));
Assert.AreEqual(expectedEntity.Name, actualEntity?.Name);
Assert.AreEqual(expectedEntity.Rate, actualEntity?.Rate);
}
[TestMethod("Insert invoke sets status to enabled or default")]
public async Task Insert_Invoke_SetsStatusToEnabledOrDefault()
{
/*
* Setup
* Valid values are Enabled or Default (db provider sets it to enabled then)
*/
var expectedStatuses = new[] { Status.Enabled }.ToList();
/*
* Check if the default value for the status field is enabled. If so, add 0 to the expected values list.
*/
var defaultValueAttributes = typeof(TaxRate).GetProperty(nameof(TaxRate.Status))!.GetCustomAttributes<DefaultAttribute>(true);
if (defaultValueAttributes.Any())
{
var values = defaultValueAttributes.Select(e => (Status)e.Value!).ToList();
if (values.Any(e => e == Status.Enabled))
expectedStatuses.Add(0);
}
/*
* Required services
*/
var actualStatus = (Status)0;
var instanceFaker = new InstanceFaker<Insert>();
var databaseContextProviderFake = instanceFaker.GetMock<IStorageProvider>()!;
_ = databaseContextProviderFake
.Setup(e => e.Open<TaxRate>().Update(It.IsAny<TaxRate>()))
.Callback<TaxRate>(e => actualStatus = e.Status)
.ReturnsAsync(new TaxRate { Id = 1 });
/*
* Arguments play no role for this test
*/
var args = new InsertTaxRateArgs();
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
databaseContextProviderFake.Verify(e => e.Open<TaxRate>().Update(It.IsAny<TaxRate>()), Times.Exactly(1));
Assert.IsTrue(expectedStatuses.Contains(actualStatus));
}
}
[TestClass]
public class OnCommit
{
[TestMethod("Insert commit invokes inserted event exactly once")]
public async Task Insert_Commit_InvokedInserted_ExactlyOnce()
{
/*
* Setup
*/
var instanceFaker = new InstanceFaker<Insert>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
_ = taxRateCacheFake.Setup(e => e.Refresh(It.IsAny<int>()));
var eventServiceFake = instanceFaker.GetMock<IEventService>()!;
_ = eventServiceFake.Setup(e => e.Enqueue(It.IsAny<ITaxRateService?>(), ServiceEvents.Inserted, It.IsAny<int>()));
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
await ((ITransactionClient)serviceFunction).Commit();
/*
* Assert
*/
eventServiceFake.Verify(e => e.Enqueue(It.IsAny<ITaxRateService?>(), ServiceEvents.Inserted, It.IsAny<int>()), Times.Exactly(1));
}
[TestMethod("Insert commit refreshes cache exactly once")]
public async Task Insert_Commit_RefreshesCache_ExactlyOnce()
{
/*
* Setup
*/
var instanceFaker = new InstanceFaker<Insert>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
_ = taxRateCacheFake.Setup(e => e.Refresh(It.IsAny<int>()));
var eventServiceFake = instanceFaker.GetMock<IEventService>()!;
_ = eventServiceFake.Setup(e => e.Enqueue(It.IsAny<ITaxRateService?>(), ServiceEvents.Inserted, It.IsAny<int>()));
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
await ((ITransactionClient)serviceFunction).Commit();
/*
* Assert
*/
taxRateCacheFake.Verify(e => e.Refresh(It.IsAny<int>()), Times.Exactly(1));
}
[TestMethod("Insert commit fires inserted event after notifying cache")]
public async Task Insert_Commit_InvokedInsertedEvent_AfterNotifyingCache()
{
/*
* Setup
* Mockbehavior string ensures no unplanned functions are called on the services.
* If you receive an error about function calls not properly set up, and function
* calls look ok, it's probably the sequence throwing the exception. This is a
* failure in user code, not the test.
*/
var sequence = new MockSequence();
var instanceFaker = new InstanceFaker<Insert>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
_ = taxRateCacheFake
.InSequence(sequence)
.Setup(e => e.Refresh(It.IsAny<int>()));
var eventServiceFake = instanceFaker.GetMock<IEventService>()!;
_ = eventServiceFake
.InSequence(sequence)
.Setup(e => e.Enqueue(It.IsAny<ITaxRateService?>(), ServiceEvents.Inserted, It.IsAny<int>()));
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
await ((ITransactionClient)serviceFunction).Commit();
/*
* Assert
*/
taxRateCacheFake.Verify(e => e.Refresh(It.IsAny<int>()), Times.Exactly(1));
eventServiceFake.Verify(e => e.Enqueue(It.IsAny<ITaxRateService?>(), ServiceEvents.Inserted, It.IsAny<int>()));
}
}
}

@ -0,0 +1,241 @@
using Connected.Entities;
using Connected.ServiceModel;
using System.Collections.Immutable;
using System.Data;
using Lookup = Common.Types.TaxRates.TaxRateOps.Lookup;
namespace Common.Types.TaxRates.Ops;
[TestClass]
public class LookupTests
{
[TestMethod("Lookup invoke returns ImmutableList when set is empty")]
public async Task Lookup_Invoke_ReturnsImmutableList_WhenEmpty()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.GetEmptyTaxRateSet();
var instanceFaker = new InstanceFaker<Lookup>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet!);
var args = new PrimaryKeyListArgs<int>();
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.IsNotNull(result);
Assert.IsTrue(result.GetType().IsAssignableToGenericType(typeof(ImmutableList<>)));
}
[TestMethod("Lookup invoke returns empty set when argument list is empty")]
public async Task Lookup_Invoke_ReturnsEmptyImmutableList_WhenArgumentListEmpty()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.CombinedTaxRateSet;
var instanceFaker = new InstanceFaker<Lookup>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet!);
var args = new PrimaryKeyListArgs<int>
{
IdList = new List<int>()
};
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.IsNotNull(result);
Assert.IsTrue(result.Count == 0);
}
[TestMethod("Lookup invoke returns empty set when argument list is invalid")]
public async Task Lookup_Invoke_ReturnsEmptyImmutableList_WhenArgumentListInvalid()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.CombinedTaxRateSet;
var instanceFaker = new InstanceFaker<Lookup>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet!);
var args = new PrimaryKeyListArgs<int>();
/*
* Test
*/
var serviceFunction = new Lookup(taxRateCacheFake.Object);
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.IsNotNull(result);
Assert.IsTrue(result.Count == 0);
}
[TestMethod("Lookup invoke returns correct set when argument list is valid")]
public async Task Lookup_Invoke_ReturnsCorrectSet_WhenArgumentListValid()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.CombinedTaxRateSet;
var instanceFaker = new InstanceFaker<Lookup>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet!);
var args = new PrimaryKeyListArgs<int>
{
IdList = new[]
{
TaxRateSamples.NotModifiedEnabled.Id,
TaxRateSamples.NewEnabled.Id,
TaxRateSamples.NotModifiedDisabled.Id
}
};
var expected = new[]
{
TaxRateSamples.NotModifiedEnabled,
TaxRateSamples.NewEnabled,
TaxRateSamples.NotModifiedDisabled
};
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.IsNotNull(result);
Assert.IsTrue(result.SequenceEquivalent(expected));
}
[TestMethod("Lookup invoke returns correct set when argument list contains deleted values")]
public async Task Lookup_Invoke_ReturnsCorrectSet_WhenArgumentListContainsDeletedValues()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.CombinedTaxRateSet;
var instanceFaker = new InstanceFaker<Lookup>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet!);
var args = new PrimaryKeyListArgs<int>
{
IdList = new[]
{
TaxRateSamples.NotModifiedEnabled.Id,
TaxRateSamples.DeletedEnabled.Id
}
};
var expected = new[]
{
TaxRateSamples.NotModifiedEnabled
};
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.IsNotNull(result);
Assert.IsTrue(result.SequenceEquivalent(expected));
}
[TestMethod("Lookup invoke returns all entries when no entries are deleted")]
public async Task Lookup_Invoke_ReturnsAllEntries_WhenNoEntriesAreDeleted()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.GetTaxRates(State.Default)
.Union(TaxRateSamples.GetTaxRates(State.New));
var instanceFaker = new InstanceFaker<Lookup>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet!);
var args = new PrimaryKeyListArgs<int>
{
IdList = dataSet.Select(e => e.Id)
};
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.IsNotNull(result);
Assert.IsTrue(result.SequenceEqual(dataSet));
}
[TestMethod("Lookup invoke returns only non deleted entries when entries are deleted")]
public async Task Lookup_Invoke_ReturnsNonDeletedOnly_WhenEntriesAreDeleted()
{
/*
* Setup
*/
var expectedDataSet = TaxRateSamples.GetTaxRates(State.Default)
.Union(TaxRateSamples.GetTaxRates(State.New));
var completeDataSet = expectedDataSet.Union(TaxRateSamples.GetTaxRates(State.Deleted));
var instanceFaker = new InstanceFaker<Lookup>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(completeDataSet);
var args = new PrimaryKeyListArgs<int>
{
IdList = completeDataSet.Select(e => e.Id)
};
/*
* Test
*/
var serviceFunction = new Lookup(taxRateCacheFake.Object);
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.IsNotNull(result);
Assert.IsTrue(result.SequenceEqual(expectedDataSet));
}
}

@ -0,0 +1,96 @@
using Connected.Entities;
using Connected.ServiceModel;
using System.Collections.Immutable;
using static Common.Types.TaxRates.TaxRateOps;
namespace Common.Types.TaxRates.Ops;
[TestClass]
public class QueryTests
{
[TestMethod("Query invoke returns ImmutableList when set is empty")]
public async Task Query_Invoke_ReturnsImmutableList_WhenEmpty()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.GetEmptyTaxRateSet();
var instanceFaker = new InstanceFaker<Query>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet!);
var args = QueryArgs.Default;
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.IsNotNull(result);
Assert.IsTrue(result.GetType().IsAssignableToGenericType(typeof(ImmutableList<>)));
}
[TestMethod("Query invoke returns all entries when no entries are deleted")]
public async Task Query_Invoke_ReturnsAllEntries_WhenNoEntriesAreDeleted()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.GetTaxRates(State.Default)
.Union(TaxRateSamples.GetTaxRates(State.New));
var instanceFaker = new InstanceFaker<Query>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet!);
var args = Dto.Empty;
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(QueryArgs.Default);
/*
* Assert
*/
Assert.IsNotNull(result);
Assert.IsTrue(result.SequenceEqual(dataSet));
}
[TestMethod("Query invoke returns only non deleted entries when entries are deleted")]
public async Task Query_Invoke_ReturnsNonDeletedOnly_WhenEntriesAreDeleted()
{
/*
* Setup
*/
var expectedDataSet = TaxRateSamples.GetTaxRates(State.Default)
.Union(TaxRateSamples.GetTaxRates(State.New));
var deletedDataSet = expectedDataSet.Union(TaxRateSamples.GetTaxRates(State.Deleted));
var instanceFaker = new InstanceFaker<Query>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(deletedDataSet);
var args = Dto.Empty;
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(QueryArgs.Default);
/*
* Assert
*/
Assert.IsNotNull(result);
Assert.IsTrue(result.SequenceEqual(expectedDataSet));
}
}

@ -0,0 +1,176 @@
using Connected.Entities;
using static Common.Types.TaxRates.TaxRateOps;
namespace Common.Types.TaxRates.Ops;
[TestClass]
public class SelectByRateTests
{
private static IEnumerable<object[]> TaxRates => TaxRateSamples.CombinedTaxRateSet
.Select(e => new object[] { e.Rate, e })
.ToList();
private static IEnumerable<object[]> DeletedTaxRates => TaxRateSamples.CombinedTaxRateSet
.Where(e => e.State == State.Deleted)
.Select(e => new object[] { e.Rate, e })
.ToList();
[TestMethod("SelectByRate invoke returns null when rate does not exist")]
public async Task Select_Invoke_ReturnsNull_WhenRateInvalid()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.CombinedTaxRateSet;
var instanceFaker = new InstanceFaker<SelectByRate>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet);
/*
* Ensure id is always out of range
*/
var outOfRangeRate = dataSet.Select(e => e.Rate).DefaultIfEmpty(0).Max() + 1;
var args = new TaxRateArgs
{
Rate = outOfRangeRate
};
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.IsNull(result);
}
[TestMethod("SelectByRate invoke returns null when rate not specified")]
public async Task Select_Invoke_ReturnsNull_WhenRateNotSpecified()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.CombinedTaxRateSet;
var instanceFaker = new InstanceFaker<SelectByRate>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet);
/*
* Ensure id is always out of range
*/
var args = new TaxRateArgs();
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.IsNull(result);
}
[TestMethod("SelectByRate invoke returns null when set is empty")]
public async Task Select_Invoke_ReturnsNull_WhenSetEmpty()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.GetEmptyTaxRateSet();
var instanceFaker = new InstanceFaker<SelectByRate>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet);
var args = new TaxRateArgs
{
Rate = 1
};
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.IsNull(result);
}
[TestMethod("SelectByRate invoke returns value when rate exists")]
[DynamicData(nameof(TaxRates))]
public async Task Select_Invoke_ReturnsValue_WhenRateValid(float rate, ITaxRate expected)
{
/*
* Setup
*/
var dataSet = TaxRates
.Select(e => e[1] as TaxRate)
.ToList();
var instanceFaker = new InstanceFaker<SelectByRate>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet);
/*
* Ensure id is always out of range
*/
var args = new TaxRateArgs
{
Rate = rate
};
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.AreSame(result, expected);
}
[TestMethod("Select invoke returns null value when rate exists but is deleted")]
[DynamicData(nameof(DeletedTaxRates))]
public async Task Select_Invoke_ReturnsNull_WhenRateValidAndDeleted(float rate)
{
/*
* Setup
*/
var dataSet = TaxRates
.Select(e => e[1] as TaxRate)
.ToList();
var instanceFaker = new InstanceFaker<SelectByRate>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet);
/*
* Ensure id is always out of range
*/
var args = new TaxRateArgs
{
Rate = rate
};
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.IsNull(result);
}
}

@ -0,0 +1,139 @@
using Connected.Entities;
using Connected.ServiceModel;
using static Common.Types.TaxRates.TaxRateOps;
namespace Common.Types.TaxRates.Ops;
[TestClass]
public class SelectTests
{
private static IEnumerable<object[]> TaxRates => TaxRateSamples.CombinedTaxRateSet
.Select(e => new object[] { e.Id, e })
.ToList();
private static IEnumerable<object[]> DeletedTaxRates => TaxRateSamples.CombinedTaxRateSet
.Where(e => e.State == State.Deleted)
.Select(e => new object[] { e.Id, e })
.ToList();
[TestMethod("Select invoke returns null when id does not exist")]
public async Task Select_Invoke_ReturnsNull_WhenIdInvalid()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.CombinedTaxRateSet;
var instanceFaker = new InstanceFaker<Select>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
_ = taxRateCacheFake
.As<IEnumerable<TaxRate>>()
.Setup(e => e.GetEnumerator())
.Returns(dataSet.GetEnumerator());
/*
* Ensure id is always out of range
*/
var outOfRangeId = dataSet.Select(e => e.Id).DefaultIfEmpty(0).Max() + 1;
var args = new PrimaryKeyArgs<int>(outOfRangeId);
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.IsNull(result);
}
[TestMethod("Select invoke returns null when set is empty")]
public async Task Select_Invoke_ReturnsNull_WhenSetEmpty()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.GetEmptyTaxRateSet();
var instanceFaker = new InstanceFaker<Select>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
_ = taxRateCacheFake
.As<IEnumerable<TaxRate>>()
.Setup(e => e.GetEnumerator())
.Returns(dataSet.GetEnumerator());
/*
* Ensure id is always out of range
*/
var args = new PrimaryKeyArgs<int>(1);
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.IsNull(result);
}
[TestMethod("Select invoke returns value when id exists")]
[DynamicData(nameof(TaxRates))]
public async Task Select_Invoke_ReturnsValue_WhenIdValid(int id, ITaxRate expected)
{
/*
* Setup
*/
var dataSet = TaxRates.Select(e => e[1] as TaxRate).ToList();
var instanceFaker = new InstanceFaker<Select>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet!);
/*
* Ensure id is always out of range
*/
var args = new PrimaryKeyArgs<int>(id);
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.AreSame(result, expected);
}
[TestMethod("Select invoke returns deleted value when id exists")]
[DynamicData(nameof(DeletedTaxRates))]
public async Task Select_Invoke_ReturnsDeletedValue_WhenIdValid(int id, ITaxRate expected)
{
/*
* Setup
*/
var dataSet = TaxRates.Select(e => e[1] as TaxRate).ToList();
var instanceFaker = new InstanceFaker<Select>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable<TaxRate>(dataSet!);
/*
* Ensure id is always out of range
*/
var args = new PrimaryKeyArgs<int>(id);
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
var result = await serviceFunction.Invoke(args);
/*
* Assert
*/
Assert.AreSame(result, expected);
}
}

@ -0,0 +1,74 @@
using Connected.Entities;
namespace Common.Types.TaxRates.Ops;
internal class TaxRateSamples
{
internal static IEnumerable<TaxRate> GetEmptyTaxRateSet() => new List<TaxRate> { };
internal static IEnumerable<TaxRate> GetTaxRates(State state) => CombinedTaxRateSet.Where(e => e.State == state);
public static TaxRate NewEnabled = new()
{
Id = 1,
Name = nameof(NewEnabled),
Rate = 10,
State = State.New,
Status = Connected.Data.Status.Enabled
};
public static TaxRate NotModifiedEnabled = new()
{
Id = 3,
Name = nameof(NotModifiedEnabled),
Rate = 30,
State = State.Default,
Status = Connected.Data.Status.Enabled
};
public static TaxRate DeletedEnabled = new()
{
Id = 4,
Name = nameof(DeletedEnabled),
Rate = 40,
State = State.Deleted,
Status = Connected.Data.Status.Enabled
};
public static TaxRate NewDisabled = new()
{
Id = 5,
Name = nameof(NewDisabled),
Rate = 50,
State = State.New,
Status = Connected.Data.Status.Disabled
};
public static TaxRate NotModifiedDisabled = new()
{
Id = 7,
Name = nameof(NotModifiedDisabled),
Rate = 70,
State = State.Default,
Status = Connected.Data.Status.Disabled
};
public static TaxRate DeletedDisabled = new()
{
Id = 8,
Name = nameof(DeletedDisabled),
Rate = 80,
State = State.Deleted,
Status = Connected.Data.Status.Disabled
};
internal static IEnumerable<TaxRate> CombinedTaxRateSet => new List<TaxRate>
{
NewEnabled,
NotModifiedEnabled,
DeletedEnabled,
NewDisabled,
NotModifiedDisabled,
DeletedDisabled
};
}

@ -0,0 +1,314 @@
using Connected.Entities.Storage;
using Connected.Notifications.Events;
using Connected.ServiceModel;
using Connected.ServiceModel.Transactions;
using Moq;
using System.Data;
using System.Linq.Expressions;
using static Common.Types.TaxRates.TaxRateOps;
using static Common.Types.TestUtils;
namespace Common.Types.TaxRates.Ops;
public class UpdateTests
{
[TestClass]
public class OnInvoke
{
private static IEnumerable<object[]> TaxRates => TaxRateSamples.CombinedTaxRateSet
.Select(e => new object[] { e.Id, e })
.ToList();
[TestMethod("Update updates only matching id")]
[DynamicData(nameof(TaxRates))]
public async Task Update_Invoke_UpdatesMatchingEntity(int id, ITaxRate expected)
{
/*
* Setup
*/
var dataSet = TaxRates.Select(e => e[1] as TaxRate).ToList();
var instanceFaker = new InstanceFaker<Update>();
var databaseContextProviderFake = instanceFaker.GetMock<IStorageProvider>()!;
Expression<Action<IStorageProvider>> updateFunction = (IStorageProvider e) => e.Open<TaxRate>().Update(It.IsAny<TaxRate>(), It.IsAny<UpdateTaxRateArgs>(), It.IsAny<Func<Task<TaxRate?>>>());
TaxRate? updatedEntity = null;
_ = databaseContextProviderFake
.Setup(updateFunction)
.Callback<TaxRate, UpdateTaxRateArgs, Func<Task<TaxRate>>>((e, _, _) => updatedEntity = e);
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet);
var args = new UpdateTaxRateArgs
{
Id = id
};
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
await serviceFunction.Invoke(args);
/*
* Assert
*/
databaseContextProviderFake.Verify(updateFunction, Times.Once());
Assert.AreEqual(expected, updatedEntity);
}
[TestMethod("Update throws if tax rate does not exist")]
public async Task Update_Invoke_ThrowsException_WhenEntityDoesNotExist()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.GetEmptyTaxRateSet();
var instanceFaker = new InstanceFaker<Update>();
var databaseContextProviderFake = instanceFaker.GetMock<IStorageProvider>()!;
Expression<Action<IStorageProvider>> updateFunction = (IStorageProvider e) => e.Open<TaxRate>().Update(It.IsAny<TaxRate>(), It.IsAny<UpdateTaxRateArgs>(), It.IsAny<Func<Task<TaxRate?>>>());
_ = databaseContextProviderFake.Setup(updateFunction);
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet);
/*
* Generate empty arguments, as the dataset is empty either way
*/
var args = new UpdateTaxRateArgs();
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
/*
* Assert
*/
await AssertExtensions.Throws(async () => await serviceFunction.Invoke(args));
}
[TestMethod("Update invokes concurrent update exactly once")]
public async Task Update_Invoke_InvokesConcurrentUpdate_ExactlyOnce()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.GetEmptyTaxRateSet();
var instanceFaker = new InstanceFaker<Update>();
var databaseContextProviderFake = instanceFaker.GetMock<IStorageProvider>()!;
Expression<Action<IStorageProvider>> updateFunction = (IStorageProvider e) => e.Open<TaxRate>().Update(It.IsAny<TaxRate>(), It.IsAny<UpdateTaxRateArgs>(), It.IsAny<Func<Task<TaxRate?>>>());
_ = databaseContextProviderFake.Setup(updateFunction);
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet);
/*
* Arguments are irrelevant for this test
*/
var args = new UpdateTaxRateArgs();
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
await serviceFunction.Invoke(args);
/*
* Assert
*/
databaseContextProviderFake.Verify(updateFunction, Times.Exactly(1));
}
[TestMethod("Update loads data exactly once when version is current")]
public async Task Update_Invoke_LoadsEntityExactlyOnce_WhenVersionIsCurrent()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.GetEmptyTaxRateSet();
var instanceFaker = new InstanceFaker<Update>();
var databaseContextProviderFake = instanceFaker.GetMock<IStorageProvider>()!;
Expression<Action<IStorageProvider>> updateFunction = (IStorageProvider e) => e.Open<TaxRate>().Update(It.IsAny<TaxRate>(), It.IsAny<UpdateTaxRateArgs>(), It.IsAny<Func<Task<TaxRate?>>>());
_ = databaseContextProviderFake.Setup(updateFunction);
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet);
/*
* Arguments are irrelevant for this test
*/
var args = new UpdateTaxRateArgs();
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
await serviceFunction.Invoke(args);
/*
* Assert
*/
taxRateCacheFake.Verify(e => e.GetEnumerator(), Times.Exactly(1));
}
[TestMethod("Update loads data twice when version is mismatched")]
public async Task Update_Invoke_LoadsEntityExactlyTwice_WhenVersionIsMismatched()
{
/*
* Setup
*/
var dataSet = TaxRateSamples.GetEmptyTaxRateSet();
var instanceFaker = new InstanceFaker<Update>();
var databaseContextProviderFake = instanceFaker.GetMock<IStorageProvider>()!;
Expression<Action<IStorageProvider>> updateFunction = (IStorageProvider e) => e.Open<TaxRate>().Update(It.IsAny<TaxRate>(), It.IsAny<UpdateTaxRateArgs>(), It.IsAny<Func<Task<TaxRate?>>>());
/*
* Simulate version mismatch by invoking the retry once
*/
_ = databaseContextProviderFake.Setup(updateFunction).Callback<TaxRate, UpdateTaxRateArgs, Func<Task<TaxRate?>>>((_, _, e) => e.Invoke());
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
taxRateCacheFake.SetupIEnumerable(dataSet);
/*
* Arguments are irrelevant for this test
*/
var args = new UpdateTaxRateArgs();
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
await serviceFunction.Invoke(args);
/*
* Assert
*/
taxRateCacheFake.Verify(e => e.GetEnumerator(), Times.Exactly(2));
}
}
[TestClass]
public class OnCommit
{
[TestMethod("Update commit invokes updated event exactly once")]
public async Task Update_Commit_InvokedUpdated_ExactlyOnce()
{
/*
* Setup
*/
var instanceFaker = new InstanceFaker<Update>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
_ = taxRateCacheFake.Setup(e => e.Refresh(It.IsAny<int>()));
var eventServiceFake = instanceFaker.GetMock<IEventService>()!;
_ = eventServiceFake.Setup(e => e.Enqueue(It.IsAny<ITaxRateService?>(), ServiceEvents.Updated, It.IsAny<int>()));
/*
* Argument values are irrelevant for the test
*/
var args = new UpdateTaxRateArgs();
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
serviceFunction.SetArguments(args);
await ((ITransactionClient)serviceFunction).Commit();
/*
* Assert
*/
eventServiceFake.Verify(e => e.Enqueue(It.IsAny<ITaxRateService?>(), ServiceEvents.Updated, It.IsAny<int>()), Times.Exactly(1));
}
[TestMethod("Update commit refreshes cache exactly once")]
public async Task Update_Commit_RefreshesCache_ExactlyOnce()
{
/*
* Setup
*/
var instanceFaker = new InstanceFaker<Update>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
_ = taxRateCacheFake.Setup(e => e.Refresh(It.IsAny<int>()));
var eventServiceFake = instanceFaker.GetMock<IEventService>()!;
_ = eventServiceFake.Setup(e => e.Enqueue(It.IsAny<ITaxRateService?>(), ServiceEvents.Updated, It.IsAny<int>()));
/*
* Argument values are irrelevant for the test
*/
var args = new UpdateTaxRateArgs();
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
serviceFunction.SetArguments(args);
await ((ITransactionClient)serviceFunction).Commit();
/*
* Assert
*/
taxRateCacheFake.Verify(e => e.Refresh(It.IsAny<int>()), Times.Exactly(1));
}
[TestMethod("Update commit fires updated event after notifying cache")]
public async Task Update_Commit_InvokedLastUpdatedEvent_AfterNotifyingCache()
{
/*
* Setup
* Mockbehavior string ensures no unplanned functions are called on the services.
* If you receive an error about function calls not properly set up, and function
* calls look ok, it's probably the sequence throwing the exception. This is a
* failure in user code, not the test.
*/
var sequence = new MockSequence();
var instanceFaker = new InstanceFaker<Update>();
var taxRateCacheFake = instanceFaker.GetMock<ITaxRateCache>()!;
_ = taxRateCacheFake
.InSequence(sequence)
.Setup(e => e.Refresh(It.IsAny<int>()));
var eventServiceFake = instanceFaker.GetMock<IEventService>()!;
_ = eventServiceFake
.InSequence(sequence)
.Setup(e => e.Enqueue(It.IsAny<ITaxRateService?>(), ServiceEvents.Updated, It.IsAny<int>()));
/*
* Argument values are irrelevant for the test
*/
var args = new UpdateTaxRateArgs();
/*
* Test
*/
var serviceFunction = instanceFaker.Instance;
serviceFunction.SetArguments(args);
await ((ITransactionClient)serviceFunction).Commit();
/*
* Assert
*/
taxRateCacheFake.Verify(e => e.Refresh(It.IsAny<int>()), Times.AtLeastOnce());
eventServiceFake.VerifyEvent<ITaxRateService, int>(ServiceEvents.Updated);
}
}
}

@ -0,0 +1,35 @@
using Connected.Entities.Annotations;
using Connected.Entities.Consistency;
using System.Reflection;
namespace Common.Types.TaxRates;
[TestClass]
public class TaxRateTests
{
[TestMethod("TaxRate is ConsistentEntity<>")]
public void TaxRate_IsConsistentEntity()
{
/*
* Test
*/
var isConsistentEntity = typeof(TaxRate).IsAssignableToGenericType(typeof(ConsistentEntity<>));
/*
* Assert
*/
Assert.IsTrue(isConsistentEntity);
}
[TestMethod("TaxRate has exactly one schema")]
public void TaxRate_HasExactlyOneSchema()
{
/*
* Test
*/
var tableAttributes = typeof(TaxRate).GetCustomAttributes<TableAttribute>();
/*
* Assert
*/
Assert.IsTrue(tableAttributes.Count() == 1);
}
}

@ -0,0 +1,105 @@
using Connected;
using Connected.Notifications.Events;
using Connected.Services;
using Moq;
namespace Common.Types;
internal static class TestUtils
{
public static bool IsAssignableToGenericType<TGenericType>(this Type type)
{
var genericType = typeof(TGenericType);
if (!genericType.IsGenericType)
throw new ArgumentException("The passed type must be a generic type.", nameof(TGenericType));
return type.IsAssignableToGenericType(genericType);
}
public static bool IsAssignableToGenericType(this Type type, Type genericType)
{
if (!genericType.IsGenericType)
throw new ArgumentException("The passed type must be a generic type.", nameof(genericType));
var interfaceTypes = type.GetInterfaces();
foreach (var interfaceType in interfaceTypes)
{
if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == genericType)
return true;
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType)
return true;
var baseType = type.BaseType;
if (baseType is null)
return false;
return baseType.IsAssignableToGenericType(genericType);
}
public static bool SequenceEquivalent<T>(this IEnumerable<T> firstSequence, IEnumerable<T> secondSequence)
{
var diff1 = firstSequence.Except(secondSequence);
var diff2 = secondSequence.Except(firstSequence);
return !diff1.Any() && !diff2.Any();
}
public static void SetArguments<TArgs>(this ServiceOperation<TArgs> operation, TArgs args)
where TArgs : IDto
{
typeof(ServiceOperation<TArgs>).GetProperty(nameof(operation.Arguments))!.SetValue(operation, args);
}
public static Moq.Language.Flow.ISetup<IEventService, Task> SetupEvent<TService, TId>(this Moq.Language.ISetupConditionResult<IEventService> setup, string @event)
{
return setup.Setup(e => e.Enqueue(It.IsAny<TService?>(), @event, It.IsAny<TId>()));
}
public static Moq.Language.Flow.ISetup<IEventService, Task> SetupEvent<TService, TId>(this Mock<IEventService> setup, string @event)
{
return setup.Setup(e => e.Enqueue(It.IsAny<TService?>(), @event, It.IsAny<TId>()));
}
public static void VerifyEvent<TService, TId>(this Mock<IEventService> setup, string @event)
{
setup.Verify(e => e.Enqueue(It.IsAny<TService?>(), @event, It.IsAny<TId>()), Times.Exactly(1));
}
public static void SetupIEnumerable<TEnumerable>(this Mock mock, IEnumerable<TEnumerable> data)
{
mock.As<IEnumerable<TEnumerable>>()
.Setup(e => e.GetEnumerator())
.Returns(data.GetEnumerator());
}
public static class AssertExtensions
{
public static async Task Throws(Task action)
{
Exception exception = null;
try
{
await action;
}
catch (Exception ex)
{
exception = ex;
}
if (exception is null)
Assert.Fail("Expected exception, none was thrown.");
}
internal static Task Throws(Func<Task> value)
{
return Throws(value());
}
}
}

@ -0,0 +1 @@
global using Microsoft.VisualStudio.TestTools.UnitTesting;

@ -0,0 +1,18 @@
using Connected.Startup;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Common.Types;
public class Bootstrapper : IStartup
{
public async Task Configure(WebAssemblyHost host)
{
await Task.CompletedTask;
}
public async Task ConfigureServices(IServiceCollection services)
{
await Task.CompletedTask;
}
}

@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>Common.Types</RootNamespace>
</PropertyGroup>
<ItemGroup>
<SupportedPlatform Include="browser" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="7.0.0-rc.2.22476.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Connected\Connected.Client\Connected.Client.csproj" />
<ProjectReference Include="..\..\Connected\Connected.UI\Connected.UI.csproj" />
<ProjectReference Include="..\..\Connected\Connected\Connected.csproj" />
<ProjectReference Include="..\Common.Types.Client\Common.Types.Client.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
</Project>

@ -0,0 +1,12 @@
using S = Connected.UIRoutes;
namespace Common.Types;
public static class CommonTypesUIRoutes
{
public const string CommonTypes = $"{S.Management}/commonTypes";
public const string TaxRates = $"{CommonTypes}/taxRates";
public const string TaxRatesAdd = $"{CommonTypes}/taxRates/add";
public const string TaxRatesEdit = $"{CommonTypes}/taxRates/edit/{{id:int}}";
}

@ -0,0 +1,24 @@
@using Connected.Components;
@inherits UIComponent
<h3 class="important">TaxRateAdd</h3>
<EditForm Model="@DataSource" OnValidSubmit="@OnInsert">
<DataAnnotationsValidator />
<ValidationSummary />
<div>
<label for="name">Name</label>
<InputText id="name" @bind-Value="DataSource.Name" />
</div>
<div>
<label for="rate">Rate</label>
<InputNumber id="rate" @bind-Value="DataSource.Rate" />
</div>
<button type="submit">Submit</button>
<button @onclick="OnCancel">Cancel</button>
</EditForm>

@ -0,0 +1,39 @@
using Connected.Components;
using Microsoft.AspNetCore.Components;
namespace Common.Types.TaxRates.Components;
public partial class TaxRateAdd : UIComponent
{
public TaxRateAdd()
{
DataSource = new InsertTaxRateArgs();
}
private InsertTaxRateArgs DataSource { get; }
[Inject]
private ITaxRateService? TaxRateService { get; set; }
[Inject]
private NavigationManager? Navigation { get; set; }
protected override async Task OnParametersSetAsync()
{
if (TaxRateService is null)
throw new ArgumentException(null, nameof(TaxRateService));
await base.OnParametersSetAsync();
}
protected virtual async void OnInsert()
{
await TaxRateService.Insert(DataSource);
Navigation.NavigateTo(Routes.TaxRates);
}
protected virtual void OnCancel()
{
Navigation.NavigateTo(Routes.TaxRates);
}
}

@ -0,0 +1,25 @@
@using Connected.Components;
@inherits UIComponent
<h3>TaxRateEditForm</h3>
<EditForm Model="@DataSource" OnValidSubmit="@OnUpdate">
<DataAnnotationsValidator />
<ValidationSummary />
<div>
<label for="name">Name</label>
<InputText id="name" @bind-Value="DataSource.Name" />
</div>
<div>
<label for="rate">Rate</label>
<InputNumber id="rate" @bind-Value="DataSource.Rate" />
</div>
<button type="submit">Submit</button>
<button @onclick="OnCancel">Cancel</button>
</EditForm>

@ -0,0 +1,42 @@
using Connected.Components;
using Connected.ServiceModel;
using Microsoft.AspNetCore.Components;
namespace Common.Types.TaxRates.Components;
public partial class TaxRateEdit : UIComponent
{
[Parameter]
public int Id { get; set; }
private UpdateTaxRateArgs? DataSource { get; set; }
[Inject]
private ITaxRateService? TaxRateService { get; set; }
[Inject]
private NavigationManager? Navigation { get; set; }
protected override async Task OnParametersSetAsync()
{
var taxRate = await TaxRateService.Select(new PrimaryKeyArgs<int> { Id = Convert.ToInt32(Id) });
DataSource = new UpdateTaxRateArgs
{
Id = taxRate.Id,
Name = taxRate.Name,
Rate = taxRate.Rate
};
}
private async void OnUpdate()
{
await TaxRateService.Update(DataSource);
Navigation.NavigateTo(CommonTypesUIRoutes.TaxRates);
}
private void OnCancel()
{
Navigation.NavigateTo(CommonTypesUIRoutes.TaxRates);
}
}

@ -0,0 +1,46 @@
@using Connected.Components;
@inherits UIComponent
@if (DataSource is null)
{
<div>
loading tax rates...
</div>
return;
}
<button @onclick="OnAdd">Add</button>
<div>
<label>Last insert</label>
<br />
<label>@LastInsert</label>
</div>
<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Rate</th>
<th>...</th>
</tr>
@foreach (var taxRate in DataSource)
{
<tr @key="taxRate.Id">
<td>
@taxRate.Id
</td>
<td>
@taxRate.Name
</td>
<td>
@taxRate.Rate
<br>
<Inline></Inline>
</td>
<td>
<button @onclick="(()=>OnEdit(taxRate.Id))">Edit</button>
</td>
</tr>
}
</table>

@ -0,0 +1,44 @@
using System.Collections.Immutable;
using Connected.Components;
using Connected.Notifications;
using Connected.ServiceModel;
using Microsoft.AspNetCore.Components;
namespace Common.Types.TaxRates.Components;
public partial class TaxRatesList : UIComponent
{
private ImmutableList<ITaxRate>? DataSource { get; set; }
[Inject]
private ITaxRateService? TaxRateService { get; set; }
[Inject]
private NavigationManager? Navigation { get; set; }
private string LastInsert { get; set; } = "waiting...";
protected override async Task OnParametersSetAsync()
{
await base.OnParametersSetAsync();
TaxRateService.Inserted += OnInserted;
DataSource = await TaxRateService.Query(QueryArgs.Default);
}
private void OnInserted(object? sender, PrimaryKeyEventArgs<int> e)
{
LastInsert = $"{e.Id} -> {DateTime.UtcNow:F}";
StateHasChanged();
}
private void OnEdit(int id)
{
Navigation.NavigateTo(CommonTypesUIRoutes.TaxRatesEdit.Replace("{id:int}", id.ToString()));
}
private void OnAdd()
{
Navigation.NavigateTo(CommonTypesUIRoutes.TaxRatesAdd);
}
}

@ -0,0 +1,5 @@
@attribute [Route(CommonTypesUIRoutes.TaxRatesAdd)]
<h3>TaxRateAdd</h3>
<TaxRateAdd></TaxRateAdd>

@ -0,0 +1,11 @@
@using Common.Types.TaxRates.Components
@attribute [Route(CommonTypesUIRoutes.TaxRatesEdit)]
<h3>TaxRateEdit</h3>
<TaxRateEdit Id="@Id"></TaxRateEdit>
@code {
[Parameter]
public int Id { get; set; }
}

@ -0,0 +1,12 @@
@attribute [Route(CommonTypesUIRoutes.TaxRates)]
@using Common.Types.TaxRates.Components;
@using Connected.Components;
@using Connected.Layouts;
@inherits UIComponent
@layout DefaultLayout
<h3>Tax rates</h3>
<DynamicComponent Type="ResolveComponent<TaxRatesList>()"></DynamicComponent>

@ -0,0 +1,6 @@
@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop

@ -0,0 +1,122 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.32916.344
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Dependencies", "Dependencies", "{20087506-E20F-4FD6-ADFB-9D7ADBBD3998}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common.Types.Client", "Common.Types.Client\Common.Types.Client.csproj", "{B94A8E27-3682-4321-9BF7-F0A2D775E905}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common.Types.Middleware", "Common.Types.Middleware\Common.Types.Middleware.csproj", "{72B591CC-DAC3-4F9A-A95C-67C265FB4E93}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common.Types", "Common.Types\Common.Types.csproj", "{EDDF95B7-236C-4F87-A9F0-1BC5A7FA9980}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common.Types.UI", "Common.Types.UI\Common.Types.UI.csproj", "{62A9D5D4-942B-40DA-AA9C-CF3D48339B60}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Connected.Data", "..\Framework\Connected.Data\Connected.Data.csproj", "{29DC3FA3-643B-4E92-B176-C6594960AD4B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Connected.Middleware", "..\Framework\Connected.Middleware\Connected.Middleware.csproj", "{1E4DFB97-CD50-4836-8B62-46D6FBDF924C}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Connected.Services", "..\Framework\Connected.Services\Connected.Services.csproj", "{90AD4721-1C34-4B9A-9515-6AFC095F55E8}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Connected", "..\Connected\Connected\Connected.csproj", "{B19801B5-7C84-4669-92AF-7581ABBDE259}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Connected.UI", "..\Connected\Connected.UI\Connected.UI.csproj", "{105164C0-685F-420F-B822-D59965244E51}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Connected.Client", "..\Connected\Connected.Client\Connected.Client.csproj", "{EA8DA8CF-9DE4-4815-93C3-ED92A6B5E64D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common.Types.Model", "Common.Types.Model\Common.Types.Model.csproj", "{DB82BD88-23C1-4E8A-9E48-92848E1942C0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common.Model", "..\Common\Common.Model\Common.Model.csproj", "{03D41846-3257-4097-9145-21DDA9546833}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Connected.Runtime", "..\Framework\Connected.Runtime\Connected.Runtime.csproj", "{7E147EBC-5B8C-462F-B736-545167935CB3}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common.Types.Tests", "Common.Types.Tests\Common.Types.Tests.csproj", "{AEF4D71A-C334-4E13-AECD-8EEA06872BB0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Connected.Entities", "..\Framework\Connected.Entities\Connected.Entities.csproj", "{E52DDB90-5F33-4189-8D72-81DE8165ADE6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B94A8E27-3682-4321-9BF7-F0A2D775E905}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B94A8E27-3682-4321-9BF7-F0A2D775E905}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B94A8E27-3682-4321-9BF7-F0A2D775E905}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B94A8E27-3682-4321-9BF7-F0A2D775E905}.Release|Any CPU.Build.0 = Release|Any CPU
{72B591CC-DAC3-4F9A-A95C-67C265FB4E93}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{72B591CC-DAC3-4F9A-A95C-67C265FB4E93}.Debug|Any CPU.Build.0 = Debug|Any CPU
{72B591CC-DAC3-4F9A-A95C-67C265FB4E93}.Release|Any CPU.ActiveCfg = Release|Any CPU
{72B591CC-DAC3-4F9A-A95C-67C265FB4E93}.Release|Any CPU.Build.0 = Release|Any CPU
{EDDF95B7-236C-4F87-A9F0-1BC5A7FA9980}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EDDF95B7-236C-4F87-A9F0-1BC5A7FA9980}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EDDF95B7-236C-4F87-A9F0-1BC5A7FA9980}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EDDF95B7-236C-4F87-A9F0-1BC5A7FA9980}.Release|Any CPU.Build.0 = Release|Any CPU
{62A9D5D4-942B-40DA-AA9C-CF3D48339B60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{62A9D5D4-942B-40DA-AA9C-CF3D48339B60}.Debug|Any CPU.Build.0 = Debug|Any CPU
{62A9D5D4-942B-40DA-AA9C-CF3D48339B60}.Release|Any CPU.ActiveCfg = Release|Any CPU
{62A9D5D4-942B-40DA-AA9C-CF3D48339B60}.Release|Any CPU.Build.0 = Release|Any CPU
{29DC3FA3-643B-4E92-B176-C6594960AD4B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{29DC3FA3-643B-4E92-B176-C6594960AD4B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{29DC3FA3-643B-4E92-B176-C6594960AD4B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{29DC3FA3-643B-4E92-B176-C6594960AD4B}.Release|Any CPU.Build.0 = Release|Any CPU
{1E4DFB97-CD50-4836-8B62-46D6FBDF924C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1E4DFB97-CD50-4836-8B62-46D6FBDF924C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1E4DFB97-CD50-4836-8B62-46D6FBDF924C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1E4DFB97-CD50-4836-8B62-46D6FBDF924C}.Release|Any CPU.Build.0 = Release|Any CPU
{90AD4721-1C34-4B9A-9515-6AFC095F55E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{90AD4721-1C34-4B9A-9515-6AFC095F55E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{90AD4721-1C34-4B9A-9515-6AFC095F55E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{90AD4721-1C34-4B9A-9515-6AFC095F55E8}.Release|Any CPU.Build.0 = Release|Any CPU
{B19801B5-7C84-4669-92AF-7581ABBDE259}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B19801B5-7C84-4669-92AF-7581ABBDE259}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B19801B5-7C84-4669-92AF-7581ABBDE259}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B19801B5-7C84-4669-92AF-7581ABBDE259}.Release|Any CPU.Build.0 = Release|Any CPU
{105164C0-685F-420F-B822-D59965244E51}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{105164C0-685F-420F-B822-D59965244E51}.Debug|Any CPU.Build.0 = Debug|Any CPU
{105164C0-685F-420F-B822-D59965244E51}.Release|Any CPU.ActiveCfg = Release|Any CPU
{105164C0-685F-420F-B822-D59965244E51}.Release|Any CPU.Build.0 = Release|Any CPU
{EA8DA8CF-9DE4-4815-93C3-ED92A6B5E64D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EA8DA8CF-9DE4-4815-93C3-ED92A6B5E64D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EA8DA8CF-9DE4-4815-93C3-ED92A6B5E64D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EA8DA8CF-9DE4-4815-93C3-ED92A6B5E64D}.Release|Any CPU.Build.0 = Release|Any CPU
{DB82BD88-23C1-4E8A-9E48-92848E1942C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DB82BD88-23C1-4E8A-9E48-92848E1942C0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DB82BD88-23C1-4E8A-9E48-92848E1942C0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DB82BD88-23C1-4E8A-9E48-92848E1942C0}.Release|Any CPU.Build.0 = Release|Any CPU
{03D41846-3257-4097-9145-21DDA9546833}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03D41846-3257-4097-9145-21DDA9546833}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03D41846-3257-4097-9145-21DDA9546833}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03D41846-3257-4097-9145-21DDA9546833}.Release|Any CPU.Build.0 = Release|Any CPU
{7E147EBC-5B8C-462F-B736-545167935CB3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7E147EBC-5B8C-462F-B736-545167935CB3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7E147EBC-5B8C-462F-B736-545167935CB3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7E147EBC-5B8C-462F-B736-545167935CB3}.Release|Any CPU.Build.0 = Release|Any CPU
{AEF4D71A-C334-4E13-AECD-8EEA06872BB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AEF4D71A-C334-4E13-AECD-8EEA06872BB0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AEF4D71A-C334-4E13-AECD-8EEA06872BB0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AEF4D71A-C334-4E13-AECD-8EEA06872BB0}.Release|Any CPU.Build.0 = Release|Any CPU
{E52DDB90-5F33-4189-8D72-81DE8165ADE6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E52DDB90-5F33-4189-8D72-81DE8165ADE6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E52DDB90-5F33-4189-8D72-81DE8165ADE6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E52DDB90-5F33-4189-8D72-81DE8165ADE6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{29DC3FA3-643B-4E92-B176-C6594960AD4B} = {20087506-E20F-4FD6-ADFB-9D7ADBBD3998}
{1E4DFB97-CD50-4836-8B62-46D6FBDF924C} = {20087506-E20F-4FD6-ADFB-9D7ADBBD3998}
{90AD4721-1C34-4B9A-9515-6AFC095F55E8} = {20087506-E20F-4FD6-ADFB-9D7ADBBD3998}
{B19801B5-7C84-4669-92AF-7581ABBDE259} = {20087506-E20F-4FD6-ADFB-9D7ADBBD3998}
{105164C0-685F-420F-B822-D59965244E51} = {20087506-E20F-4FD6-ADFB-9D7ADBBD3998}
{EA8DA8CF-9DE4-4815-93C3-ED92A6B5E64D} = {20087506-E20F-4FD6-ADFB-9D7ADBBD3998}
{03D41846-3257-4097-9145-21DDA9546833} = {20087506-E20F-4FD6-ADFB-9D7ADBBD3998}
{7E147EBC-5B8C-462F-B736-545167935CB3} = {20087506-E20F-4FD6-ADFB-9D7ADBBD3998}
{E52DDB90-5F33-4189-8D72-81DE8165ADE6} = {20087506-E20F-4FD6-ADFB-9D7ADBBD3998}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4C661325-1729-4560-89F9-E2B51B111B72}
EndGlobalSection
EndGlobal

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Framework\Connected.Data\Connected.Data.csproj" />
<ProjectReference Include="..\..\Framework\Connected.Runtime\Connected.Runtime.csproj" />
<ProjectReference Include="..\..\Framework\Connected.Services\Connected.Services.csproj" />
<ProjectReference Include="..\Common.Types.Middleware\Common.Types.Middleware.csproj" />
<ProjectReference Include="..\Common.Types.Model\Common.Types.Model.csproj" />
</ItemGroup>
</Project>

@ -0,0 +1,16 @@
using Common.Types.Continent.Countries;
using Connected.Annotations;
using Connected.Entities;
using Connected.Entities.Annotations;
namespace Common.Types.Continents.Countries;
[Table(Schema = SchemaAttribute.TypesSchema)]
internal record ContinentCountry : Entity<int>, IContinentCountry
{
[Ordinal(0)]
public int Continent { get; init; }
[Ordinal(1)]
public int Country { get; init; }
}

@ -0,0 +1,11 @@
using Connected.Entities.Caching;
namespace Common.Types.Continents.Countries;
internal interface IContinentCountryCache : IEntityCacheClient<ContinentCountry, int> { }
internal class ContinentCountryCache : EntityCacheClient<ContinentCountry, int>, IContinentCountryCache
{
public ContinentCountryCache(IEntityCacheContext context) : base(context, "_")
{
}
}

@ -0,0 +1,38 @@
using Common.Types.Continent.Countries;
using Connected.ServiceModel;
using Connected.Services;
using System.Collections.Immutable;
namespace Common.Types.Continents.Countries;
internal class ContinentCountryService : EntityService<int>, IContinentCountryService
{
public ContinentCountryService(IContext context) : base(context)
{
}
public Task Delete(PrimaryKeyArgs<int> args)
{
throw new NotImplementedException();
}
public Task<int> Insert(InsertContinentCountryArgs args)
{
throw new NotImplementedException();
}
public Task<ImmutableList<IContinentCountry>?> Query()
{
throw new NotImplementedException();
}
public Task<ImmutableList<IContinentCountry>?> QueryCountries(PrimaryKeyArgs<int> args)
{
throw new NotImplementedException();
}
public Task<IContinentCountry> SelectCountry(PrimaryKeyArgs<int> args)
{
throw new NotImplementedException();
}
}

@ -0,0 +1,25 @@
using Common.Types.Continent;
using Common.Types.Countries;
using Connected.Data.DataProtection;
using Connected.Data.EntityProtection;
using Connected.Entities;
using Connected.Middleware;
using Connected.Validation;
namespace Common.Types.Continents.Countries;
internal class ContinentProtector : MiddlewareComponent, IEntityProtector<IContinent>
{
public ContinentProtector(IContinentCountryCache cache)
{
Cache = cache;
}
private IContinentCountryCache Cache { get; }
public async Task Invoke(EntityProtectionArgs<IContinent> args)
{
if ((await (from dc in Cache where dc.Continent == args.Entity.Id select dc).AsEntity()) is not null)
throw ValidationExceptions.ReferenceExists(typeof(ICountry), args.Entity.Id);
}
}

@ -0,0 +1,22 @@
using Connected.Data;
using Connected.Entities.Annotations;
using Connected.Entities.Consistency;
namespace Common.Types.Countries;
[Table(Schema = SchemaAttribute.TypesSchema)]
internal record Country : ConsistentEntity<int>, ICountry
{
public const string CacheKey = $"{SchemaAttribute.TypesSchema}.{nameof(Country)}";
[Length(128)]
public string Name { get; init; }
public int Lcid { get; init; }
[Length(128)]
public string IsoCode { get; init; }
public Status Status { get; init; } = Status.Enabled;
}

@ -0,0 +1,14 @@
using Connected.Entities.Caching;
namespace Common.Types.Countries;
internal interface ICountryCache : IEntityCacheClient<Country, int> { }
/// <summary>
/// Cache for the <see cref="ICountry"/> entity.
/// </summary>
internal sealed class CountryCache : EntityCacheClient<Country, int>, ICountryCache
{
public CountryCache(IEntityCacheContext context) : base(context, Country.CacheKey)
{
}
}

@ -0,0 +1,156 @@
using System.Collections.Immutable;
using Connected;
using Connected.Entities;
using Connected.Entities.Storage;
using Connected.Notifications.Events;
using Connected.ServiceModel;
using Connected.Services;
namespace Common.Types.Countries;
internal sealed class QueryCountries : ServiceFunction<IDto, ImmutableList<ICountry>?>
{
public QueryCountries(ICountryCache cache)
{
Cache = cache;
}
private ICountryCache Cache { get; }
protected override async Task<ImmutableList<ICountry>?> OnInvoke()
{
return await (from dc in Cache select dc).AsEntities<ICountry>();
}
}
internal sealed class SelectCountry : ServiceFunction<PrimaryKeyArgs<int>, ICountry?>
{
public SelectCountry(ICountryCache cache)
{
Cache = cache;
}
private ICountryCache Cache { get; }
protected override async Task<ICountry?> OnInvoke()
{
return await (from dc in Cache where dc.Id == Arguments.Id select dc).AsEntity();
}
}
internal sealed class SelectCountryByName : ServiceFunction<NameArgs, ICountry?>
{
public SelectCountryByName(ICountryCache cache)
{
Cache = cache;
}
private ICountryCache Cache { get; }
protected override async Task<ICountry?> OnInvoke()
{
return await (from dc in Cache where string.Equals(dc.Name, Arguments.Name, StringComparison.OrdinalIgnoreCase) select dc).AsEntity();
}
}
internal sealed class LookupCountries : ServiceFunction<PrimaryKeyListArgs<int>, ImmutableList<ICountry>?>
{
public LookupCountries(ICountryCache cache)
{
Cache = cache;
}
private ICountryCache Cache { get; }
protected override async Task<ImmutableList<ICountry>?> OnInvoke()
{
if (Arguments.IdList is null)
return null;
return await (from dc in Cache where Arguments.IdList.Contains(dc.Id) select dc).AsEntities<ICountry>();
}
}
internal sealed class DeleteCountry : ServiceAction<PrimaryKeyArgs<int>>
{
public DeleteCountry(ICountryService countryService, IStorageProvider storage, ICountryCache cache, IEventService events)
{
CountryService = countryService;
Storage = storage;
Cache = cache;
Events = events;
}
private ICountryService CountryService { get; }
private IStorageProvider Storage { get; }
private ICountryCache Cache { get; }
private IEventService Events { get; }
protected override async Task OnInvoke()
{
await Storage.Open<Country>().Update(new Country { Id = Arguments.Id, State = State.Deleted });
}
protected override async Task OnCommitted()
{
await Cache.Remove(Arguments.Id);
await Events.Enqueue(this, CountryService, ServiceEvents.Deleted, Arguments.Id);
}
}
internal sealed class InsertCountry : ServiceFunction<InsertCountryArgs, int>
{
public InsertCountry(ICountryService countryService, IStorageProvider database, IEventService events, ICountryCache cache)
{
CountryService = countryService;
Database = database;
Events = events;
Cache = cache;
}
private ICountryService CountryService { get; }
private IStorageProvider Database { get; }
private IEventService Events { get; }
private ICountryCache Cache { get; }
protected override async Task<int> OnInvoke()
{
var entity = Arguments.AsEntity<Country>(State.New);
var result = await Database.Open<Country>().Update(entity);
return result is null ? 0 : result.Id;
}
protected override async Task OnCommitted()
{
await Cache.Refresh(Result);
await Events.Enqueue(this, CountryService, ServiceEvents.Inserted, Result);
}
}
internal sealed class UpdateCountry : ServiceAction<UpdateCountryArgs>
{
public UpdateCountry(ICountryService countryService, IStorageProvider database, ICountryCache cache, IEventService events)
{
CountryService = countryService;
Database = database;
Cache = cache;
Events = events;
}
private IStorageProvider Database { get; }
private ICountryCache Cache { get; }
private IEventService Events { get; }
private ICountryService CountryService { get; }
protected override async Task OnInvoke()
{
await Database.Open<Country>().Update(await Load(), Arguments, async () =>
{
await Cache.Refresh(Arguments.Id);
return await Load();
});
}
private async Task<Country?> Load() => await (from dc in Cache where dc.Id == Arguments.Id select dc).AsEntity();
protected override async Task OnCommitted()
{
await Cache.Refresh(Arguments.Id);
await Events.Enqueue(this, CountryService, ServiceEvents.Updated, Arguments.Id);
}
}

@ -0,0 +1,56 @@
using Common.Types.Security;
using Connected.ServiceModel;
using Connected.Services;
using Connected.Services.Annotations;
using System.Collections.Immutable;
namespace Common.Types.Countries;
internal sealed class CountryService : EntityService<int>, ICountryService
{
public CountryService(IContext context) : base(context)
{
}
[ServiceAuthorization(Claims.Delete)]
public async Task Delete(PrimaryKeyArgs<int> args)
{
await Invoke(GetOperation<DeleteCountry>(), args);
}
[ServiceAuthorization(Claims.Add)]
public async Task<int> Insert(InsertCountryArgs args)
{
return await Invoke(GetOperation<InsertCountry>(), args);
}
[ServiceAuthorization(Claims.Read)]
public async Task<ImmutableList<ICountry>?> Query()
{
return await Invoke(GetOperation<QueryCountries>(), Dto.Empty);
}
[ServiceAuthorization(Claims.Read)]
public async Task<ImmutableList<ICountry>?> Query(PrimaryKeyListArgs<int> args)
{
return await Invoke(GetOperation<LookupCountries>(), args);
}
[ServiceAuthorization(Claims.Read)]
public async Task<ICountry?> Select(PrimaryKeyArgs<int> args)
{
return await Invoke(GetOperation<SelectCountry>(), args);
}
[ServiceAuthorization(Claims.Read)]
public async Task<ICountry?> Select(NameArgs args)
{
return await Invoke(GetOperation<SelectCountryByName>(), args);
}
[ServiceAuthorization(Claims.Modify)]
public async Task Update(UpdateCountryArgs args)
{
await Invoke(GetOperation<UpdateCountry>(), args);
}
}

@ -0,0 +1,53 @@
using Connected.Middleware;
using Connected.Validation;
namespace Common.Types.Countries;
internal class CountryValidator : MiddlewareComponent, IValidator<InsertCountryArgs>
{
public CountryValidator(ICountryService countryService)
{
CountryService = countryService;
}
private ICountryService CountryService { get; }
/// <summary>
///
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
public async Task Validate(InsertCountryArgs args)
{
/*
* Country has the following constraints:
* - name is unique
* - lcid is unique
* - iso2Alpha code is unique
*/
/*
* This method handles insert and update country methods.
* The algorithm is different for each method.
* First check if it's an update
*/
var update = args as UpdateCountryArgs;
foreach (var country in await CountryService.Query())
{
/*
* Ignore self record.
*/
if (update is not null && country.Id == update.Id)
continue;
if (string.Equals(country.Name, args.Name, StringComparison.OrdinalIgnoreCase))
throw ValidationExceptions.ValueExists(nameof(country.Name), args.Name);
if (country.Lcid > 0 && country.Lcid == args.Lcid)
throw ValidationExceptions.ValueExists(nameof(country.Lcid), args.Lcid);
if (!string.IsNullOrEmpty(country.IsoCode) && string.Equals(country.IsoCode, args.IsoCode, StringComparison.OrdinalIgnoreCase))
throw ValidationExceptions.ValueExists(nameof(country.IsoCode), args.IsoCode);
}
}
}

@ -0,0 +1,25 @@
using Common.Types.Middleware.Currencies;
using Connected.Interop;
using Connected.Middleware;
using System.Globalization;
namespace Common.Types.Currencies;
internal class DefaultCurrencyFormatterMiddleware<TValue> : MiddlewareComponent, ICurrencyFormatterMiddleware<TValue>
{
public Task<string?> Format(TValue value, ICurrency currency, string format)
{
if (value is null)
return Task.FromResult<string?>(null);
if (string.IsNullOrWhiteSpace(format))
format = "N2";
var culture = currency.Lcid == 0 ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(currency.Lcid);
if (!TypeConversion.TryConvert(value, out double converted, culture))
return Task.FromResult(value.ToString());
return Task.FromResult<string?>(converted.ToString(format, culture));
}
}

@ -0,0 +1,10 @@
namespace Common.Types.Security
{
internal static class Claims
{
public const string Delete = "Common Delete";
public const string Read = "Common Read";
public const string Add = "Common Add";
public const string Modify = "Common Modify";
}
}

@ -0,0 +1,14 @@
using System.Runtime.CompilerServices;
using Connected;
using Connected.Annotations;
[assembly: MicroService(MicroServiceType.Service)]
[assembly: InternalsVisibleTo("Common.Types.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
namespace Common.Types;
internal class ServerStartup : Startup
{
}

@ -0,0 +1,33 @@
using Connected.Data;
using Connected.Entities.Annotations;
using Connected.Entities.Concurrency;
namespace Common.Types.TaxRates;
/// <summary>
/// The <see cref="ITaxRate"/> entity.
/// </summary>
[Table(Schema = SchemaAttribute.TypesSchema)]
internal sealed record TaxRate : ConcurrentEntity<int>, ITaxRate
{
/// <summary>
/// The cache key under which all TaxRate entities are stored.
/// </summary>
public const string CacheKey = $"{SchemaAttribute.TypesSchema}.{nameof(TaxRate)}";
/// <summary>
/// The name of the <see cref="ITaxRate"/>.
/// </summary>
[Length(128)]
public string? Name { get; init; }
/// <summary>
/// The rate of the <see cref="ITaxRate"/>.
/// </summary>
public float Rate { get; init; }
/// <summary>
/// The <see cref="ITaxRate"/> status. Only <see cref="Status.Enabled"/> entities
/// should be used on front ends.
/// </summary>
[Default(Status.Enabled)]
public Status Status { get; init; }
}

@ -0,0 +1,26 @@
using Connected.Entities.Caching;
namespace Common.Types.TaxRates;
/// <summary>
/// This is the contract for the typed cache. Using contracts for
/// caching is useful when writing unit tests so a developer
/// can mock the entire cache.
/// </summary>
internal interface ITaxRateCache : IEntityCacheClient<TaxRate, int> { }
/// <summary>
/// Cache for the <see cref="ITaxRate"/> entity.
/// </summary>
/// <remarks>
/// <see cref="EntityCacheClient{TEntity, TPrimaryKey}"/> stores the entire set
/// of records in the database. This is useful for data which doesn't change
/// frequently because invalidating it ofter can have performance penalties.
/// The platform knows how to load and invalidate the entity so developer
/// doesn't nedd to write any code at all.
/// </remarks>
internal sealed class TaxRateCache : EntityCacheClient<TaxRate, int>, ITaxRateCache
{
public TaxRateCache(IEntityCacheContext context) : base(context, TaxRate.CacheKey)
{
}
}

@ -0,0 +1,252 @@
using System.Collections.Immutable;
using Connected.Entities;
using Connected.Entities.Storage;
using Connected.Notifications.Events;
using Connected.ServiceModel;
using Connected.Services;
namespace Common.Types.TaxRates;
internal class TaxRateOps
{
/// <summary>
/// Queries all <see cref="ITaxRate"/> records.
/// </summary>
internal sealed class Query : ServiceFunction<QueryArgs, ImmutableList<ITaxRate>?>
{
/// <summary>
/// Creates a new instance of the <see cref="Query"/> class.
/// </summary>
/// <param name="cache">The cache where the records are stored.</param>
public Query(ITaxRateCache cache, IStorageProvider storage)
{
Cache = cache;
Storage = storage;
}
private ITaxRateCache Cache { get; }
public IStorageProvider Storage { get; }
protected override async Task<ImmutableList<ITaxRate>?> OnInvoke()
{
var r = await (from dc in Storage.Open<TaxRate>() select dc).WithArguments(Arguments).AsEntities<ITaxRate>();
/*
* We simply return all records that exist in the system.
*/
return await (from dc in Cache select dc).WithArguments(Arguments).AsEntities<ITaxRate>();
}
}
/// <summary>
/// Returns <see cref="ITaxRate"/> with the specified id or null
/// if the record for the specified id does not exist.
/// </summary>
internal sealed class Select : ServiceFunction<PrimaryKeyArgs<int>, ITaxRate?>
{
public Select(ITaxRateCache cache)
{
Cache = cache;
}
private ITaxRateCache Cache { get; }
protected override async Task<ITaxRate?> OnInvoke()
{
/*
* Filter cache by the id.
*/
return await (from dc in Cache where dc.Id == Arguments.Id select dc).AsEntity();
}
}
/// <summary>
/// Returns <see cref="ITaxRate"/> with the specified name and rate or null if
/// the record with the specified arguments does not exist.
/// </summary>
internal sealed class SelectByRate : ServiceFunction<TaxRateArgs, ITaxRate?>
{
public SelectByRate(ITaxRateCache cache)
{
Cache = cache;
}
private ITaxRateCache Cache { get; }
protected override async Task<ITaxRate?> OnInvoke()
{
return await (from dc in Cache
where string.Equals(dc.Name, Arguments.Name, StringComparison.OrdinalIgnoreCase) && dc.Rate == Arguments.Rate
select dc).AsEntity();
}
}
/// <summary>
/// Returns List of <see cref="ITaxRate"/> for the specified set of ids. Use this method when joining data
/// to other entities.
/// </summary>
internal sealed class Lookup : ServiceFunction<PrimaryKeyListArgs<int>, ImmutableList<ITaxRate>?>
{
public Lookup(ITaxRateCache cache)
{
Cache = cache;
}
private ITaxRateCache Cache { get; }
protected override async Task<ImmutableList<ITaxRate>?> OnInvoke()
{
/*
* Use simple linq join for the specified set of ids.
*/
return await (from dc in Cache where Arguments.IdList.Contains(dc.Id) select dc).AsEntities<ITaxRate>();
}
}
/// <summary>
/// Inserts a new <see cref="ITaxRate"/> and returns its Id.
/// </summary>
internal sealed class Insert : ServiceFunction<InsertTaxRateArgs, int>
{
public Insert(ITaxRateService taxRateService, IStorageProvider storage, IEventService events, ITaxRateCache cache)
{
TaxRateService = taxRateService;
Storage = storage;
Events = events;
Cache = cache;
}
private ITaxRateService TaxRateService { get; }
private IStorageProvider Storage { get; }
private IEventService Events { get; }
private ITaxRateCache Cache { get; }
protected override async Task<int> OnInvoke()
{
/*
* First, create a new entity from the passed arguments and mark its state as new. This will
* signal the DatabaseContext to perform an insert operation when calling the Update.
*/
var entity = Arguments.AsEntity<TaxRate>(State.New);
/*
* Call update on the DatabaseContext. This call will return a new ITaxRate of the inserted
* entity.
*/
return (await Storage.Open<TaxRate>().Update(entity)).Id;
}
protected override async Task OnCommitted()
{
/*
* At this stage, the transaction has been commited which means
* record is definitely permanently stored in the database.
* We are making a simple call to the cache to refresh the item with the
* new id. Cache will query a database for new record and will store it
* in memory.
*/
await Cache.Refresh(Result);
/*
* Now trigger the inserted event which will notify all components hooked in the
* same process, out of process scale out instances and clients (wasm).
*/
await Events.Enqueue(this, TaxRateService, ServiceEvents.Inserted, Result);
}
}
/// <summary>
/// Permanently deletes a <see cref="ITaxRate"/> from the system.
/// </summary>
/// <remarks>
/// This method gets called after all <see cref="Server.Data.DataProtection.IDataProtectionMiddleware{TArgs}"/>
/// middleware passed successfuly.
/// </remarks>
internal sealed class Delete : ServiceAction<PrimaryKeyArgs<int>>
{
public Delete(ITaxRateService taxRateService, IStorageProvider storage, ITaxRateCache cache, IEventService events)
{
TaxRateService = taxRateService;
Storage = storage;
Cache = cache;
Events = events;
}
private ITaxRateService TaxRateService { get; }
private IStorageProvider Storage { get; }
private ITaxRateCache Cache { get; }
private IEventService Events { get; }
protected override async Task OnInvoke()
{
/*
* we don't need a reference to a record here because delete uses only
* an id. The overhead would only occur in cases if the record wouldn't exist
* but this is not the job of the operation. The Validators should theoretically
* reject such an operation.
*/
await Storage.Open<TaxRate>().Update(new TaxRate { Id = Arguments.Id, State = State.Deleted });
}
protected override async Task OnCommitted()
{
/*
* Once all the transactions have been commited remove the non existing record
* from the cache.
*/
await Cache.Remove(Arguments.Id);
/*
* And notify audience about the event.
*/
await Events.Enqueue(this, TaxRateService, ServiceEvents.Deleted, Arguments.Id);
}
}
/// <summary>
/// Updates the <see cref="ITaxRate"/> entity.
/// </summary>
internal sealed class Update : ServiceAction<UpdateTaxRateArgs>
{
public Update(ITaxRateService taxRateService, IStorageProvider storage, ITaxRateCache cache, IEventService events)
{
TaxRateService = taxRateService;
Storage = storage;
Cache = cache;
Events = events;
}
private IStorageProvider Storage { get; }
private ITaxRateCache Cache { get; }
private IEventService Events { get; }
private ITaxRateService TaxRateService { get; }
protected override async Task OnInvoke()
{
/*
* TaxRate is concurrency entity which means the platform takes care of
* data consistency. Data consistency means we can't overwrite updates made
* by others.
* Updating Concurrency entity thus requires a bit more logic. We must use a retry logic
* in case of Concurrency failure. We'll call Update method with reload lambda function.
*/
var entity = SetState(await Load());
await Storage.Open<TaxRate>().Update(entity, Arguments, async () =>
{
/*
* The concurrency exception occured.
* Refresh the entry from the cache. This will load a new version from
* a database.
*/
await Cache.Refresh(Arguments.Id);
return SetState(await Load());
});
}
private async Task<TaxRate?> Load() => await (from dc in Cache where dc.Id == Arguments.Id select dc).AsEntity();
protected override async Task OnCommitted()
{
/*
* Once the update is complete refresh the cache because the database assigned a new timestamp
* to an entity and any sunsequent update would fail anyway.
*/
await Cache.Refresh(Arguments.Id);
/*
* Now trigger the distributed event notifying the update has completed.
*/
await Events.Enqueue(this, TaxRateService, ServiceEvents.Updated, Arguments.Id);
}
}
}

@ -0,0 +1,94 @@
using Common.Types.Security;
using Connected.ServiceModel;
using Connected.Services;
using Connected.Services.Annotations;
using System.Collections.Immutable;
namespace Common.Types.TaxRates;
/// <summary>
/// The implementation class for <see cref="ITaxRateService"/> service.
/// </summary>
internal sealed class TaxRateService : EntityService<int>, ITaxRateService
{
public TaxRateService(IContext context) : base(context)
{
}
/// <summary>
/// Perorfms a lookup on <see cref="ITaxRate"/> records based on a specified
/// set of ids.
/// </summary>
/// <param name="e">The list of ids for which records should be returned.</param>
/// <returns>The list if <see cref="ITaxRate"/> records.</returns>
[ServiceAuthorization(Claims.Read)]
public async Task<ImmutableList<ITaxRate>?> Query(PrimaryKeyListArgs<int> e)
{
return await Invoke(GetOperation<TaxRateOps.Lookup>(), e);
}
/// <summary>
/// Queries the entire <see cref="ITaxRate"/> entity set.
/// </summary>
/// <returns>The list of all <see cref="ITaxRate"/> entities.</returns>
[ServiceAuthorization(Claims.Read)]
public async Task<ImmutableList<ITaxRate>?> Query(QueryArgs? args)
{
return await Invoke(GetOperation<TaxRateOps.Query>(), args ?? QueryArgs.NoPaging);
}
/// <summary>
/// Searches for the first <see cref="ITaxRate"/> entity which matches
/// the specified arguments.
/// </summary>
/// <param name="args">The arguments representing search criteria.</param>
/// <returns>The first <see cref="ITaxRate"/> entity which matches the
/// criteria, <code>null</code> otherwise.</returns>
[ServiceAuthorization(Claims.Read)]
public async Task<ITaxRate?> Select(TaxRateArgs args)
{
return await Invoke(GetOperation<TaxRateOps.SelectByRate>(), args);
}
/// <summary>
/// Selects the <see cref="ITaxRate"/> for the specified id.
/// </summary>
/// <param name="args">The id for which a record will
/// be returned.</param>
/// <returns>The <see cref="ITaxRate"/> entity with the specified id,
/// <code>null</code> otherwise.</returns>
[ServiceAuthorization(Claims.Read)]
public async Task<ITaxRate?> Select(PrimaryKeyArgs<int> args)
{
return await Invoke(GetOperation<TaxRateOps.Select>(), args);
}
/// <summary>
/// Permanently deletes an <see cref="ITaxRate"/> entity with
/// the specified id.
/// </summary>
/// <remarks>
/// This operation can be rejected by an <see cref="IDataProtectionMiddleware{TArgs}"/>
/// middleware.
/// </remarks>
/// <param name="args">The id of the entity which will be deleted.</param>
[ServiceAuthorization(Claims.Delete)]
public async Task Delete(PrimaryKeyArgs<int> args)
{
await Invoke(GetOperation<TaxRateOps.Delete>(), args);
}
/// <summary>
/// Inserts a new <see cref="ITaxRate"/> entity into the system.
/// </summary>
/// <param name="args">The values representing a new entity.</param>
/// <returns>An id of the newly inserted entity.</returns>
[ServiceAuthorization(Claims.Add)]
public async Task<int> Insert(InsertTaxRateArgs args)
{
return await Invoke(GetOperation<TaxRateOps.Insert>(), args);
}
/// <summary>
/// Updates an existing <see cref="ITaxRate"/> entity.
/// </summary>
/// <param name="args">The arguments representing a changed values.</param>
[ServiceAuthorization(Claims.Modify)]
public async Task Update(UpdateTaxRateArgs args)
{
await Invoke(GetOperation<TaxRateOps.Update>(), args);
}
}

@ -0,0 +1,48 @@
using Connected.Entities;
using Connected.Middleware;
using Connected.Validation;
namespace Common.Types.TaxRates;
/// <summary>
/// Business logic validator for the <see cref="InsertTaxRateArgs"/> arguments.
/// </summary>
internal sealed class InsertTaxRateValidator : MiddlewareComponent, IValidator<InsertTaxRateArgs>
{
public InsertTaxRateValidator(ITaxRateCache cache)
{
Service = cache;
}
private ITaxRateCache Service { get; }
public async Task Validate(InsertTaxRateArgs args)
{
/*
* We have a constraint on a name property.
*/
if (await (from dc in Service where string.Equals(dc.Name, args.Name, StringComparison.OrdinalIgnoreCase) select dc).AsEntity() is ITaxRate existing)
throw ValidationExceptions.ValueExists(nameof(args.Name), args.Name);
}
}
/// <summary>
/// Business logic validator for the <see cref="UpdateTaxRateArgs"/> arguments.
/// </summary>
internal sealed class UpdateTaxRateValidator : MiddlewareComponent, IValidator<UpdateTaxRateArgs>
{
public UpdateTaxRateValidator(ITaxRateCache cache)
{
Service = cache;
}
private ITaxRateCache Service { get; }
public async Task Validate(UpdateTaxRateArgs args)
{
/*
* A difference from the insert validator is to exclude the id of the updating record.
*/
if (await (from dc in Service where string.Equals(dc.Name, args.Name, StringComparison.OrdinalIgnoreCase) && dc.Id != args.Id select dc).AsEntity() is ITaxRate existing)
throw ValidationExceptions.ValueExists(nameof(args.Name), args.Name);
}
}
Loading…
Cancel
Save