Skip to main content

Posts

Showing posts from February, 2024

EF Core–.NET 8 update

The .NET 8 release of Entity Framework Core offers a large list of new features. The goal of this post is not to walk you through all these features, therefore you can have a look at the What's new page on Microsoft Learn , instead I want to talk about a specific feature as a follow-up on the previous posts about EF Core I did this week. In those posts I talked about the FromSql method to use your handwritten SQL statements to fetch EF Core entities. What I didn’t mention is that this only worked for entities that were registered as an entity to the DbContext. Starting with the EF Core 8 release, this condition has been removed, allowing us to create any SQL statements you want and map them to C# objects. This means that EF Core can now become an alternative to micro-ORM’s like Dapper . Of course there is maybe still a performance difference(I’ll do a benchmark and share the results) but feature wise this is a great addition. To use this feature, we need to call the SqlQue

EF Core - System.InvalidOperationException : The required column 'Id' was not present in the results of a 'FromSql' operation.

Yesterday I talked about an error I got when using the FromSql method in Entity Framework Core(EF Core). It allows you to execute raw SQL queries against a relational database. Here is the example I was using yesterday: Remark: The FromSql method was introduced in EF Core 7.0. In older versions, you should use FromSqlInterpolated instead. However when we tried to execute the code above it failed with the following error message: System.InvalidOperationException : The required column 'Id' was not present in the results of a 'FromSql' operation. You typically get the  error message above when there isn’t a matching column found in the SQL result for every property in your entity type. In our case the query was using a ‘SELECT *’ so I couldn’t be that we missed a column. To explain what was causing the issue, I first have to show our entity type and mapping class: As you can see there is a difference between the name of one of our columns(ProductID) and t

EF Core - Cannot convert from 'string' to 'System.FormattableString'

While doing a pair programming session with a new developer in one of my teams, we ended up with a compiler error after writing the following code: This is the error message we got: Argument 2: cannot convert from 'string' to 'System.FormattableString'   The fix was easy just add a ‘$’ before the query: However it would not have been a good pair programming session if we didn’t drill down further into this. What is a FormattableString? A FormattableString in C# is a type introduced in .NET 4.6. It represents a composite format string, which consists of fixed text intermixed with indexed placeholders (format items). These placeholders correspond to the objects in a list. The key features of FormattableString are: Capturing Information Before Formatting : A FormattableString captures both the format string (similar to what you’d pass to string.Format , e.g., "Hello, {0}" ) and the arguments that would be used to format it.

Dapper - Return dynamic data

For simple data fetching scenario's, I tend to keep away from Entity Framework and go the micro-ORM approach using libraries like Dapper . Today I had a small use case where I wanted to return some data using dynamic types in C# and handle it like a list of key-value pairs instead of using strongly typed objects.  The good news is that this is supported out-of-the-box in Dapper. Dapper gives you multiple overloads that returns a dynamic type. Here is an example using Query() : Simple but effective! Remark: If you are not really looking for a dynamic result set but don’t want to create a class or record type, you can also use value tuples to map the returned rows: More information Dapper Anonymous Result - Learn How to Map Result to Dynamic Object (dappertutorial.net)

Implementing the decorator pattern using System. Reflection.DispatchProxy

If you are new to the decorator pattern, let me start with a short explanation: Decorator is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors. A common use case for decorators is to implement Aspect Oriented Programming (AOP) which allows you to implement cross-cutting concerns like logging, caching, … There are multiple ways to implement this pattern, you can manually implement it, use your DI container , use a source generator to write the boilerplate code or use a dynamic proxy that wraps call to the original class. It’s this last approach I want to focus on in this blog post. You could use the great  Castle.DynamicProxy library but for simpler use cases, there is a built-in alternative through the System.Reflection.DispatchProxy class. Let’s have a look at a small code example on how to use this class. First we need to create a Decorator class that impl

