joren
joren
CC#
Created by joren on 12/14/2023 in #help
Using base class as relationship definition in model ASP.net WEB API
So I've written this model that I used to save my credentials to authenticate my users with:
public class UserCredentialsModel : IdentityUser, IModelEntity
{
[Required]
string Id { get; set; }

[Required]
public DateTime CreatedAt { get; set; }

public ICollection<RefreshTokenModel> RefreshTokens { get; } = new List<RefreshTokenModel>();

// Does this work?
public BaseProfile profile { get; set; }
}
public class UserCredentialsModel : IdentityUser, IModelEntity
{
[Required]
string Id { get; set; }

[Required]
public DateTime CreatedAt { get; set; }

public ICollection<RefreshTokenModel> RefreshTokens { get; } = new List<RefreshTokenModel>();

// Does this work?
public BaseProfile profile { get; set; }
}
Now as you can see I have a BaseProfile here, each credential has its connected profile attached. It is a one to one relationship. However, I have multiple types of profiles, that have a few things in common so I wrote a base class like this:
public class BaseProfile : IModelEntity
{
public string Id { get; set; }


[Required]
public string FirstName { get; set; }

[Required]
public string LastName { get; set; }

public UserCredentialsModel UserCredentials { get; set; }
}
public class BaseProfile : IModelEntity
{
public string Id { get; set; }


[Required]
public string FirstName { get; set; }

[Required]
public string LastName { get; set; }

public UserCredentialsModel UserCredentials { get; set; }
}
and then I have different profiles that inherit from this, would this relationship still work as intended when using Baseprofile? Or do I need to have a field for each profile and have them as nullable/have some enum to decide the profile type and use that as a way to differentiate
3 replies
CC#
Created by joren on 12/9/2023 in #help
How are DTO utilized
So I've been writing some end points for my learning project, and I stumbled on DTO. The concept I understand, limit view you return for privacy reasons, security reasons, having a smaller payload, etc. How does it work in practice though, I saw that auto mapper is a thing used, which is awesome, that I can use and understand easily. However, what's best practice, when you have a DTO for a model, does the endpoint always return the DTO? Or do you have two endpoints, one that return the actual model, and one the DTO?
177 replies
CC#
Created by joren on 12/8/2023 in #help
Data seeding database
So currently in my program.cs I have the following code:
// Seed the database, disable once done.
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
DataContext context = services.GetRequiredService<DataContext>();

if(context.Database.EnsureCreated())
{
var dataSeeder = new DataSeeder(context);
dataSeeder.SeedData();
}
}
catch (Exception ex)
{
Console.WriteLine($"Error occurred while seeding the database: {ex.Message}");
}
}
// Seed the database, disable once done.
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
DataContext context = services.GetRequiredService<DataContext>();

if(context.Database.EnsureCreated())
{
var dataSeeder = new DataSeeder(context);
dataSeeder.SeedData();
}
}
catch (Exception ex)
{
Console.WriteLine($"Error occurred while seeding the database: {ex.Message}");
}
}
Now, seeding only makes sense in a development environment and only has to be executed once. So would this be a proper way to go about it? My DataSeeder class basically creates objects of all my models, gives them mock values, and that I save to the database.
74 replies
CC#
Created by joren on 10/26/2023 in #help
❔ ✅ Verifying the purpose of Moq usage
mockDatabase.Setup(db => db.GetUserName(It.IsAny<int>()))
.Returns((int userId) => "User" + userId);
mockDatabase.Setup(db => db.GetUserName(It.IsAny<int>()))
.Returns((int userId) => "User" + userId);
So, as you can see I use It.IsAny<int>() to mimic a value that would be passed, since GetUserName() requres an integer passed as argument. However this value is not used in the actual mock, but rather the
string result = userManager.GetUserDisplayName(42);
string result = userManager.GetUserDisplayName(42);
the 42 that is passed here, which then calls GetUserName() inside of it.
67 replies
CC#
Created by joren on 10/26/2023 in #help
✅ Covariance & Contravariance
public interface IRepository<T>
{
T Get();
void Add(T item);
}

public class Animal
{
public string Name { get; set; }
}

public class Dog : Animal
{
public string Breed { get; set; }
}

