#StackBounty: #c# #generics Solution of class design issue of generic of restricted type

Bounty: 50

I am developing a statistics library in .net. I have developed a Set<T> data structure. Now, I want to derive a data structure named DescriptiveStatisticalSet<T>, and I want this set to be able to operate only on integer and double types.

Problem:

I want to implement a generic type that is able to work with integer
and double data types only.

Say, I have the following interfaces and classes:

public interface IIntegerDataType  
{
    int Data { get; set; }
    int Add(int other);
}

public interface IDoubleDataType  
{
    double Data { get; set; }
    double Add(double other);
}
public class IntegerDataType : IIntegerDataType
{
    public int Data { get; set; }

    public int Add(int other)
    {
        return Data + other;
    }
}
public class DoubleDataType : IDoubleDataType
{
    public double Data { get; set; }

    public double Add(double other)
    {
        return Data + other;
    }
}

Is it possible to create a generic type DataType<T> so that both
(and only) IntegerDataType and DoubleDataType could be accessed
through that generic type?

Solution:

I have devised the following solution:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataTypeNamespace
{
    public interface IDataType
    {
        object Add(object other); 
        void SetVal(object other);
    }
    public interface IDataType<T> where T : IDataType, new()
    {
        T Add(T other);
    }
    class IntegerDataType : IDataType
    {
        public int Data { get; set; }

        public object Add(object other)
        {
            int o = ((IntegerDataType)other).Data;
            return Data + o;
        }
        public void SetVal(object other)
        {
            Data = (int)other;
        }
    }

    class DoubleDataType : IDataType
    {
        public double Data { get; set; }

        public object Add(object other)
        {
            double o = ((DoubleDataType)other).Data;
            return Data + o;
        }

        public void SetVal(object other)
        {
            Data = (double)other;
        }
    }

    public class DataType<T> : IDataType<T> where T : IDataType, new()//https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/new-constraint
    {
        IDataType _item;
        public DataType(IDataType item)
        {
            _item = item;
        }

        public T Add(T other)
        {
            object o = _item.Add(other);

            T t = new T();

            t.SetVal(o);

            return t;
        }
    }

    public class MainClass
    {
        public static void Main(string[] args)
        {
            //IntegerDataType item1 = new IntegerDataType();
            //item1.Data = 10;

            //IntegerDataType item2 = new IntegerDataType();
            //item2.Data = 20;

            //DataType<IntegerDataType> l1 = new DataType<IntegerDataType>(item1);
            //IntegerDataType sum1 = l1.Add(item2);

            DoubleDataType item3 = new DoubleDataType();
            item3.Data = 10.5;

            DoubleDataType item4 = new DoubleDataType();
            item4.Data = 20.5;

            DataType<DoubleDataType> l2 = new DataType<DoubleDataType>(item3);
            DoubleDataType sum2 = l2.Add(item4);
        }
    }
}

Can someone review this? Or, maybe help me to improve?


Get this bounty!!!

#StackBounty: #c# #performance #generics #reflection #interval Calculating time windows for entities

Bounty: 50

I have made some code that operates on multiple entities and creates ‘time windows’ for them. Basically, the entities will contain states, usually in boolean or int. They will be timestamped and in order to reduce the number of rows when creating a graph for a large date range, I am calculating time windows of 5 mins, 15 mins and 60 mins. If I’m calculating the 5 minute time windows, and a state is true from 00:00:00 to 00:02:59 and false from 00:03:00 onwards, the time window for the first 5 minutes of the day would be true, since the state was true for 3 out of 5 minutes.

I have used custom attributes, generics and reflection in order to check what properties the entities have and which of them I need to process.

The code works, but I’m sure it can be improved.