AddConsole is obsolete: This method is retained only for compatibility

While working on a POC I got the following warning/error when trying to add some logging: Here is the exact error message: CS0619: ‘ConsoleLoggerExtensions.AddConsole(ILoggerFactory)’ is obsolete: ‘This method is retained only for compatibility. The recommended alternative is AddConsole(this ILoggingBuilder builder). There are multiple ways to get rid of this warning, but I solved it by using the following code: Happy coding!

Visual Studio Presentation Mode

I think we all have seen presentations where Visual Studio was used during the demos but were we had a hard time because the fonts were too small in the editor, Solution Explorer and menu items, I have to admit that I have been guilty making this same mistake. I recently discovered that Visual Studio has a Presentation Mode. Presentation Mode is a feature that lets you open an instance of Visual Studio that looks like a fresh install, without any customizations, extensions, or settings synchronization. This way, you can avoid any distractions or confusion that may arise from your personal preferences or environment. You can then optimize any settings that are relevant for your presentation, such as font sizes, themes, window layouts, and keyboard shortcuts. These settings will be preserved for the next time you use Presentation Mode. To enter presentation mode, open a Developer Command Prompt and execute the following command: devenv /RootSuffix DemoMode Remark: You can swap t

Visual Studio–Share your settings

In VSCode you can share your settings through profiles . This allows you to easily apply your UI layout, settings and extensions to multiple VSCode instances. A similar thing is possible in Visual Studio. Settings can be exported through the Import and Export Settings Wizard: Go to Tools –> Import and Export Settings Choose Export selected environment settings and click on Next > Now you can choose which settings should be exported. Check or uncheck the settings you want to export and click on Next > Specify where you want to store your .vssettingsfile file and click on Finish You can now close the wizard. Remark: When you sign in to Visual Studio on multiple computers using the same personalization account, your settings can be synchronized across the computers. Although the .vssettings file allows you to share a lot of configuration settings, it cannot be used to share the installed features and extensions. However this is possible through an

Property based testing in C#–CsCheck

Almost a year ago I wrote a series of blog posts on how to use property-based tests in C#. Part 1 – Introduction Part 2 – An example Part 3 – Finding edge cases Part 4 – Writing your own generators Part 5 – Locking input In this series I used FsC https://fscheck.github.io/FsCheck/ heck as the library of my choice. Although originally created for F#, it also works for C# as I have demonstrated. However as it was originally created for F#, it sometimes feels strange when using FsCheck in C#. If you prefer a more idiomatic alternative, you can have a look at CsCheck , also inspired by QuickCheck but specifically created for C#. CsCheck offers no specific integration but can be used with any testing framework(XUnit, NUnit, MSTest, …). Here is a small example: CsCheck does it really well in the shrinking challenge and offers support for multiple types of tests including concurrency testing . This is a feature I really like as concurrency related issues

Share a private key without using passwords

If you follow security best practices, you are not re-using the same password for multiple purposes. As a consequence you end up with a long list of passwords that you need to secure and manage. Although the use of a password vault certainly improved the experience, I still try to avoid the usage of passwords as much as possible. Today I want to share a ‘trick’ I discovered that allows you to share(export/import) a PFX file without using passwords. No clue what a pfx is? Let me explain that first… A PFX file, also known as a PKCS#12 file , is a binary format used to store certificates and their associated private keys . It combines 2 parts: A certificate part : A certificate is a digital document that contains information about an entity (such as a person, organization, or server). It is used for authentication, encryption, and secure communication. Certificates are issued by a Certificate Authority (CA) . A private key part : The private key is a cryptographic key

The importance of the ubiquitous language

