How to bubble up event in Composition Api Vue 3

The naive way to do it…

Child component (event bubbled from)

<!-- ChildComponent.vue -->
<template>
  <button @click="handleClick">Click Me!</button>
</template>

<script setup>
import { defineEmits } from 'vue'

const emits = defineEmits(['clicked'])

function handleClick() {
  emits('clicked', 'Some data')
}
</script>

Intermediate component

<!-- IntermediateComponent.vue -->
<template>
  <ChildComponent @clicked="handleClicked" />
</template>

<script setup>
import ChildComponent from './ChildComponent.vue'
import { defineEmits } from 'vue'

const emits = defineEmits(['clicked'])

function handleClicked(data) {
  // Bubble up the event to the parent of the WrapperComponent
  emits('clicked', data)
}
</script>

Parent component

<!-- ParentComponent.vue -->
<template>
  <div>
    <IntermediateComponent @clicked="onChildClicked" />
  </div>
</template>

<script setup>
function onChildClicked(data) {
  console.log('Event data from child:', data)
}
</script>

The more straightforward way to do it

<!-- IntermediateComponent.vue -->
<template>
  <ChildComponent v-bind="$attrs" @update:modelValue="handleModelUpdate" />
</template>

<script setup>
import ChildComponent from './ChildComponent.vue'
import { defineEmits } from 'vue'

// Emit function that captures all event names
const emits = defineEmits()

function handleModelUpdate(value) {
  emits('update:modelValue', value)
}
</script>

Jointure implementation in Typescript

Sometimes when you want to manage your code efficiency you may need to optimize some Java implementations.

Jointure implementation in Typescript may be such a case.

Underneath you will find my proposal to implement a jointure in Typescript environment. This is a generic code and may be optimized in many way for your implementation needs.

class ArrayExtensions {

    static innerJoin<TL, TR, TK, TJ>(lefts: TL[], rights: TR[], onLeftKey: (l: TL) => TK, onRightKey: (r: TR) => TK, joinBuilder: (l: TL, r: TR) => TJ): TJ[] {
        const leftsWithKeys = lefts.map(l => [l, onLeftKey(l)] as [TL, TK]);
        const rightsWithKeys = rights.map(r => [r, onRightKey(r)] as [TR, TK]);
        const rightGroupsByKey = rightsWithKeys.reduce((acc, [r, key]) => {
            if (!acc[key]) acc[key] = [];
            acc[key].push(r);
            return acc;
        }, {} as Record<TK, TR[]>);
        const result = leftsWithKeys.flatMap(([l, key]) => {
            const joineds = rightGroupsByKey[key] || [];
            return joineds.map(joined => joinBuilder(l, joined));
        });
        return result;
    }

    static leftJoin<TL, TR, TK, TJ>(lefts: TL[], rights: TR[], onLeftKey: (l: TL) => TK, onRightKey: (r: TR) => TK, joinBuilder: (l: TL, r: TR | null) => TJ, defaultRight?: TR): TJ[] {
        const leftsWithKeys = lefts.map(l => [l, onLeftKey(l)] as [TL, TK]);
        const rightsWithKeys = rights.map(r => [r, onRightKey(r)] as [TR, TK]);
        const rightGroupsByKey = rightsWithKeys.reduce((acc, [r, key]) => {
            if (!acc[key]) acc[key] = [];
            acc[key]. push(r);
            return acc;
        }, {} as Record<TK, TR[]>);
        const result = leftsWithKeys.flatMap(([l, key]) => {
            const joineds = rightGroupsByKey[key] || (defaultRight ? [defaultRight] : []);
            return joineds.map(joined => joinBuilder(l, joined));
        });
        return result;
    }

    static fullJoin<TL, TR, TK>(lefts: TL[], rights: TR[], leftKeyFunc: (l: TL) => TK, rightKeyFunc: (r: TR) => TK, defaultLeft?: TL, defaultRight?: TR): [TL | undefined, TR | undefined][] {
        const leftJoinedToRight = this.leftJoin(lefts, rights, leftKeyFunc, rightKeyFunc, (l, r) => [l, r] as [TL, TR | undefined], defaultRight);
        const joinedRightKeys = new Set<TK>(leftJoinedToRight.filter(m => m[1] !== undefined).map(m => rightKeyFunc(m[1]!)));
        const defaultLeftAndMissingRights = rights
            .map(r => [r, rightKeyFunc(r)] as [TR, TK])
            .filter(([_, key]) => !joinedRightKeys.has(key))
            .map(([r, _]) => [defaultLeft, r] as [TL | undefined, TR]);
        const fullJointure = leftJoinedToRight.concat(defaultLeftAndMissingRights);
        return fullJointure;
    }
}

Underneath the related unit tests

import { ArrayExtensions } from './ArrayExtensions';
// adjust the import path as necessary