Sometimes, the code works fast for a couple of thousands of rows across 16 entities, i.e. 16 calls to the CalculateTimeWindows<T>() method (less than a second) but sometimes it’s really slow (takes some 45 seconds). Any ideas how I can optimise this code?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace Services.Helpers
{
    #region Custom Attributes
    [AttributeUsage(AttributeTargets.Property)]
    public class DoNotCopyIntoTimeWindow : System.Attribute { } // leave default

    [AttributeUsage(AttributeTargets.Property)]
    public class IsProcessedIntoTimeWindow : System.Attribute { } // calculate time window for this property

    [AttributeUsage(AttributeTargets.Property)]
    public class IsTimeWindowDate : Attribute { } // attribute to mark property as the datetime

    [AttributeUsage(AttributeTargets.Property)]
    public class IsTimeWindowIdentifier : Attribute { } // this is the time window property
    #endregion

    public class TimeWindow
    {
        #region Structs
        public struct TimeWindowDictionary
        {
            public string Name { get; set; }
            public Dictionary<NullObject<dynamic>, int> Dictionary { get; set; }
        }

        public struct NullObject<T>
        {
            [DefaultValue(true)]
            private readonly bool isnull;// default property initializers are not supported for structs

            private NullObject(T item, bool isnull) : this()
            {
                this.isnull = isnull;
                Item = item;
            }

            public NullObject(T item) : this(item, item == null)
            {
            }

            public static NullObject<T> Null()
            {
                return new NullObject<T>();
            }

            public T Item { get; private set; }

            public bool IsNull()
            {
                return isnull;
            }

            public static implicit operator T(NullObject<T> nullObject)
            {
                return nullObject.Item;
            }

            public static implicit operator NullObject<T>(T item)
            {
                return new NullObject<T>(item);
            }

            public override string ToString()
            {
                return (Item != null) ? Item.ToString() : "NULL";
            }

            public override bool Equals(object obj)
            {
                if (obj == null)
                    return IsNull();

                if (!(obj is NullObject<T>))
                    return false;

                var no = (NullObject<T>)obj;

                if (IsNull())
                    return no.IsNull();

                if (no.IsNull())
                    return false;

                return Item.Equals(no.Item);
            }

            public override int GetHashCode()
            {
                if (IsNull())
                    return 0;

                var result = Item.GetHashCode();

                if (result >= 0)
                    result++;

                return result;
            }
        }
        #endregion

        public static IEnumerable<T> CalculateTimeWindows<T>(DateTime dateFrom, DateTime dateTo, List<T> stateModels) where T : new()
        {
            if (stateModels.Count() == 0)
                return new List<T>();

            dateFrom = GetPropertiesAndDictionaries(dateFrom, stateModels, out PropertyInfo datePropertyInfo, out List<PropertyInfo> copyProperties, out PropertyInfo timeWindowIdentifier, out int size, out TimeWindowDictionary[] dictionaries, out int i);

            return CalculateTimeWindow(dateFrom, dateTo, stateModels, 5, datePropertyInfo, copyProperties, timeWindowIdentifier, size, dictionaries, i)
                        .Concat(CalculateTimeWindow(dateFrom, dateTo, stateModels, 15, datePropertyInfo, copyProperties, timeWindowIdentifier, size, dictionaries, i))
                        .Concat(CalculateTimeWindow(dateFrom, dateTo, stateModels, 60, datePropertyInfo, copyProperties, timeWindowIdentifier, size, dictionaries, i));
        }

        public static IEnumerable<T> CalculateTimeWindow<T>(DateTime dateFrom, DateTime dateTo, List<T> stateModels, byte timeWindowMinutes, PropertyInfo datePropertyInfo, List<PropertyInfo> copyProperties, PropertyInfo timeWindowIdentifier, int size, TimeWindowDictionary[] dictionaries, int i) where T : new()
        {
            if (stateModels.Count() > 0)
            {
                DateTime currentWindowFrom, currentWindowTo, nextWindowFrom;
                nextWindowFrom = dateFrom;
                int itemPointer = 0;
                T prevItem = default;
                T prevTimeWindow = default;

                KeyValuePair<NullObject<dynamic>, int> maxValue = new KeyValuePair<NullObject<dynamic>, int>();
                int j = 1;

                do // one time window
                {
                    for (i = 0; i < size; i++)
                        dictionaries[i].Dictionary = new Dictionary<NullObject<dynamic>, int>();

                    currentWindowFrom = nextWindowFrom;
                    nextWindowFrom = currentWindowFrom.AddMinutes(timeWindowMinutes);
                    currentWindowTo = nextWindowFrom.AddSeconds(-1);

                    var calculateTime = currentWindowFrom;

                    for (itemPointer = itemPointer; itemPointer < stateModels.Count(); itemPointer++)
                    {
                        var item = stateModels.ElementAt(itemPointer);

                        var date = (DateTime)datePropertyInfo.GetValue(item);

                        if (date >= currentWindowTo)
                            break;

                        var endDate = (date > currentWindowTo) ? nextWindowFrom : date; // state might extend more than the end of the time window
                        CalculateStateSeconds(prevItem, dictionaries, calculateTime, endDate);

                        prevItem = item;
                        calculateTime = (date < currentWindowFrom) ? currentWindowFrom : date; // to fix the 'yesterday' date
                    }

                    if (calculateTime < currentWindowTo)
                        CalculateStateSeconds(prevItem, dictionaries, calculateTime, nextWindowFrom);

                    if (dictionaries[0].Dictionary.Count > 0)
                    {
                        bool sameAsPrevious = (prevTimeWindow != null);
                        var output = new T();

                        foreach (var dictionary in dictionaries)
                        {
                            //var valToSet = dictionary.Dictionary.FirstOrDefault(x => x.Value.Equals(dictionary.Dictionary.Values.Max())).Key.Item;

                            for (i = 0; i < dictionary.Dictionary.Count; i++)
                            {
                                maxValue = dictionary.Dictionary.First();
                                for (j = 1; j < dictionary.Dictionary.Count; j++)
                                {
                                    var valuePair = dictionary.Dictionary.ElementAt(j);

                                    if (valuePair.Value > maxValue.Value)
                                        maxValue = valuePair;
                                }
                            }
                            var valToSet = maxValue.Key.Item;

                            if (sameAsPrevious)
                            {
                                var prevVal = GetValue(prevTimeWindow, dictionary.Name);

                                if (valToSet == null && prevVal == null)
                                { }
                                else if ((valToSet == null && prevVal != null) || (valToSet != null && prevVal == null) || !valToSet.Equals(prevVal))
                                    sameAsPrevious = false;
                            }

                            SetValue(output, dictionary.Name, valToSet);
                        }

                        if (!sameAsPrevious)
                        {
                            foreach (var copyProperty in copyProperties)
                                SetValue(output, copyProperty.Name, copyProperty.GetValue(prevItem));

                            timeWindowIdentifier.SetValue(output, timeWindowMinutes);

                            datePropertyInfo.SetValue(output, currentWindowFrom);

                            prevTimeWindow = output;

                            yield return output;
                        }
                    }
                }
                while (nextWindowFrom <= dateTo);
            }
        }

        private static DateTime GetPropertiesAndDictionaries<T>(DateTime dateFrom, List<T> stateModels, out PropertyInfo datePropertyInfo, out List<PropertyInfo> copyProperties, out PropertyInfo timeWindowIdentifier, out int size, out TimeWindowDictionary[] dictionaries, out int i) where T : new()
        {
            Type tType = typeof(T);
            var propInfos = tType.GetProperties();

            datePropertyInfo = propInfos.Single(p => p.GetCustomAttributes(typeof(IsTimeWindowDate), true).Any());
            var firstDate = (DateTime)datePropertyInfo.GetValue(stateModels.First());

            if (firstDate < dateFrom)
                dateFrom = new DateTime(firstDate.Year, firstDate.Month, firstDate.Day, firstDate.Hour, 0, 0, DateTimeKind.Utc);

            var properties = propInfos.Where(p => p.GetCustomAttributes(typeof(IsProcessedIntoTimeWindow), true).Any()).Select(x => x.Name);
            copyProperties = propInfos.Where(p => !p.GetCustomAttributes(typeof(IsTimeWindowIdentifier), true).Any() && !p.GetCustomAttributes(typeof(DoNotCopyIntoTimeWindow), true).Any() && !p.GetCustomAttributes(typeof(IsTimeWindowDate), true).Any() && !p.GetCustomAttributes(typeof(IsProcessedIntoTimeWindow), true).Any() && p.CanWrite && !p.GetMethod.IsVirtual).ToList();
            timeWindowIdentifier = propInfos.Single(p => p.GetCustomAttributes(typeof(IsTimeWindowIdentifier), true).Any());

            size = properties.Count();
            dictionaries = new TimeWindowDictionary[size];

            i = 0;
            foreach (var property in properties)
            {
                dictionaries[i] = new TimeWindowDictionary() { Name = property };
                i++;
            }

            return dateFrom;
        }

        private static dynamic GetValue(object inputObject, string propertyName)
        {
            Type type = inputObject.GetType();
            PropertyInfo propertyInfo = type.GetProperty(propertyName);
            return propertyInfo.GetValue(inputObject);
        }

        private static void SetValue(object inputObject, string propertyName, object propertyVal)
        {
            //find out the type
            Type type = inputObject.GetType();

            //get the property information based on the type
            PropertyInfo propertyInfo = type.GetProperty(propertyName);

            if (propertyVal != null)
            {
                //find the property type
                Type propertyType = propertyInfo.PropertyType;

                //Convert.ChangeType does not handle conversion to nullable types
                //if the property type is nullable, we need to get the underlying type of the property
                var targetType = IsNullableType(propertyType) ? Nullable.GetUnderlyingType(propertyType) : propertyType;

                //Returns an System.Object with the specified System.Type and whose value is
                //equivalent to the specified object.
                propertyVal = Convert.ChangeType(propertyVal, targetType);
            }

            //Set the value of the property
            propertyInfo.SetValue(inputObject, propertyVal, null);

        }

        private static bool IsNullableType(Type type)
        {
            return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
        }

        private static void CalculateStateSeconds<T>(T prevItem, IEnumerable<TimeWindowDictionary> dictionaries, DateTime calculateTime, DateTime endDate)
        {
            if (prevItem != null)
            {
                var seconds = Convert.ToInt32(endDate.Subtract(calculateTime).TotalSeconds);

                Type tType = typeof(T);

                foreach (var dictionary in dictionaries)
                {
                    PropertyInfo propertyInfo = tType.GetProperty(dictionary.Name);
                    var key = propertyInfo.GetValue(prevItem);

                    dictionary.Dictionary.TryGetValue(key, out int existingSeconds);
                    dictionary.Dictionary[key] = existingSeconds + seconds;
                }
            }
        }
    }
}

