Posts

Introducing RazorSharpener

Image
Introduction Sharpener: a person or device that makes something sharp  (Cambridge Dictionary). RazorSharpener  is a Razor compiler and renderer. It can load a .razor file and compile it into a .NET class that implements IComponent , the base interface for Razor components . This can be used, for example, to build a template engine, as Razor allows us to combine contents and code. Usage RazorSharpener  is composed of just two classes: RazorCompiler : used to compile a .razor source file ( Razor component ) into a .NET class RazorRenderer : renders a  Razor component  type into a string Razor Compiler To compile a .razor file is very simple: var compiler = new RazorCompiler(); var asm = compiler.Compile("RenderMessage.razor"); As you can see, the Compile method takes a file from the current folder and produces an assembly, which is how .NET "wraps" generated code. If there is any compilation error, an exception is thrown. The generated assembly will...

Value Generators in EF Core

Introduction EF Core has the concept of value generators. Very simply, they provide values for properties, either the primary key or another one. Wasn't too long ago that this feature - configurable value generators - was missing from EF Core, but now we have it, and it works well. We still don't have all of the id generators offered by NHibernate , but, we have something, and, what's best, we can build our own! Strategies versus Value Generators Before value generators were around, we could specify a generation or update strategy for properties, like the id. Strategies were a hint for the database provider, they didn't exactly specify how the value would be generated. The strategies are: None : the value is never generated Identity : the value is generated only when the record is first inserted Computed : the value is generated when the row is either inserted or modified Usually,  Identity  meant that something like auto-increment or SQL Server IDENTITY will be used, ...

ASP.NET Core Pitfalls - Action Constraint Order

Introduction When we have more than one action method in MVP or Web API that can match a given request, the request may fail or land on an unwanted method. By default, a number of items is used to figure out which method to call: The HTTP verb The action method name The route template The action method parameters The request content type An  action constaint  may be needed to select the right one; an action constraint is an implementation of IActionConstraint , and is normally added through an attribute or a convention. Some examples of built-in action constrains include: [Consumes] attribute: for selecting the method based on the Content-Type request header HttpMethodActionConstraint : legacy, don't bother OverloadActionConstraint : the method selected must match all required parameters If you want to build your own, you should inherit from  ActionMethodSelectorAttribute  and implement  IsValidForRequest . Problem Sometimes, however, just applying an acti...

A Simple State Machine in .NET - Adding Code-based Implementation