describe('ArrayExtensions', () => {
    describe('innerJoin', () => {
        it('should correctly perform an inner join on two arrays', () => {
            const lefts = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }];
            const rights = [{ employeeId: 1, department: "Engineering" }, { employeeId: 2, department: "Human Resources" }];
            const result = ArrayExtensions.innerJoin(
                lefts,
                rights,
                l => l.id,
                r => r.employeeId,
                (l, r) => ({ name: l.name, department: r.department })
            );
            expect(result).toEqual([
                { name: "Alice", department: "Engineering" },
                { name: "Bob", department: "Human Resources" }
            ]);
        });
    });

    describe('leftJoin', () => {
        it('should correctly perform a left join on two arrays', () => {
            const lefts = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }, { id: 3, name: "Charlie" }];
            const rights = [{ employeeId: 1, department: "Engineering" }, { employeeId: 2, department: "Human Resources" }];
            const result = ArrayExtensions.leftJoin(
                lefts,
                rights,
                l => l.id,
                r => r.employeeId,
                (l, r) => ({ name: l.name, department: r ? r.department : "None" })
            );
            expect(result).toEqual([
                { name: "Alice", department: "Engineering" },
                { name: "Bob", department: "Human Resources" },
                { name: "Charlie", department: "None" }
            ]);
        });
    });

    describe('fullJoin', () => {
        it('should correctly perform a full join on two arrays', () => {
            const lefts = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }];
            const rights = [{ employeeId: 2, department: "Human Resources" }, { employeeId: 3, department: "Marketing" }];
            const result = ArrayExtensions.fullJoin(
                lefts,
                rights,
                l => l.id,
                r => r.employeeId,
                { id: 0, name: "Unknown" },
                { employeeId: 0, department: "None" }
            );
            expect(result).toEqual([
                [{ id: 1, name: "Alice" }, undefined],
                [{ id: 2, name: "Bob" }, { employeeId: 2, department: "Human Resources" }],
                [undefined, { employeeId: 3, department: "Marketing" }]
            ]);
        });
    });
});

Jointure implementation in Java 21

Sometimes when you want to manage your code efficiency you may need to optimize some Java implementations.

Jointure implementation in Java 21 may be such a case.

Underneath you will find my proposal to implement a jointure in Java 21 environment. This is a generic code and may be optimized in many way for your implementation needs. It use System.Linq but remediation can be done very easily to not depend on this library.

package joins;

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Extensions {

    public static <TL, TR, TK, TJ> List<TJ> innerJoin(List<TL> lefts, List<TR> rights,
                                                      Function<TL, TK> onLeftKey, Function<TR, TK> onRightKey,
                                                      BiFunction<TL, TR, TJ> joinBuilder) {
        Map<TK, List<TR>> rightGroupsByKey = rights.stream()
                .collect(Collectors.groupingBy(onRightKey));

        return lefts.stream()
                .flatMap(left -> {
                    TK key = onLeftKey.apply(left);
                    List<TR> matchedRights = rightGroupsByKey.getOrDefault(key, Collections.emptyList());
                    return matchedRights.stream().map(right -> joinBuilder.apply(left, right));
                })
                .collect(Collectors.toList());
    }

    public static <TL, TR, TK> List<Pair<TL, TR>> leftJoin(List<TL> lefts, List<TR> rights,
                                                           Function<TL, TK> onLeftKey, Function<TR, TK> onRightKey) {
        return leftJoin(lefts, rights, onLeftKey, onRightKey, Pair::new, null);
    }

    public static <TL, TR, TK> List<Pair<TL, TR>> leftJoin(List<TL> lefts, List<TR> rights,
                                                           Function<TL, TK> onLeftKey, Function<TR, TK> onRightKey,
                                                           TR defaultJoined) {
        return leftJoin(lefts, rights, onLeftKey, onRightKey, Pair::new, defaultJoined);
    }

    public static <TL, TR, TK, TJ> List<TJ> leftJoin(List<TL> lefts, List<TR> rights,
                                                     Function<TL, TK> onLeftKey, Function<TR, TK> onRightKey,
                                                     BiFunction<TL, TR, TJ> joinBuilder, TR defaultJoined) {
        Map<TK, List<TR>> rightGroupsByKey = rights.stream()
                .collect(Collectors.groupingBy(onRightKey));
        return lefts.stream()
                .flatMap(left -> {
                    TK key = onLeftKey.apply(left);
                    List<TR> matchedRights = rightGroupsByKey.getOrDefault(key, Collections.singletonList(defaultJoined));
                    return matchedRights.stream().map(right -> joinBuilder.apply(left, right));
                })
                .collect(Collectors.toList());
    }

    public static <TL, TR, TK> List<Pair<TL, TR>> fullJoin(List<TL> lefts, List<TR> rights,
                                                           Function<TL, TK> leftKeyFunc, Function<TR, TK> rightKeyFunc,
                                                           TL defaultLeft, TR defaultRight) {
        List<Pair<TL, TR>> leftJoinResult = leftJoin(lefts, rights, leftKeyFunc, rightKeyFunc, defaultRight);
        Set<TK> joinedRightKeys = leftJoinResult.stream()
                .filter(pair -> pair.getRight() != defaultRight)
                .map(pair -> rightKeyFunc.apply(pair.getRight()))
                .collect(Collectors.toSet());

        List<Pair<TL, TR>> defaultLeftAndMissingRights = rights.stream()
                .filter(right -> !joinedRightKeys.contains(rightKeyFunc.apply(right)))
                .map(right -> new Pair<>(defaultLeft, right))
                .toList();

        List<Pair<TL, TR>> fullJoinResult = new ArrayList<>(leftJoinResult);
        fullJoinResult.addAll(defaultLeftAndMissingRights);

        return fullJoinResult;
    }
}