Here’s a sample class and Unit test:

public abstract class MyBaseModel : ICloneable
{
    [DoNotCopyIntoTimeWindow]
    public int Id { get; set; }

    public short fk_TenantId { get; set; }

    [IsTimeWindowIdentifier]
    public byte TimeWindow { get; set; }

    [IsTimeWindowDate]
    public DateTime Date { get; set; }

    [IsProcessedIntoTimeWindow]
    public byte ActuallyAnEnum { get; set; }

    public abstract bool CalculatorOn { get; }

    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

public class MyModel : MyBaseModel
{
    public short ShortId { get; set; }
    public short AnotherShortId { get; set; }

    [IsProcessedIntoTimeWindow]
    public decimal Value { get; set; }

    public override bool CalculatorOn
    {
        get
        {
            throw new NotImplementedException();
        }
    }
}

[TestMethod]
public void TestLowerResolution()
{
    /* generate test data */
    DateTime dateFrom = new DateTime(2018, 1, 28, 15, 0, 0, DateTimeKind.Utc);
    var dateTo = dateFrom.AddDays(1).AddSeconds(-1);

    var myValues = new List<MyModel>();

    myValues.Add(new MyModel()
    {
        Date = new DateTime(2018, 1, 9, 15, 48, 46, DateTimeKind.Utc),
        ShortId = 5,
        AnotherShortId = 0,
        TimeWindow = 0,
        Value = 30,
        fk_TenantId = 1006
    });

    myValues.Add(new MyModel()
    {
        Date = new DateTime(2018, 1, 29, 10, 11, 31, DateTimeKind.Utc),
        ShortId = 5,
        AnotherShortId = 0,
        TimeWindow = 0,
        Value = 14336,
        fk_TenantId = 1006
    });

    myValues.Add(new MyModel()
    {
        Date = new DateTime(2018, 1, 29, 10, 11, 59, DateTimeKind.Utc),
        ShortId = 5,
        AnotherShortId = 0,
        TimeWindow = 0,
        Value = 30,
        fk_TenantId = 1006
    });

    var windows = TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myValues).ToList();
}