public class AnimalRepository : IRepository<Animal>
{
public Animal Get()
{
Console.WriteLine("Getting an animal from the repository.");
return new Animal { Name = "Fido" };
}

public void Add(Animal item)
{
Console.WriteLine("Adding an animal to the repository.");
}
}
public class DogRepository : IRepository<Dog>
{
public Dog Get()
{
Console.WriteLine("Getting a dog from the repository.");
return new Dog { Name = "Buddy", Breed = "Golden Retriever" };
}

public void Add(Dog item)
{
Console.WriteLine("Adding a dog to the repository.");
}
}

internal class Program
{
public static void UseAnimalRepository(IRepository<Animal> repository)
{
var animal = repository.Get();
Console.WriteLine("Used repository to get an animal: " + animal.Name);
repository.Add(new Animal { Name = "Spot" });
Console.WriteLine("Used repository to add an animal.");
}

public static void Main()
{
AnimalRepository animalRepository = new AnimalRepository();
DogRepository dogRepository = new DogRepository();

Console.WriteLine("Using Animal Repository:");
UseAnimalRepository(animalRepository);

Console.WriteLine("\nUsing Dog Repository:");
UseAnimalRepository(dogRepository); // This line won't work without contravariance
}
}
public interface IRepository<T>
{
T Get();
void Add(T item);
}

public class Animal
{
public string Name { get; set; }
}

public class Dog : Animal
{
public string Breed { get; set; }
}

public class AnimalRepository : IRepository<Animal>
{
public Animal Get()
{
Console.WriteLine("Getting an animal from the repository.");
return new Animal { Name = "Fido" };
}

public void Add(Animal item)
{
Console.WriteLine("Adding an animal to the repository.");
}
}
public class DogRepository : IRepository<Dog>
{
public Dog Get()
{
Console.WriteLine("Getting a dog from the repository.");
return new Dog { Name = "Buddy", Breed = "Golden Retriever" };
}

public void Add(Dog item)
{
Console.WriteLine("Adding a dog to the repository.");
}
}

internal class Program
{
public static void UseAnimalRepository(IRepository<Animal> repository)
{
var animal = repository.Get();
Console.WriteLine("Used repository to get an animal: " + animal.Name);
repository.Add(new Animal { Name = "Spot" });
Console.WriteLine("Used repository to add an animal.");
}

public static void Main()
{
AnimalRepository animalRepository = new AnimalRepository();
DogRepository dogRepository = new DogRepository();

Console.WriteLine("Using Animal Repository:");
UseAnimalRepository(animalRepository);

Console.WriteLine("\nUsing Dog Repository:");
UseAnimalRepository(dogRepository); // This line won't work without contravariance
}
}
So i wrote up this example and I stumbled upon the contravariance lacking here.
211 replies
CC#
Created by joren on 10/25/2023 in #help
❔ ✅ using Xunit; does not work in visual studio
As far as I was aware its shipped with .Net when u install C# development, but when I try to import it it does not work.
17 replies
CC#
Created by joren on 10/25/2023 in #help
❔ Clarification on Async and Task.Run
So I've been trying out the Async and Task.Run, now I need some clarification about the two and their differences. Now Async is basically one worker, that shifts its attention from Task to Task while another task is being processed (without needing workers attention). Now I read that C# achieve this by using the Task.Scheduler, which has a thread pool and what not. Now Task.Run would be parallelism in C#, it creates a thread with the function you pass to it. Now, granted the above information is correct, Async using a thread pool wouldnt that be considered utilizing parallelism?
214 replies
CC#
Created by joren on 10/21/2023 in #help
✅ Anonymous type
No description
23 replies
CC#
Created by joren on 10/20/2023 in #help
❔ => operator
So I read while looking into LINQ documentation that => is the syntax for a lambda expression. Now in the context of LINQ it makes sense, I would've guessed already. However in a class:
class A
{
int foo() => 34;
}
class A
{
int foo() => 34;
}
I would assume it is not seen as a lambda, it should just be a class method as its just syntax sugar for:
int foo() { return 34; }
int foo() { return 34; }
26 replies
CC#
Created by joren on 10/19/2023 in #help
✅ Deferred Execution or Forcing Immediate Execution
So I was reading the documentation on LINQ and I came across the two concepts i wrote in the title, now lets look at:
int[] nums = { 1, 2, 3, 4, 5};

var numQuery = from num in nums where (num % 2) != 0 select num;

foreach (int num in numQuery) {
Console.Write(num);
}
int[] nums = { 1, 2, 3, 4, 5};

var numQuery = from num in nums where (num % 2) != 0 select num;