package joins;

import java.util.Objects;

public class Pair<L, R> {
    private final L left;
    private final R right;

    public Pair(L left, R right) {
        this.left = left;
        this.right = right;
    }

    public L getLeft() {
        return left;
    }

    public R getRight() {
        return right;
    }

    @Override
    public int hashCode() {
        return left.hashCode() ^ right.hashCode();
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Pair)) return false;
        Pair<?, ?> p = (Pair<?, ?>) o;
        return Objects.equals(p.left, left) && Objects.equals(p.right, right);
    }

    @Override
    public String toString() {
        return "(" + left + ", " + right + ")";
    }
}

Underneath the related unit tests

package joins;


import java.util.Arrays;
import java.util.List;

import org.testng.annotations.Test;

import static org.testng.AssertJUnit.*;

public class JoinOperationsTest {

    @Test
    public void testInnerJoin() {
        List<Person> persons = Arrays.asList(
                new Person(1, "Alice", 1),
                new Person(2, "Bob", 2),
                new Person(3, "Charlie", 3)
        );

        List<Department> departments = Arrays.asList(
                new Department(1, "HR"),
                new Department(2, "Engineering"),
                new Department(3, "Marketing")
        );

        List<Pair<Person, Department>> results = Extensions.innerJoin(
                persons, departments,
                Person::getDepartmentId, Department::getId,
                Pair::new
        );

        assertEquals(3, results.size());
        assertTrue(results.contains(new Pair<>(persons.get(0), departments.get(0))));
    }

    @Test
    public void testLeftJoinWithNoMatchingRight() {
        List<Person> persons = Arrays.asList(
                new Person(1, "Alice", 1),
                new Person(2, "Bob", 4) // No matching department
        );

        List<Department> departments = Arrays.asList(
                new Department(1, "HR")
        );

        List<Pair<Person, Department>> results = Extensions.leftJoin(
                persons, departments,
                Person::getDepartmentId, Department::getId,
                Pair::new, null
        );

        assertEquals(2, results.size());
        assertNotNull(results.get(0).getRight()); // Should have a department
        assertNull(results.get(1).getRight()); // Should not have a department
    }
}
package joins;

public class Department {
    private int id;
    private String name;