Get this bounty!!!

#StackBounty: #reinventing-the-wheel #scala #generics #dsl Typeclass-oriented example project with implicit classes

Bounty: 50

The following code will only be an example of a project that due to (nested) higher kinds heavily relies on typeclasses for its DSL.

When reviewing the code keep in mind that this is an example, so I am not relying on libraries like cats even if they might already provide solutions for what I am doing.

With that aside I have some explicit questions about aspects of my code apart from an overall review:

  • What’s the correct package structuring e.g. /algebra, /syntax, /ops, /dsl, /implicits, … and where in that structure do simple case classes (like M or N) go, where typeclasses (like Invertable), where typeclass-instances (like mnInvertable), where implicit classes (like InvertableOps)?
  • Is my use of an implicit class good here, or is there a better way to define .invert on types like M[N[A]]?
  • Should the implicit parameter in the implicit class be moved to def invert instead?
  • What’s the naming convention for typeclasses (I used ...able), typeclass instances (I used type + typeclass) and implicit classes (I used typeclass + Ops)?
  • Bonus: Is it possible to define Invertable as context bounds instead of an implicit parameter? (I think not, but who knows!)
// src/main/scala/myproject/algebra/M.scala
case class M[A](value: A)

// src/main/scala/myproject/algebra/N.scala
case class N[A](value: A)