We all know that the hardest thing in software development is naming things . Domain Driven Design tries to tackle this by focusing on the 'ubiquitous language'. The "ubiquitous language" refers to a shared language that is used by all team members, including domain experts, developers, and stakeholders, to discuss the domain and the software being developed. This language is designed to bridge the communication gap between technical and non-technical team members, ensuring that everyone has a clear understanding of the domain concepts and requirements. The ubiquitous language consists of domain-specific terms and concepts that are defined collaboratively and consistently used across all artifacts of the software development process, including code, documentation, and discussions. By using a common language, DDD aims to reduce misunderstandings and ambiguities, leading to more effective collaboration and better software designs. The best way to emphasize the imp

Azure Static Web App–Authorization

As a follow-up on the presentation I did at CloudBrew about Azure Static Web Apps I want to write a series of blog posts. Part I - Using the VS Code Extension Part II - Using the Astro Static Site Generator Part III  – Deploying to multiple environments Part IV – Password protect your environments Part V – Traffic splitting Part VI – Authentication using pre-configured providers Part VII – Application configuration using staticwebapp.config.json Part VIII – API Configuration Part IX – Injecting snippets Part X – Custom authentication Part XI(this post) – Authorization If we talk about authentication, we also have to talk about authorization. Authorization is role based and every user gets at least one role for free: the “anonymous” role. Once you are authenticated, a second role is assigned; the “authenticated” role. You can see this by browsing to the .auth/me endpoint after authenticating. You’ll get a response back similar to this

Implement the mediator pattern using MassTransit

The mediator pattern is a behavioral design pattern used in software engineering. It defines an object that encapsulates how a set of objects interact .  In object-oriented programming, programs often consist of many classes. As more classes are added to a program, especially during maintenance or refactoring, the problem of communication between these classes becomes complex. Direct communication between objects can lead to tight coupling, making the program harder to read, maintain, and change. The mediator pattern introduces a mediator object that acts as an intermediary between interacting objects. Instead of direct communication, objects now communicate through the mediator. This reduces dependencies between objects and promotes loose coupling. A popular way to implement the mediator pattern in .NET is through the popular MediatR library . But if you are already using Masstransit ,  there is no need to introduce an extra dependency as Masstransit has built-in support for

Don’t be a feature team

I saw the following quote passing when watching a presentation by Nick Tune : The best single source for innovation is your engineers (because  they’re working with the enabling technology every day, so they’re in the best position to see what’s just now possible). This quote comes from Marty Cagan who makes the distinction between product teams and feature teams. What is the difference between the 2? Empowerment! Marty Cagan explains empowerment like this in one of his articles : Empowerment of an engineer means that you provide the engineers with the problem to solve, and the strategic context, and they are able to leverage technology to figure out the best solution to the problem. An easy way to tell whether you have empowered engineers or not, is if the first time your engineers see a product idea is at sprint planning, you are clearly a feature team, and your engineers are not empowered in any meaningful sense. The reality is that most teams freedom is limi

Azure Static Web App–Custom authentication

As a follow-up on the presentation I did at  CloudBrew  about Azure Static Web Apps I want to write a series of blog posts. Part I - Using the VS Code Extension Part II - Using the Astro Static Site Generator Part III  – Deploying to multiple environments Part IV – Password protect your environments Part V – Traffic splitting Part VI – Authentication using pre-configured providers Part VII – Application configuration using staticwebapp.config.json Part VIII – API Configuration Part IX – Injecting snippets Part X(this post) – Custom authentication After getting side tracked by talking about configuration, it is now time to focus back on the authentication and authorization part.  I already explained that when using Static Web Apps you get 2 authentication providers out-of-the-box: GitHub Azure Active Directory (Microsoft Entra ID) Today I want to show you how to use the OIDC provider of your choice through custom authentication. So if you want to specify your own Azure AD

GraphQL OWASP Cheat Sheet

I’m a big fan of GraphQL but as with every technology it comes with it's own set of (security) challenges. To properly secure your GraphQL API, I can recommend to check the GraphQL Cheat Sheet . It handles common attack vectors and best practices to avoid them.   If you have never heard about the OWASP Cheat Sheet Series , also have a look at all the other sheets in the series. A must read for every developer!