    // Constructor, getters and setters
    public Department(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

package joins;

public class Person {
    private int id;
    private String name;
    private int departmentId;

    // Constructor, getters and setters
    public Person(int id, String name, int departmentId) {
        this.id = id;
        this.name = name;
        this.departmentId = departmentId;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(int departmentId) {
        this.departmentId = departmentId;
    }
}

Github implementation in java : https://github.com/cosXsinX/javaJoins

Regex Pattern recursion famous test solution

It has become very common and thus having a test without a solution for me as I badly blundered because of these test for a specific candidature make me think that it may has become very interesting to keep solution somewhere on my website.

This is the acceptation tests :

using NUnit.Framework;

namespace maximilien.zakowski.Tests
{
    public class Tests
    {
        private Library BuildTested()
        {
            return new ParenthesesBracketsPatternTester();
        }

        [TestCase("()")]
        [TestCase("[]")]
        [TestCase("[()]")]
        [TestCase("[[()]]")]
        [TestCase("[()[]]")]
        [TestCase("([()[]])")]
        public void Test1(string validated)
        {
            var tested = BuildTested();
            Assert.IsTrue(tested.IsValid(validated));
        }
    }
}

The solution to this problems is the regex Pattern recursion :

Source : https://www.regular-expressions.info/refrecurse.html

The solution underneath :

using System.Text.RegularExpressions;

namespace maximilien.zakowski
{
    public class ParenthesesBracketsPatternTester
    {
        public bool IsValid(string validated)
        {
            var regex = new Regex("(?'group'(\\(\\)|\\[\\]))((?'group')|(\\((?'group')\\))|(\\[(?'group')\\]))");
            return regex.IsMatch(validated);
        }
    }
}

Pattern Binder – BinderDirector – C#

Very usefull in ressource aggregation, here you will find a code snippet that can be integrated in Inversion Of Control pattern using Interface Segregation Principle of SOLID designing principles.

public interface IBinder
    {

    }

    public interface IBinder<in T> : IBinder
    {
        void Bind(IEnumerable<T> bounds);
    }

    public interface IBinderDirector<T> 
    {
        IBinder<T>[] DataBinders { get; }

        void Bind(IEnumerable<T> bounds);
        void BindParallel(IEnumerable<T> bounds);
        void BindOnlySelected(IEnumerable<T> bounds, IEnumerable<Type> selecteds);
        void BindAllExcept(IEnumerable<T> bounds,IEnumerable<Type> excepts);
        void BindOnlySelectedParallel(IEnumerable<T> bounds,IEnumerable<Type> selecteds);
        void BindAllExceptParallel(IEnumerable<T> bounds,IEnumerable<Type> excepts);
    }


    public class BinderDirector<T> : IBinderDirector<T>
    {
        private readonly IBinder<T>[] _dataBinders;
        public IBinder<T>[] DataBinders => throw new NotImplementedException();

        public BinderDirector(IEnumerable<IBinder<T>> dataBinders)
        {
            _dataBinders = (dataBinders ?? Enumerable.Empty<IBinder<T>>()).ToArray();
        }

        public void Bind(IEnumerable<T> bounds)
        {
            var boundAsList = bounds.ToArray();
            foreach(var dataBinder in _dataBinders) dataBinder.Bind(boundAsList);
        }

        public void BindAllExcept(IEnumerable<T> bounds, IEnumerable<Type> excepts)
        {
            var boundArray = bounds.ToArray();
            var runnableDataBinders = _dataBinders.Where(m => excepts.Any(s => !s.IsAssignableFrom(m.GetType())));
            foreach (var dataBinder in runnableDataBinders) dataBinder.Bind(bounds);
        }

        public void BindAllExceptParallel(IEnumerable<T> bounds, IEnumerable<Type> excepts)
        {
            var boundArray = bounds.ToArray();
            var runnableDataBinders = _dataBinders.Where(m => excepts.Any(s => !s.IsAssignableFrom(m.GetType())));
            Parallel.ForEach(runnableDataBinders, (runnableDataBinder, index) => runnableDataBinder.Bind(bounds));
        }

        public void BindOnlySelected(IEnumerable<T> bounds, IEnumerable<Type> selecteds)
        {
            var boundArray = bounds.ToArray();
            var runnableDataBinders = _dataBinders.Where(m => selecteds.Any(s => s.IsAssignableFrom(m.GetType())));
            foreach (var dataBinder in runnableDataBinders) dataBinder.Bind(bounds);
        }

        public void BindOnlySelectedParallel(IEnumerable<T> bounds, IEnumerable<Type> selecteds)
        {
            var boundArray = bounds.ToArray();
            var runnableDataBinders = _dataBinders.Where(m => selecteds.Any(s => s.IsAssignableFrom(m.GetType())));
            Parallel.ForEach(runnableDataBinders, (runnableDataBinder, index) => runnableDataBinder.Bind(bounds));
        }

        public void BindParallel(IEnumerable<T> bounds)
        {
            var boundArray = bounds.ToArray();
            Parallel.ForEach(_dataBinders, dataBinder => dataBinder.Bind(boundArray));
        }
    }

Underneath you will find an example of concrete implementation. The thing which is interesant, is that the BinderDirector is a pure interpretation of the Interface Segregation Principle :

public interface IWithBindPropertiesA
    {
        string IdentifierA { get; }
        string ReturnedPropertyValueA { set; }
    }

    public interface IWithBindPropertiesB
    {
        string IdentifierB { get; }
        string ReturnedPropertyValueB { set; }
    }

    public class ConcreteImplementation : IWithBindPropertiesA, IWithBindPropertiesB
    {
        public new string IdentifierA { get; set; }

        public new string ReturnedPropertyValueA { get; set; }

        public new string IdentifierB { get; set; }

        public new string ReturnedPropertyValueB { get; set; }
    }


    public class BindPropertiesABinder : IBinder<IWithBindPropertiesA>
    {
        public void Bind(IEnumerable<IWithBindPropertiesA> bounds)
        {
            foreach(var bound in bounds)
            {
                bound.ReturnedPropertyValueA = bound.IdentifierA == "A"?"A":"unknown"; //In fact you can do what you want
            }
        }
    }
    public class BindPropertiesBBinder : IBinder<IWithBindPropertiesB>
    {
        public void Bind(IEnumerable<IWithBindPropertiesB> bounds)
        {
            foreach (var bound in bounds)
            {
                bound.ReturnedPropertyValueB = bound.IdentifierB == "B" ? "B" : "unknown"; //In fact you can do what you want
            }
        }
    }

    public static class Program
    {
        public static void Main(string[] argc)
        {
            var binderDirector = new BinderDirector<ConcreteImplementation>(new IBinder<ConcreteImplementation>[] {
                new BindPropertiesABinder(),
                new BindPropertiesBBinder()
            });
        }
    }

LMAX Disruptor Pattern

Disruptor pattern stem it’s performance due to the current architecture of computers.

The architecture relavance remain in :

  • Zero memory allocation after initial setup
  • Push based consumers
  • The feeder is attached to only one thread and have minimal workload (it dispatch the data – rolling cache)

Everything mentioned upper make the LMAX Disruptor pattern a low latency pattern.

.Net implementation is available here :

https://github.com/disruptor-net/Disruptor-net

Fast exponentiation – C# implementation

When you want to power very fast a number in order to meet some performance constraints the standard math power algorithm implementation can be overwhelmed.

Fast exponentiation algorithm take advantage of the computer binary memory structure in order to avoid complexe arithmetic computation.

This algorithm allows you to raise any number to a natural power for a reduced number of multiplications.

For any number and even degree , the identity holds:

= (x n / 2 = x n / 2 ⋅ x n / 2

For the case of odd degree, it is enough to lower it by one:

= x n – 1 ⋅ x , while (n – 1) is an even number.

Fast exponentiation – recursive implementation (beware of stack overflow)

static long RecursivePower(long x, int n)
{
    if (n == 0) return 1; //in any case Power(x,0) give 1
    if ((n & 1) == 0) //Bit comparison to check if is an even number
    {
        var p = RecursivePower(x, n >> 1); //Equivalent to Power(x, n/2)
        return p * p;
    }
    else
    {
        return x * RecursivePower(x, n - 1);
    }
}

Fast exponentiation – Iterative implementation

static long IterativePower(long x, int n)
{
    var result = 1L;
    while (n> 0)
    {
        if ((n & 1) == 0) //Bit comparison to check if is an even number
        {
            x *= x;
            n >>= 1;
        }
        else
        {
            result *= x;
            --n;
        }
    }
    return result;
}

C++ equivalent implementation of C# interface

Sometimes when learning from one language to another one, you may have to adapt your habit to the paradigm of language and it’s evolution degree.

Interface for C# developer is one of the pillar of SOLID Implementation Principles. In the C++ development the equivalence is not trivial enough in my opinion.

Response : virtual C++ classes

Interface in C#

//ICompte.cs file
public interface ICompte
{
    double retirerArgent(double montant);
    double ajouterArgent(double montant);
    double Solde {get;}
}

C++ equivalent implementation

//ICompte.h file
class ICompte
{
public:
	virtual double retirerArgent(double montant) = 0;
	virtual double ajouterArgent(double montant) = 0;
	virtual double getSolde() = 0;
};

TestValueFactory C# & Mapper Tests

When you’re writing tests, especially mapper tests, knowing the value which is mapped is not of great use. What you’re testing is that the value is correctly mapped, or bound to the accurate location in destination.

Mapping is very often not considered by young developer (and sometimes senior developer) as a source of error. In my opinion, actually it is. Thus, that’s why I am sharing those code snippets to help people writing tests on mappers.

Keep this sentence in mind, when writing tests in group code project : “Backup your a** !”. Everything can be a source of error.

The TestValueHelper implementation provide issue resolution to handle random type value generation. This class is certainly to be developped.

using System;
using System.Collections.Generic;

namespace maximilienzakowski.com.TestToolKit
{
    public static class TestValueFactory
    {
        private static readonly Random _random = new Random();

        public static int GetRandomIntValue()
        {
            return _random.Next();
        }

        public static int GetRandomIntValue(int minValue, int maxValue)
        {
            return _random.Next(minValue, maxValue);
        }

        public static int GetRandomIntValue(int[] except)
        {
            var exceptSet = new HashSet<int>(except??new int[] { });
            int result;
            do
            {
                result = _random.Next();
            }
            while (exceptSet.Contains(result));
            return result;
        }

        public static DateTime GetRandomDateTimeValue()
        {
            DateTime start = new DateTime(1970, 1, 1);
            int range = (DateTime.Today - start).Days;
            return start.AddDays(_random.Next(range))
                .AddHours(_random.Next(0, 24))
                .AddMinutes(_random.Next(0, 60))
                .AddSeconds(_random.Next(0, 60));
        }

        public static double GetRandomDoubleValue()
        {
            return _random.Next() * _random.NextDouble();
        }

        public static decimal GetRandomDecimalValue()
        {
            double RandH, RandL;
            do
            {
                RandH = _random.NextDouble();
                RandL = _random.NextDouble();
            } while ((RandH > 0.99999999999999d) || (RandL > 0.99999999999999d));
            return (decimal)RandH + (decimal)RandL / 1E14m;
        }
        public static decimal GetRandomDecimalValue( decimal minValue, decimal maxValue)
        {
            return GetRandomDecimalValue() * (maxValue - minValue) + minValue;
        }

        public static T GetRandomEnumValue<T>() where T : System.Enum
        {
            var values = Enum.GetValues(typeof(T));
            return (T)values.GetValue(_random.Next(0,values.Length-1));
        }

        public static string GetRandomStringValue()
        {
            return GetRandomStringValue(20);
        }

        public static string GetRandomStringValue(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            return new string(Enumerable.Repeat(chars, length).Select(s => s[_random.Next(s.Length)]).ToArray());
        }
    }
}

Tested code snippet which is a builder + mapper association :

public class ItemToInvoiceRowConverter2
    {
        public IInvoiceRow Convert(IItem converted)
        {
            if (converted == null) return null;
            var result = new InvoiceRow();
            //result.Number = converted.Id;
            result.IdItem = converted.Id;
            result.Kind = converted.Kind;
            result.Label = converted.Name;
            //result.Vat = converted.;
            result.Unit = converted.Unit;
            result.UnitPrice = converted.Price;
            //result.Discount = converted.Id;
            //result.Quantity = converted.Id;
            return result;
        }
    }

Unit test code :

using myApplication.Converters;
using myApplication.Models;
using maximilienzakowski.com.TestToolKit;
using Moq;
using NUnit.Framework;

namespace myApplication.Tests
{
    [TestFixture]
    public class ItemToInvoiceRowConverterTests
    {
        private ItemToInvoiceRowConverter2 BuildTested()
        {
            return new ItemToInvoiceRowConverter2();
        }

        [Test]
        public void ConvertShouldReturnNullWhenConvertedIsNull()
        {
            var tested = BuildTested();
            var result = tested.Convert(null);
            Assert.IsNull(result);
        }


        [Test]
        public void ConvertShouldConvertAndMapAccurately()
        {
            var converted = new Mock<IItem>();
            var id = TestValueFactory.GetRandomIntValue();
            var kind = TestValueFactory.GetRandomStringValue();
            var name = TestValueFactory.GetRandomStringValue();
            var unit = TestValueFactory.GetRandomStringValue();
            var price = TestValueFactory.GetRandomDecimalValue();

            converted.SetupGet(x => x.Id).Returns(id);
            converted.SetupGet(x => x.Kind).Returns(kind);
            converted.SetupGet(x => x.Name).Returns(name);
            converted.SetupGet(x => x.Unit).Returns(unit);
            converted.SetupGet(x => x.Price).Returns(price);
            var tested = BuildTested();
            var result = tested.Convert(converted.Object);
            Assert.IsNotNull(result);
            Assert.AreEqual(id, result.IdItem);
            Assert.AreEqual(kind, result.Kind);
            Assert.AreEqual(name, result.Label);
            Assert.AreEqual(unit, result.Unit);
            Assert.AreEqual(price, result.UnitPrice);

            converted.VerifyGet(x => x.Id,Times.Once);
            converted.VerifyGet(x => x.Kind, Times.Once);
            converted.VerifyGet(x => x.Name, Times.Once);
            converted.VerifyGet(x => x.Unit, Times.Once);
            converted.VerifyGet(x => x.Price, Times.Once);
            converted.VerifyNoOtherCalls();
        }
    }
}

Hope this will help someone else than me…

Linq.Net To SqlLite Converter implementation attempt

Sometimes when you want to manage your code efficiency you may need to optimize some .Net implementation.

Instead of relying on Entity Framework or other closed binary implementation you may need to implement your specific AdHoc behavior, this is a good example to do so…

Underneath you will find my proposal to implement a Linq to SQLLite conversion with C#. This is a generic code and may be optimized in many way for your implementation needs. It use System.Linq but remediation can be done very easily to not depend on this library.

using System.Collections;
using System.Linq.Expressions;
using System.Reflection;

namespace Com.Maximilienzakowski.Dal.Common.Repository
{
    public interface ICommandTextWhereArgBuilder<T> where T : class
    {
        string Build(Expression<Func<T, bool>> whereExpression);
        string Build(Expression node);
    }

    public class SqliteCommandTextWhereArgBuilder<T> : ICommandTextWhereArgBuilder<T> where T : class
    {
        private readonly IDictionary<ExpressionType,ISqlLiteWhereCommandExpressionBuilder> _whereExpressionsBuilders;
        private readonly IObjectToSqlValueConverter _objectToSqlValueConverter = new ObjectToSqlValueConverter();
        public SqliteCommandTextWhereArgBuilder()
        {
            var sqlLiteWhereCommandExpressionBuilders = new ISqlLiteWhereCommandExpressionBuilder[]
            {
                new SqlLiteLambdaWhereCommandExpressionBuilder<T>(this),
                new SqlLiteAndWhereCommandExpressionBuilder<T>(this),
                new SqlLiteAndAlsoWhereCommandExpressionBuilder<T>(this),
                new SqlLiteEqualWhereCommandExpressionBuilder<T>(this),
                new SqlLiteContainsCallWhereCommandExpressionBuilder<T>(this),
                new SqliteConvertAccessWhereCommandExpressionBuilder<T>(this),
                new SqliteMemberAccessWhereCommandExpressionBuilder<T>(_objectToSqlValueConverter),
                new SqliteConstantWhereCommandExpressionBuilder<T>(_objectToSqlValueConverter),
                
            };
            _whereExpressionsBuilders = sqlLiteWhereCommandExpressionBuilders.ToDictionary(m => m.ExpressionType, m => m);
        }


        public string Build(Expression<Func<T, bool>> whereExpression)
        {
            var expression = whereExpression.Reduce;
            return Build(expression());
        }

        public string Build(Expression node)
        {
            if(!_whereExpressionsBuilders.TryGetValue(node.NodeType, out var whereExpressionBuilder)) return "UNDEFINED EXPRESSION BUILDER";
            return whereExpressionBuilder.Build(node);
        }
    }

    public class SqlLiteContainsCallWhereCommandExpressionBuilder<T> : ISqlLiteWhereCommandExpressionBuilder where T : class
    {
        private readonly ICommandTextWhereArgBuilder<T> _commandTextWhereArgBuilder;
        public ExpressionType ExpressionType => ExpressionType.Call;
        public SqlLiteContainsCallWhereCommandExpressionBuilder(ICommandTextWhereArgBuilder<T> commandTextWhereArgBuilder)
        {
            _commandTextWhereArgBuilder = commandTextWhereArgBuilder ?? throw new ArgumentNullException(nameof(commandTextWhereArgBuilder));
        }
        public string Build(Expression? node)
        {
            if (node.NodeType != ExpressionType.Call) return string.Empty;
            var methodCallNode = (MethodCallExpression)node;
            if (methodCallNode.Method.Name != "Contains") return "UNHANDLED METHOD CALL";
            if(methodCallNode.Arguments.Count == 2)
            {
                return $"({ _commandTextWhereArgBuilder.Build(methodCallNode.Arguments.Last())} IN {_commandTextWhereArgBuilder.Build(methodCallNode.Arguments.First())})";
            }
            else if(methodCallNode.Arguments.Count == 1)
            {
                var left = _commandTextWhereArgBuilder.Build(methodCallNode.Arguments.Single());
                return $"({left} IN {_commandTextWhereArgBuilder.Build(methodCallNode.Object)})";
            }
            return "UNHANDLED CONTAINS METHOD CALL";
        }
    }


    public class SqlLiteLambdaWhereCommandExpressionBuilder<T> : ISqlLiteWhereCommandExpressionBuilder where T : class
    {
        private readonly ICommandTextWhereArgBuilder<T> _commandTextWhereArgBuilder;
        public ExpressionType ExpressionType => ExpressionType.Lambda;
        public SqlLiteLambdaWhereCommandExpressionBuilder(ICommandTextWhereArgBuilder<T> commandTextWhereArgBuilder)
        {
            _commandTextWhereArgBuilder = commandTextWhereArgBuilder ?? throw new ArgumentNullException(nameof(commandTextWhereArgBuilder));
        }
        public string Build(Expression? node)
        {
            if(node.NodeType != ExpressionType.Lambda) return string.Empty;
            var lambdaNode = (LambdaExpression)node;
            return _commandTextWhereArgBuilder.Build(lambdaNode.Body);
        }
    }

    public class SqlLiteAndWhereCommandExpressionBuilder<T> : ISqlLiteWhereCommandExpressionBuilder where T : class
    {
        private readonly ICommandTextWhereArgBuilder<T> _commandTextWhereArgBuilder;

        public ExpressionType ExpressionType => ExpressionType.And;
        public SqlLiteAndWhereCommandExpressionBuilder(ICommandTextWhereArgBuilder<T> commandTextWhereArgBuilder)
        {
            _commandTextWhereArgBuilder = commandTextWhereArgBuilder ?? throw new ArgumentNullException(nameof(commandTextWhereArgBuilder));
        }

        public string Build(Expression? node)
        {
            if (node.NodeType != ExpressionType) return string.Empty;
            var binaryExpressionType = (BinaryExpression)node;
            return $"({_commandTextWhereArgBuilder.Build(binaryExpressionType.Left)}) AND ({_commandTextWhereArgBuilder.Build(binaryExpressionType.Right)})";
        }
    }

    public class SqlLiteAndAlsoWhereCommandExpressionBuilder<T> : ISqlLiteWhereCommandExpressionBuilder where T : class
    {
        private readonly ICommandTextWhereArgBuilder<T> _commandTextWhereArgBuilder;

        public ExpressionType ExpressionType => ExpressionType.AndAlso;
        public SqlLiteAndAlsoWhereCommandExpressionBuilder(ICommandTextWhereArgBuilder<T> commandTextWhereArgBuilder)
        {
            _commandTextWhereArgBuilder = commandTextWhereArgBuilder ?? throw new ArgumentNullException(nameof(commandTextWhereArgBuilder));
        }

        public string Build(Expression? node)
        {
            if (node.NodeType != ExpressionType) return string.Empty;
            var binaryExpressionType = (BinaryExpression)node;
            return $"({_commandTextWhereArgBuilder.Build(binaryExpressionType.Left)}) AND ({_commandTextWhereArgBuilder.Build(binaryExpressionType.Right)})";
        }
    }

    public class SqlLiteEqualWhereCommandExpressionBuilder<T> : ISqlLiteWhereCommandExpressionBuilder where T : class
    {
        private readonly ICommandTextWhereArgBuilder<T> _commandTextWhereArgBuilder;

        public ExpressionType ExpressionType => ExpressionType.Equal;
        public SqlLiteEqualWhereCommandExpressionBuilder(ICommandTextWhereArgBuilder<T> commandTextWhereArgBuilder)
        {
            _commandTextWhereArgBuilder = commandTextWhereArgBuilder ?? throw new ArgumentNullException(nameof(commandTextWhereArgBuilder));
        }

        public string Build(Expression? node)
        {
            if (node.NodeType != ExpressionType) return string.Empty;
            var binaryExpressionType = (BinaryExpression)node;
            return $"{_commandTextWhereArgBuilder.Build(binaryExpressionType.Left)} = {_commandTextWhereArgBuilder.Build(binaryExpressionType.Right)}";
        }
    }

    public class SqliteMemberAccessWhereCommandExpressionBuilder<T> : ISqlLiteWhereCommandExpressionBuilder where T : class
    {

        private readonly IObjectToSqlValueConverter _objectToSqlValueConverter;
        public ExpressionType ExpressionType => ExpressionType.MemberAccess;
        public SqliteMemberAccessWhereCommandExpressionBuilder(IObjectToSqlValueConverter objectToSqlValueConverter)
        {
            _objectToSqlValueConverter = objectToSqlValueConverter ?? throw new ArgumentNullException(nameof(objectToSqlValueConverter));
        }

        public string Build(Expression? node)
        {
            if (node.NodeType != ExpressionType) return string.Empty;
            var memberExpression = (MemberExpression)node;
            if(memberExpression.Member.MemberType == MemberTypes.Field)
            {
                if(memberExpression.Expression == null) return "NULL UNDERLYING EXPRESSION IN MEMBER EXPRESSION";
                if (memberExpression.Expression.NodeType != ExpressionType.Constant) return "NOT A CONSTANT EXPRESSION NODE TYPE IN MEMBER EXPRESSION";
                var constantExpression = (ConstantExpression)memberExpression.Expression;
                var fieldInfo = (FieldInfo)memberExpression.Member;
                return $"\"{_objectToSqlValueConverter.Convert(fieldInfo.GetValue(constantExpression.Value))}\"";
            }
            return $"\"{memberExpression?.Member?.Name}\"";
        }
    }

    public class SqliteConvertAccessWhereCommandExpressionBuilder<T> : ISqlLiteWhereCommandExpressionBuilder where T : class
    {

        private readonly ICommandTextWhereArgBuilder<T> _commandTextWhereArgBuilder;
        public ExpressionType ExpressionType => ExpressionType.Convert;
        public SqliteConvertAccessWhereCommandExpressionBuilder(ICommandTextWhereArgBuilder<T> commandTextWhereArgBuilder)
        {
            _commandTextWhereArgBuilder = commandTextWhereArgBuilder ?? throw new ArgumentNullException(nameof(commandTextWhereArgBuilder));
        }

        private static readonly IDictionary<Tuple<Type, Type>, string> _formatBySourceAndDestinationTupleTypes =
            new Dictionary<Tuple<Type, Type>, string>()
            {
                {Tuple.Create(typeof(int),typeof(long)), "{0}" },
            };

        public string Build(Expression? node)
        {
            if (node.NodeType != ExpressionType) return string.Empty;
            var unaryExpression = (UnaryExpression)node;
            if (!_formatBySourceAndDestinationTupleTypes.TryGetValue(Tuple.Create(unaryExpression.Operand.Type, unaryExpression.Type), out var format))
                return "UNKNONW CONVERT EXPRESSION";
            return string.Format(format, _commandTextWhereArgBuilder.Build(unaryExpression.Operand));
        }
    }

    public class SqliteConstantWhereCommandExpressionBuilder<T> : ISqlLiteWhereCommandExpressionBuilder where T : class
    {
        private readonly IObjectToSqlValueConverter _objectToSqlValueConverter1;
        public ExpressionType ExpressionType => ExpressionType.Constant;
        public SqliteConstantWhereCommandExpressionBuilder(IObjectToSqlValueConverter objectToSalValueConverter)
        {
            _objectToSqlValueConverter1 = objectToSalValueConverter ?? throw new ArgumentNullException(nameof(objectToSalValueConverter));
        }

        public string Build(Expression? node)
        {
            if (node.NodeType != ExpressionType) return string.Empty;
            var constantExpression = (ConstantExpression)node;
            return _objectToSqlValueConverter1.Convert(constantExpression.Value);
        }
    }

    


    public class ObjectToSqlValueConverter : IObjectToSqlValueConverter
    {
        private readonly IDictionary<Type, Func<object, string>> _valueConversionFuncByType =
            new Dictionary<Type, Func<object, string>>()
            {
                {typeof(string), value => $"'{value}'"},
                {typeof(int), value => $"{value}"},
                {typeof(long), value => $"{value}"},
                {typeof(short), value => $"{value}"},
                {typeof(float), value => $"{value}"},
                {typeof(double), value => $"{value}"},
                {typeof(decimal), value => $"{value}"},
            };
        public string Convert(object? value)
        {
            if (value == null) return "NULL";
            var valueType = value.GetType();
            if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                var underlyingValueType = Nullable.GetUnderlyingType(valueType);
                if (underlyingValueType == null) return "UNKNOWN CASE OF NULLABLE UNDERLYING NULL VALUE";
                return Convert(System.Convert.ChangeType(value, underlyingValueType));
            }
            if((valueType.IsArray || valueType.IsGenericType && valueType.GetGenericTypeDefinition().IsAssignableTo(typeof(IEnumerable))))
            {
                var enumerable = (IEnumerable)value;
                return $"({string.Join(",", Enumerate(enumerable).Select(Convert))})";
            }
            if (!_valueConversionFuncByType.TryGetValue(valueType, out var conversionFunc)) return "UNKNOWN TYPE";
            return conversionFunc(value);
        }

        private IEnumerable<object> Enumerate(IEnumerable enumerable)
        {
            foreach(var value in enumerable)
            {
                yield return value;
            }
        }
    }
}