// src/main/scala/myproject/syntax/Invertable.scala
trait Invertable[F[_], G[_]] {
  def invert[A](fga: F[G[A]]): G[F[A]]
}

// src/main/scala/myproject/implicits/package.scala
implicit val mnInvertable: Invertable[M, N] = new Invertable[M, N] {
  def invert[A](fga: M[N[A]]): N[M[A]] = N(M(fga.value.value))
}

implicit class InvertableOps[F[_], G[_], A](fga: F[G[A]])(implicit i: Invertable[F, G]) {
  def invert = i.invert(fga)
}

// Somewhere in the project
M(N(1)).invert // It works!


Get this bounty!!!

#StackBounty: #generics #kotlin #mockito Mockito: ClassCastException on generic parent class

Bounty: 50

To abbreviate my unit tests, I created the following parent class:

internal abstract class TestUnitController<CONTROLLER: Any, SERVICE: Any> {

    @Mock
    protected lateinit var service: SERVICE

    @InjectMocks
    protected lateinit var controller: CONTROLLER

    protected abstract fun controllerCall(): CONTROLLER.() -> Unit
    protected abstract fun serviceCall(): SERVICE.() -> Any?

    @Test
    fun `when service returns error should throw ResponseStatusException`() {
        testControllerServiceError(service, serviceCall()) { controllerCall() }
    }

    protected fun <U> testController(value: U, assertions: () -> Unit) {
        testController(service, serviceCall(), value) { assertions() }
    }
}

And a unit test child like the following:

@RunWith(MockitoJUnitRunner::class)
internal class TestUnitCreateCompanyController : TestUnitController<CreateCompanyController, CompanyService>() {

    private val request = CompanyCreateRequest("LOL SARL")

    override fun controllerCall(): CreateCompanyController.() -> Unit = { createCompany(request) }

    override fun serviceCall(): CompanyService.() -> Any? = { createCompany(any()) }

    @Test
    fun `when create company service successful should return created company`() {
        val domain = CompanyDomain(name = request.name)
        testController(domain) {
            controller.createCompany(request).run {
                uuid.shouldEqual(domain.uuid.toString())
                name.shouldEqual(domain.name)
            }
        }
    }
}

However when I run this, I get the following exception:

java.lang.ClassCastException: org.mockito.codegen.Object$MockitoMock$1782227983 cannot be cast to org.m0skit0.fikchador.spring.domain.company.CompanyService

    at org.m0skit0.fikchador.spring.endpoint.company.create.TestUnitCreateCompanyController$serviceCall$1.invoke(TestUnitCreateCompanyController.kt:13)
    at org.m0skit0.fikchador.spring.test.TestUtilsKt.testController(TestUtils.kt:21)
    at org.m0skit0.fikchador.spring.test.TestUnitController.testController(TestUnitController.kt:24)
    at org.m0skit0.fikchador.spring.endpoint.company.create.TestUnitCreateCompanyController.when create company service successful should return created company(TestUnitCreateCompanyController.kt:24)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)


Get this bounty!!!

#StackBounty: #generics #design-patterns #data-structures #types #dart How to store a collection path for a model?

Bounty: 50

I’m building models for my app in Dart/Flutter. Here’s how a model looks like:

abstract class Model {
  /// A unique identifier of the model.
  /// Gets generated by Firestore.
  final String id;

  Model(this.id);
}

