Posts

Showing posts with the label C#

Data Annotations

Data Annotations  Required  for anything that is not null: [Required] DataType for anything: [DataType(DataType.Password)] The data types are:                 Custom = 0, // Summary: Represents a custom data type.         DateTime = 1, // Summary: Represents an instant in time, expressed as a date and time of day.         Date = 2,         Time = 3,                 Duration = 4, // Summary: Represents a continuous time during which an object exists.         PhoneNumber = 5,         Currency = 6,         Text = 7,         Html = 8,         MultilineText = 9,         EmailAddress = 10,         Password = 11,         Url = 12,         ImageUrl = 13, ...

Pagination in APIs with Razor

 Pagination in APIs Make a PaginationRequest.cs and put this in it: namespace eShop.Catalog.API.Model; public record PaginationRequest(int PageSize = 10, int PageIndex = 0); ------------------------------------ namespace eShop.Catalog.API.Model; public class PaginatedItems<TEntity>(int pageIndex, int pageSize, long count, IEnumerable<TEntity> data) where TEntity : class {     public int PageIndex { get; } = pageIndex;     public int PageSize { get; } = pageSize;     public long Count { get; } = count;     public IEnumerable<TEntity> Data { get;} = data; } ------------------------------------    Pagination only really applies to the GetAll(), GetItemsByName(), or GetAllByType() methods. Not needed on create, delete, update, or GetById().     So in your:   api.MapGet("/items", GetAllItems);    you need to implement GetAllItems() as such: public static async Task<Results<Ok<...

Deep Copy of List of T

   Deep Copy of List<T>   I wish Microsoft had a clean method of DeepCopy(). Q: How get a deep copy of T? A1:  List<Book> books_2 = books_1.Select(book => new Book(book.title)).ToList(); A2: List<Book> books_2 = books_1.ConvertAll(book => new Book(book.title));   Credit: https://stackoverflow.com/questions/14007405/how-create-a-new-deep-copy-clone-of-a-listt  

Task.WhenAll

  var parallelSupplierTask = dbParallel1.Supplier.Where(x => x.Name.Contains("7")).OrderByDescending(x => x.Name).ToListAsync(); var parallelCustomerTask = dbParallel2.Customer.Where(x => x.Name.Contains("7")).OrderByDescending(x => x.Name).ToListAsync(); await Task . WhenAll ( parallelSupplierTask , parallelCustomerTask ) ; https://juldhais.net/super-fast-query-in-entity-framework-6d20cd5358e2 https://stackoverflow.com/questions/41749896/ef-6-how-to-correctly-perform-parallel-queries Also use  AsNoTracking when using EF Excellent Q & A.  See all the answers. https://stackoverflow.com/questions/34375696/executing-tasks-in-parallel The 109 answer is a really nice example: https://stackoverflow.com/questions/12343081/run-two-async-tasks-in-parallel-and-collect-results-in-net-4-5

C# Shallow Clone of List of T

  C# Shallow Clone For a shallow clone of a List<T> and not just a pointer to the originalList, do this: var shallowClone = new List(originalList);

Sleeping in .NET

  Sleep Newer way with asynchronous programming: await Task.Delay( TimeSpan.FromSeconds(2) , cancellationToken); // sleep 2 seconds Another way: var timer = new Timer(callback, etc.);  timer.Elapsed += OnTimerElapsed; timer.AutoReset = true; timer.Enabled = true; Old way: System.Threading.Thread.Sleep(1000); or Thread.Sleep(TimeSpan.FromSeconds(2));.

Cancellation Tokens - C# Async programming

Cancellation Tokens    I see cancellation tokens all the time in .NET 8 for handling long running asynchronous operations, but they have been around since asynchronous programming started.  Parts It has two pieces: CancellationTokenSource - creates a cancellation token and sends a cancellation request to all copies of that token. CancellationToken - listeners monitor the token’s current state. Listening Ways to Listen:  1) polling, 2)  register a callback, 3) listen to multiple tokens simultaneously. Polling example: while (!cancellationToken.IsCancellationRequested) { ... } Cancellation source purpose  A cancellation token gives you the right to know someone is trying to cancel something. It does not give you the right to actually signal a cancellation. Only the cancellation token source gives you that. This is by design. // Define the cancellation token. CancellationTokenSource source = new CancellationTokenSource (); CancellationToken token = sou...