.NET 8–It’s time to get rid of these flaky tests!

There is only one thing worse than having no tests and that is having flaky tests. You know, tests that sometimes fail and sometimes succeed when the code itself didn't change. One of the biggest reasons this can happen is when your tests have time related logic. My tests succeed on Monday but not during the weekend. Sidenote: there is a cool Azure DevOps feature specifically to handle and fix flaky tests. Anyway that is not the topic of this post. In .NET 8 Microsoft tried to fix this by introducing a new time abstraction API. Instead of directly calling DateTime.Now or DateTime.UtcNow inside your code, you can now use the TimeProvider class and ITimer interface. Together they offer time abstraction functionality, facilitating the simulation of time in testing scenarios. Remark: Microsoft was so nice to backport these APIs and made them available in a separate NuGet package Microsoft.Bcl.TimeProvider . So now we can update our code to use the TimeProvider class i

RabbitMQ–Using Alternate Exchanges to avoid loosing messages

A few days ago I blogged about a situation we had where some messages send to RabbitMQ got lost. I showed a possible solution when using MassTransit. We further investigated the issue and a colleague(thanks Stijn!) suggested another solution by using a specific RabbitMQ feature: Alternate Exchanges . The documentation explains the feature like this: It is sometimes desirable to let clients handle messages that an exchange was unable to route (i.e. either because there were no bound queues or no matching bindings). Typical examples of this are detecting when clients accidentally or maliciously publish messages that cannot be routed "or else" routing semantics where some messages are handled specially and the rest by a generic handler Alternate Exchange ("AE") is a feature that addresses these use cases. Whenever an exchange with a configured AE cannot route a message to any queue, it publishes the message to the specified AE instead. If that AE doe

Azure DevOps–Set default access level

Something that I always have to explain when someone uses Azure DevOps for the first time is that there are 2 levels that needs to be configured to give someone access to Azure DevOps. The first level is the security level. By adding a user to a specific security group at the project level, the user is able to access specific features and execute specific actions However there is also a second level, the access level. This level is related to the acquired license and also defines which features are available to you. So only if the 2 levels align, you can use a specific feature inside Azure DevOps A typical situation: A project administrator adds a new user to a team inside Azure DevOps. By adding a user to a team, he is added to the Contributor group and should be able to access most features at the project level. However because he is new in Azure DevOps, the user gets a default access level assigned. If you didn’t change this default, this will be the Stakeholder access le

Azure DevOps Server–Change attachment size

If you are using Azure DevOps in Azure, attachments added to a workitem are limited to 60MB in size, a value you cannot change. On premise, when using Azure DevOps Server, the default attachment size is limited to 4MB. However you can increase this value to up to 2GB. Let me show you how to get this done… Log on to the application tier of your Azure DevOps server Remark: You have to log in with an account that is a member of the Team Foundation Administrators group Browse to the following URL to open the ConfigurationSettingsService: http://localhost:8080/tfs/DefaultCollection/WorkItemTracking/v1.0/ConfigurationSettingsService.asmx Choose the SetMaxAttachmentSize operation from the list of available operations: Specify a maxSize value in bytes and click on Invoke to update the configuration setting: You can validate if the value was changed correctly by going to the GetMaxAttachmentSize operation and invoking it. This will return

F# - The essentials

Long time readers of my blog know that my programming language of choice is not C# but F#. Although I don't have a lot of opportunities to use it in my day to day job, I always like to return to functional programming land whenever I can for small (side) projects. If you never have tried F# yourself, this is a good moment to give it a try. The people from Amplifying F# released a FREE online course based on Ian Russell’s Essential F# book. Every week a new aspect of the language is introduced and each lesson takes only 10-15 minutes. So no excuses, just give it a try. The lessons just got started, so this is the right time to still join the course. It will make you a better programmer in general and will positively impact the way you write your C# code as well.