class MyModel extends Model {
  final String name;
  final String description;
  final int order;

  MyModel(String id, this.name, this.items, this.order) : super(id);
}

Those models would be stored in Google Firestore in mymodels collection:

mymodels/abc
mymodels/def
...

To fetch a list of these models from Firestore I need to store the collection path (mymodels) for MyModel type somewhere. So I could use it later when fetching models:

Future<List<T>> fetchList() {
  // How to know `path` by knowing T?
  _firestore.collection('path').getDocuments()
}

Where to store that collection path? I was thinking to declare a static property in Model interface, but Dart doesn’t seem to allow override static properties.

Would Dart annotations be a good fit for that?


Get this bounty!!!

#StackBounty: #c# #oop #generics #abstract-class Issue calling a generic common repository's method

Bounty: 100

I have a base repository setup. I want to create a generic common repository to use a common method which returns a boolean called:

DoesRecordExist()

I have the base repo and common repo setup, but i’m having issue referencing the ICommonRepository in the service. How do I call this method?

BaseRepository:

   public abstract class BaseRepository<TModel> : IBaseRepository<TModel> where TModel : BaseClass
    {
        private readonly IDbContext _context;
        private readonly IValidator<TModel> _validator;

        public BaseRepository(IDbContext context, IValidator<TModel> validator = null)
        {
            _context = context;
            _validator = validator ?? new InlineValidator<TModel>();
        }

        public bool DoesRecordExist(Guid id)
        {
            return _context.Set<TModel>().Any(x => x.Guid == id);
        }
    }

CommonRepository:

 public  class CommonRepository<TModel> : BaseRepository<TModel> where TModel : BaseClass, ICommonRepository<TModel>
{
    private readonly IDbContext _context;
    private readonly IValidator<TModel> _validator;
    public CommonRepository(IDbContext context, IValidator<TModel> validator = null) : base(context, validator)
    {
        _context = context;
        _validator = validator ?? new InlineValidator<TModel>();
    }
    public bool CommonDoesRecordExist(Guid id)
    {
        return DoesRecordExist(id);
    }
}

GlobalService:

private readonly ICategoryRepository _categoryRepository;
private readonly ISubcategoryRepository _subCategoryRepository;
private readonly ISubcategoryDescriptionRepository _subcategoryDescriptionRepository;
private readonly ICommonRepository<??????> _commonRepository;

public GlobalDataService(
    ICategoryRepository categoryRepository, 
    ISubcategoryRepository subCategoryRepository, 
    ISubcategoryDescriptionRepository subcategoryDescriptionRepository, 
    ICommonRepository<????> commonRepository)
{
    _categoryRepository = categoryRepository;
    _subCategoryRepository = subCategoryRepository;
    _subcategoryDescriptionRepository = subcategoryDescriptionRepository;
    _commonRepository = commonRepository;
}

 public bool DoesUserRecordExist(Guid userId)
    {
        //PROBLEM ON THIS LINE... bool existingData = _commonRepository.CommonDoesRecordExist(userId); 
            if (existingData)
            {
                //do stuff
            }
            else
            {
                //do other stuff
            }
        }

ICommonRepository.cs

   public interface ICommonRepository<T> : IBaseRepository
    {
        bool CommonDoesRecordExist(Guid id);
    }

IBaseRepository.cs

public interface IBaseRepository<T> : IBaseRepository
{
    bool DeleteAll();
    bool DoesRecordExist(Guid id, Expression<Func<T, bool>> filter);
    List<T> GetAll();
    T GetOne(Guid id);
    T Save(T item);
    bool Delete(Guid id);
    bool Delete(T item);
    IQueryable<T> Include(params Expression<Func<T, object>>[] includes);

}

public interface IBaseRepository
{
    string CollectionName { get; }
}


Get this bounty!!!

#StackBounty: #c# #oop #generics #abstract-class Issue calling a generic common repository's method

Bounty: 100

I have a base repository setup. I want to create a generic common repository to use a common method which returns a boolean called:

DoesRecordExist()

I have the base repo and common repo setup, but i’m having issue referencing the ICommonRepository in the service. How do I call this method?