foreach (int num in numQuery) {
Console.Write(num);
}
Now its pretty clear its deferred execution, we declare the query but its actually executed when the foreach is called. What I dont understand is why
var evenNumQuery =
from num in numbers
where (num % 2) == 0
select num;

int evenNumCount = evenNumQuery.Count();
var evenNumQuery =
from num in numbers
where (num % 2) == 0
select num;

int evenNumCount = evenNumQuery.Count();
Is considered Immediate execution, it still declares it and then triggers the query, in this case a foreach internally but conceptually this is pretty much the same. This though:
List<int> numQuery2 =
(from num in numbers
where (num % 2) == 0
select num).ToList();

// or like this:
// numQuery3 is still an int[]

var numQuery3 =
(from num in numbers
where (num % 2) == 0
select num).ToArray();
List<int> numQuery2 =
(from num in numbers
where (num % 2) == 0
select num).ToList();

// or like this:
// numQuery3 is still an int[]

var numQuery3 =
(from num in numbers
where (num % 2) == 0
select num).ToArray();
Calling .ToList or To.Array makes sense, you'd be executing the query in place and returning the result of the execution rather than saving the query to be executed later. Am I misinterpreting the documentation?
346 replies
CC#
Created by joren on 10/3/2023 in #help
❔ Covariance and Contravariance C#
So I stumbled on this topic and I dont seem to grasp it properly, though I saw the following example somewhere:
class Base
{
void func() { ... }
}
class Derived : Base
{
void fuc() { ... }
}

Base a = new Base(); // obv fine
Base b = new Derived(); // obv fine
class Base
{
void func() { ... }
}
class Derived : Base
{
void fuc() { ... }
}

Base a = new Base(); // obv fine
Base b = new Derived(); // obv fine
Both now can call func(), but b cannot call fuc() too as its treated as a Base (reference) type. Now in C++, you'd just cast b to Derived and it'd work and be perfectly valid code. The sources I looked at, mentioned that this is why covariance/contravariance exists?
136 replies
CC#
Created by joren on 9/16/2023 in #help
❔ Defining base impl ctor in interface
So currently for some testing I have the following code:
interface HumanInterface
{
public string Name { get; }
public string Description { get; }

public void walk() { Console.WriteLine("Default implementation"); }

// Forcing implementing class to define scream()
public void scream();
}

class Foo : HumanInterface
{
Foo(string name, string description)
{
Name = name;
Description = description;
}

public string Name { get; }
public string Description { get; }
void HumanInterface.scream() { Console.WriteLine("Screams"); }
}
interface HumanInterface
{
public string Name { get; }
public string Description { get; }

public void walk() { Console.WriteLine("Default implementation"); }

// Forcing implementing class to define scream()
public void scream();
}

class Foo : HumanInterface
{
Foo(string name, string description)
{
Name = name;
Description = description;
}

public string Name { get; }
public string Description { get; }
void HumanInterface.scream() { Console.WriteLine("Screams"); }
}
my ctor Foo is pretty generic, in fact I'd probably want all my derived classes to have that exact ctor. How'd I achieve this?
197 replies
CC#
Created by joren on 9/16/2023 in #help
❔ Confusion as to what to default to when it comes to accessibility modifiers
So I come from a extensive C++ background, in which we use the keywords: public and private a bit different. They say everything about accessibility but nothing about assemblies and whether we are allowing external assemblies to access our classes, methods and even members. Now to my understanding internal is basically public but within the assembly im working in, meaning that is how I say: this func() method is public and can now be called on its respective object outside of the class. And public is used to say: hey, this is allowed to be called form another assembly and is public within its own assembly too. Now, knowing this, I concluded that best practice, granted we work within one assembly, the internal keyword is the default one should use however I'd love to get some assurance on it. Since even my IDE defaults to public when auto-generation ctors, methods, etc.
// ./Entities/HumanEntity.cs
internal class HumanEntity : BaseEntity
{
internal HumanEntity() { }
internal HumanEntity(string name) { Name = name; }

internal void func() { }
}

// ./Program.cs
HumanEntity humanEntity = new HumanEntity("asdf");
Console.WriteLine(humanEntity.Name);
humanEntity.func();
// ./Entities/HumanEntity.cs
internal class HumanEntity : BaseEntity
{
internal HumanEntity() { }
internal HumanEntity(string name) { Name = name; }

internal void func() { }
}

// ./Program.cs
HumanEntity humanEntity = new HumanEntity("asdf");
Console.WriteLine(humanEntity.Name);
humanEntity.func();
261 replies