Introduction On a previous post , I introduced my SimpleStateMachine project. Essentially, it provided an easy way to define a state machine from enumeration values. The version presented used attributes on these enumeration values to build up the state machine. Because this can sometimes be intrusive, and we may not want to "pollute" our enumerations, I decided to implement another way to define a state machine from an enumeration. State Machines from Code So, I came up with this interface: public interface IStateMachine<T> where T : Enum { T GetInitialState(); IStateMachine<T> CanTransitionTo(T state, params IReadOnlyCollection<T> otherStates); IEnumerable<T> GetTransitions(T state); bool IsFinalState(T state); bool IsInitialState(T state); } It provides basically the same operations that were previously available: Get the initial state of an enumeration ( GetInitialState ) Check if an enumeration value is the initial ( IsInitial...

PhD

As some of you may know, I was recently accepted to the PhD programme in Informatics Engineering of the Informatics Engineering Department of the University of Coimbra ! I was very happy about it, as there weren't that many vacancies and I don't have an academic/scientific background - essentially, I'm a software developer -, and it was something I long wanted to do. I still don't have a subject or advisor(s), this is something that I need to address in the next few months, before classes start, in September. So, I guess this is to say that I may be writing some posts about it, as I go along; all will have the #phd tag. And that's it! ;-)

Using GUIDs with EF Core

Introduction GUIDs , also known as UUIDs , are a very useful data type that is present in all major databases. It allows having values that are magically generated and never repeat, making them ideal for usage across data sources, where a single source of data cannot be reused. in .NET, they are represented by the Guid type; in SQL Server, it is UNIQUEIDENTIFIER , in PostgreSQL it is UUID , in Oracle it is RAW(16) , and in MySQL it is BINARY(16) . EF Core supports all of them. There are pros and cons regarding using GUIDs as database primary keys: They are obviously great for uniqueness They can be generated on the client But, on the other side: They take a lot of space (16 bytes), compared to 4 bytes for integers or 8 for longs They can lead to very fragmented indexes Let's see what we can do about that. Primary Key Generation in EF Core There are 3 ways to have EF Core generate GUIDs for the primary keys: Have the primary key property marked as database generated of type identit...

Retrieving Services from Dependency Injection in .NET

Introduction Dependency Injection  (DI) is a critical part of .NET since the .NET Core days. A simple, although powerful, DI container is included out of the box, and ASP.NET Core makes heavy use of it . I already wrote about DI in .NET a few times: .NET 8 Dependency Injection Changes: Keyed Services ASP.NET Core Inversion of Control and Dependency Injection The Evolution of .NET Dependency Resolution Dependency Injection Lifetime Validation .NET Core Service Provider Gotchas and Less-Known Features An Extended Service Provider for .NET This time I want to highlight something that people may not be aware of, even though I already mentioned it in one of my posts. Retrieving Services As you know, the DI is represented by an instance of IServiceProvider . When we want to retrieve a service we call  GetService , passing it a Type , for a dynamic call, or  GetService<T> , for a strongly-typed version, which just calls the other one with a cast. Now, if the service repre...

Entity Framework Core Pitfalls: Asynchronous vs Synchronous Calls and Interceptors

Introduction Another on my EF Core pitfalls series. This time, interceptors and synchronous/asynchronous calls. Problem You surely know about EF Core interceptors , a very useful feature that I talked about many times. What's the problem with them? Well, all of the interceptor interfaces  define both synchronous as well as asynchronous versions of their methods. This is so that, for example, when we call DbContext.SaveChanges the synchronous version is called, and when it's DbContext.SaveChangesAsync , the asynchronous one instead. I think you get the idea. So, imagine we added an interceptor, inheriting from SaveChangesInterceptor ,   to our collection of interceptors . If we then commit the changes in the  DbContext  through a call to  DbContext.SaveChanges , only SavingChanges , SavedChanges , SavedChangesFailed ,  SaveChangedCanceled  and, or, ThrowingConcurrencyException methods will be called, and you may be very surprised because your well-cra...

Microsoft MVP Global Summit

Image
Today begins the Microsoft MVP Global Summit ! This is one of the highlights of being an MVP : a yearly gathering at the Microsoft Campus in Redmond, WA, to which all MVPs are invited. It's a chance to learn about the Microsoft products, where they are going, ask questions and provide feedback, discuss technical and business issues with the Microsoft personnel and other MVPs, and, it is all in all, a great experience! All under NDA, of course! ;-) This year, sadly, I won't be able to attend, but I wish all my MVP fellows a terrific Summit! #MVPBuzz #MVPAward #MVPSummit

A Simple State Machine in .NET

Image
Introduction Update: new additions here . This is another post that should be tagged lazy-weekend! Let's imagine a simple state machine for tracking the state of tickets. It consists of the following states: Created : the ticket has been created Ready : the ticket is ready to be picked up for implementation In Progress : the ticket is being implemented Blocked : the ticket is currently blocked In Review : the ticket was sent for review Closed : the ticket has been closed The following diagram illustrates these states and the possible transitions: A simple state machine Don't worry too much about the actual states, this is meant to be an example. An explanation for these transitions is in order: The first state for a ticket is Created From Created , the ticket can transition to Closed , or to Ready From Ready , the ticket can transition to In Progress , Blocked , or Closed   From In Progress , the ticket can transition to Blocked , In Review , Ready , or Closed From In Review , ...