BaseRepository:

   public abstract class BaseRepository<TModel> : IBaseRepository<TModel> where TModel : BaseClass
    {
        private readonly IDbContext _context;
        private readonly IValidator<TModel> _validator;

        public BaseRepository(IDbContext context, IValidator<TModel> validator = null)
        {
            _context = context;
            _validator = validator ?? new InlineValidator<TModel>();
        }

        public bool DoesRecordExist(Guid id)
        {
            return _context.Set<TModel>().Any(x => x.Guid == id);
        }
    }

CommonRepository:

 public  class CommonRepository<TModel> : BaseRepository<TModel> where TModel : BaseClass, ICommonRepository<TModel>
{
    private readonly IDbContext _context;
    private readonly IValidator<TModel> _validator;
    public CommonRepository(IDbContext context, IValidator<TModel> validator = null) : base(context, validator)
    {
        _context = context;
        _validator = validator ?? new InlineValidator<TModel>();
    }
    public bool CommonDoesRecordExist(Guid id)
    {
        return DoesRecordExist(id);
    }
}

GlobalService:

private readonly ICategoryRepository _categoryRepository;
private readonly ISubcategoryRepository _subCategoryRepository;
private readonly ISubcategoryDescriptionRepository _subcategoryDescriptionRepository;
private readonly ICommonRepository<??????> _commonRepository;

public GlobalDataService(
    ICategoryRepository categoryRepository, 
    ISubcategoryRepository subCategoryRepository, 
    ISubcategoryDescriptionRepository subcategoryDescriptionRepository, 
    ICommonRepository<????> commonRepository)
{
    _categoryRepository = categoryRepository;
    _subCategoryRepository = subCategoryRepository;
    _subcategoryDescriptionRepository = subcategoryDescriptionRepository;
    _commonRepository = commonRepository;
}

 public bool DoesUserRecordExist(Guid userId)
    {
        //PROBLEM ON THIS LINE... bool existingData = _commonRepository.CommonDoesRecordExist(userId); 
            if (existingData)
            {
                //do stuff
            }
            else
            {
                //do other stuff
            }
        }

ICommonRepository.cs

   public interface ICommonRepository<T> : IBaseRepository
    {
        bool CommonDoesRecordExist(Guid id);
    }

IBaseRepository.cs

public interface IBaseRepository<T> : IBaseRepository
{
    bool DeleteAll();
    bool DoesRecordExist(Guid id, Expression<Func<T, bool>> filter);
    List<T> GetAll();
    T GetOne(Guid id);
    T Save(T item);
    bool Delete(Guid id);
    bool Delete(T item);
    IQueryable<T> Include(params Expression<Func<T, object>>[] includes);

}

public interface IBaseRepository
{
    string CollectionName { get; }
}


Get this bounty!!!

#StackBounty: #swift #generics Swift 5 dynamic type for array

Bounty: 50

I have the following code in Swift:

class VolumeData <T> {
   private var volume: [T]

   init(with data:Data, width: UInt32, height: UInt32, depth: UInt32) {
      let size = width * height * depth
      volume = data.arrayFromData(size: Int(size))
   }
 }

class Volume: NSObject {

    private var rawVolume : Data?
    public var volume : VolumeData<Any>?
    public var header: Header?

 ....

    func loadVolume(_ name: String) {
        let filepath = Bundle.main.path(forResource: name, ofType: "vol")
        rawVolume = try? Data.init(contentsOf: URL(fileURLWithPath: filepath ?? ""))
        header = Header.init(from: ((rawVolume?.subdata(in: 0..<284))!))
        let volSize = header!.width * header!.height * header!.depth
        switch header!.type {
        case .FLOAT:
             volume = VolumeData<Float32>(with: (rawVolume?.subdata
             (in: 284..<volSize))!, width: header!.width, 
             height: header!.height, depth: header!.depth)
        default:
            volume = nil
        }
    }
}

And for the sake of completion:

extension Data {
    func arrayFromData<T> (size: Int) -> [T] {
       var arr:[T] = []
       for i in 0..<size {
           let offset = 4*i
           let d:T = self[offset..<offset+4].withUnsafeBytes { $0.pointee }
           arr.append(d)
        }
        return arr
    }
}

Right now I have a compile-time error:

Cannot assign value of type 'VolumeData<Float32>' (aka 'VolumeData<Float>') 
  to type 'VolumeData<Any>?'

Anyone can point me the correct way to implement this kind of dynamic generics in Swift?


Get this bounty!!!