Skip to main content

6 posts tagged with "c#"

View All Tags

· 2 min read

Welcome to our latest project - a Proof of Concept (PoC) repository that explores dynamic distance calculation using delegates. In this blog post, we'll take you through the features, the motivation behind the project, and how you can experiment with dynamic resolution of distance calculation services in a web API.

Why Delegates?

Delegates in C# are powerful constructs that allow us to treat methods as first-class citizens. Leveraging this capability, our PoC demonstrates how to dynamically resolve distance calculation services at runtime. This flexibility opens the door to easily switch between different providers based on specific conditions or user preferences.

Key Features

Dynamic Resolution with Delegates

The heart of this project lies in the DistanceCalculator class, which uses a delegate (DistanceProviderResolver) to dynamically resolve the distance calculation service. This allows us to switch between Google and PCMiler providers with ease, providing a seamless and extensible solution.

var distanceCalculator = new DistanceCalculator();
var distanceService = distanceCalculator.ResolveDistanceProvider(DistanceProvider.Google);
double distance = distanceService.CalculateDistance("Origin", "Destination");

Configurability

Experiment with different distance calculation providers by customizing the Program.cs file. This configurability makes it easy to adapt the PoC to various scenarios and requirements.

Limitations and Roadmap

As a Proof of Concept, it's important to note that this project currently uses simulated distance calculation logic with dummy values. While it showcases the concept effectively, it may lack certain features expected in a production-ready application.

We encourage you to explore, experiment, and contribute. If you encounter issues or have ideas for improvements, please open an issue on our GitHub repository.

Demo

Clone the Repository :

git clone https://github.com/nhonvo/delegate-poc.git
cd delegate-poc

Conclusion

Dynamic distance calculation with delegates offers a glimpse into the world of flexible and configurable service resolution. We hope this PoC sparks ideas and discussions about how such a concept could be integrated into real-world applications.

Feel free to dive into the code, contribute your insights, and join us on this exploration of dynamic resolution in C#.

Happy coding!

· 3 min read

Introduction

  • Entity Framework Core is an ORM framework, open-source, lightweight and cross-platform developed by Microsoft.
  • It enables developers to work with databases using .NET object and EF Core is built on top of ADO.NET

Relationship

One-to-One Relationship

modelBuilder.Entity<Author>()
.HasOne(a => a.Book) // Author has one Book
.WithOne(b => b.Author) // Book has one Author
.HasForeignKey<Book>(b => b.AuthorId); // Foreign key in Book referencing AuthorId

One-to-Many Relationship

modelBuilder.Entity<Author>()
.HasMany(a => a.Books) // Author has many Books
.WithOne(b => b.Author) // Book has one Author
.HasForeignKey(b => b.AuthorId); // Foreign key in Book referencing AuthorId

Many-to-Many Relationship

modelBuilder.Entity<StudentCourse>()
.HasKey(sc => new { sc.StudentId, sc.CourseId }); // Define composite primary key for the join table

modelBuilder.Entity<StudentCourse>()
.HasOne(sc => sc.Student)
.WithMany(s => s.Courses)
.HasForeignKey(sc => sc.StudentId); // Foreign key in join table referencing StudentId

modelBuilder.Entity<StudentCourse>()
.HasOne(sc => sc.Course)
.WithMany(c => c.Students)
.HasForeignKey(sc => sc.CourseId); // Foreign key in join table referencing CourseId

DeleteBehavior

The DeleteBehavior enum in EF Core includes the following options:

  1. Cascade: Deleting the principal/parent entity will cause the dependent/child entities to be deleted as well. OnDelete(DeleteBehavior.Cascade)

  2. SetNull: Deleting the principal/parent entity will set the foreign key properties in the dependent/child entities to null. OnDelete(DeleteBehavior.SetNull)

  3. SetDefault: Deleting the principal/parent entity will set the foreign key properties in the dependent/child entities to their default values. OnDelete(DeleteBehavior.SetDefault)

  4. Restrict: Prevents the deletion of the principal/parent entity if there are dependent/child entities. OnDelete(DeleteBehavior.Restrict) . An exception will be thrown.

  5. NoAction: Similar to Restrict, it is used to specify no action on delete. OnDelete(DeleteBehavior.NoAction) and you'll need to handle constraints in your application logic.

For example:

modelBuilder.Entity<ParentEntity>()
.HasMany(p => p.ChildEntities)
.WithOne(c => c.ParentEntity)
.OnDelete(DeleteBehavior.Restrict);

This configuration would set the delete behavior for the relationship between ParentEntity and ChildEntity to Restrict.

Best pratices

  1. Indexing: Creating indexes on frequently accessed columns can improve query performance.

  2. Proper data modeling: Designing tables and relationships properly can improve query performance and prevent performance issues.

  3. Caching: Storing frequently accessed data in a cache can reduce database calls and improve application performance.

  4. Query optimization: Writing efficient queries can improve performance. Techniques such as avoiding unnecessary joins and reducing the number of returned columns can help.

  5. Connection pooling: Reusing database connections instead of creating new ones can improve performance.

  6. Batch processing: Performing multiple operations in a single database call can improve performance and reduce overhead.

  7. Asynchronous programming: Using asynchronous programming techniques can improve performance by allowing the application to continue executing while waiting for database calls to complete.

· 2 min read
  1. c# basic(datatype, exception, ...) -> important
  2. Algorithm (bubble sort, selected sort, ...) -> quick view
  3. OOP (4 ) -> important
  4. SOLID (5) -> quick view
  5. C# advance (delegate, generic, async ) -> optional
  6. SQL(join(8), understand func vs store procedure) -> important
  7. Linq -> quick view
  8. ef core -> quick view
  9. webapi -> optional

Create and Build Projects

dotnet new console -n MyConsoleApp    // Create a new console application
dotnet new webapi -n MyWebApi // Create a new Web API project
dotnet build // Build the project

Run Applications

dotnet run                            // Run the application
dotnet run --project <project_path> // Run a specific project
dotnet watch run // Run with file watching

Add Dependencies

dotnet add package <package_name>     // Add a NuGet package
dotnet restore // Restore dependencies

Generate Code

dotnet new classlib -n MyLibrary      // Create a class library
dotnet add reference <project_path> // Add a project reference
dotnet publish -c Release // Publish the application

Unit Testing

dotnet new xunit -n MyTests           // Create xUnit test project
dotnet test // Run tests

Entity Framework Core

dotnet ef migrations add <migration_name>    // Add a migration
dotnet ef database update // Apply migrations

Publish and Deploy

dotnet publish -c Release --self-contained // Publish a self-contained application

Package Management

dotnet nuget push -k <api_key> -s <source> <package.nupkg>    // Publish a NuGet package

ASP.NET Core Identity

dotnet new identity -n MyIdentityApp   // Create an ASP.NET Core Identity project

Azure Functions

dotnet new func -n MyFunction          // Create an Azure Functions project

Clean Up

dotnet clean                          // Clean the build output