Skip to main content

Posts

Showing posts from April, 2024

ASP.NET Core -Updating the OpenTelemetry configuration

Today I had to make some changes to an existing ASP.NET Core application still using .NET 6 and a preview version of the OpenTelemetry.Extensions.Hosting nuget package. I thought it was a good time to update to .NET 8 and to the latest OpenTelemetry version so updated both the targetframework and the used package versions. After the changes my csproj file looked like this: However when I tried to compile and run my application I got the following error message: 'IServiceCollection' does not contain a definition for 'AddOpenTelemetryTracing' and no accessible extension method 'AddOpenTelemetryTracing' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?) Here is the code that caused the error: Turns out that the OpenTelemetry API has changed quite significantly since the preview and that AddOpenTelemetryTracing has been removed in favour of AddOpenTelemetry sinc

TypeScript compiler trick

Last week I showed you how to use Pattern Matching and more specifically the Type Pattern in TypeScript. I used a set of commands: with a corresponding command handler as an example: While reading the following article I noticed that a TypeScript compiler trick was mentioned to further improve the type safety of our code. In the article the following code was used: As it wasn’t immediately clear to me what this code does exactly I decided to write a blog post about it. Explaining the magic The TypeScript code above defines a generic type alias named CommandTypeOf . This alias takes a type parameter T that must extend from a type named Command . The resulting type of CommandTypeOf<T> is the type of the type property of T . In simpler terms, this code is used to extract the type of the type property from our Command type. You can use CommandTypeOf<CreateUserCommand> to get the type 'createUser' , which is the type of the type property in CreateUse

Switch expression for void methods

While preparing yesterday’s post, I was wondering if I could rewrite the following switch statement to use the new .NET 8 switch expression syntax. Here is the original code: And here is my attempt to rewrite this to a switch expression: Unfortunately this didn’t work and resulted in a compiler error: Only assignment, call, increment, decrement, await and new object expressions can be used as a statement. Turns out that switch expression cannot return void . It must return a value and this value must be consumed and cannot be discarded. Too bad! Maybe this is something that will change in future .NET versions as hinted here : The switch_expression is not permitted as an expression_statement. We are looking at relaxing this in a future revision. More information Recursive pattern matching - C# feature specifications | Microsoft Learn switch expression - Evaluate a pattern match expression using the `switch` expression - C# | Microsoft Learn

Type pattern matching in C# and TypeScript

Although C# remains an object-oriented programming language, it has incorporated more and more functional techniques over the years. One of this techniques is ‘pattern matching’.   On the Microsoft Learn website , it is explained like this: Pattern matching is a technique where you test an expression to determine if it has certain characteristics. Not so sexy right? In fact it is rather boring described like this. That is because pattern matching is not something fancy new. It is here to simplify complex if-else statements into more compact and readable code. Pattern matching does not aim at writing code that cannot be written without. Its only purpose is to have more concise and elegant code. There are multiple supported pattern types; constant patterns , declaration patterns , relational patterns , and so on… In this post I want to talk about a specific pattern; the type pattern. The type pattern in itself is quite simple, it checks the runtime type of an express

Giving the .NET smart components a try–The Smart TextArea

Microsoft announced last month, the .NET Smart Components, an experimental set of AI-powered UI components that can be added to your .NET apps. They asked us to give these components a try and share our feedback. In a first post I tried the Smart Combobox . Now let’s have a look at the Smart TextArea component. The idea of the Smart TextArea is that it gives you a smart autocomplete that can be tailored to the specific context you want to use it in. It looks at what the user is currently typing and tries to make suggestions based on the configured context and tone. It feels quite similar to prompt engineering but with a focus on helping you typing a text faster and easier.  Here is an example use case from the documentation : Your app might allow agents to respond to customer/staff/user messages by typing free text, e.g., in a live chat system, support ticket system, CRM, bug tracker, etc. You can use Smart TextArea to help those agents be more productive, writing better-

Azure DevOps Wiki–The order file in this hierarchy is missing paging entries.

One of the features of Azure DevOps is to create a wiki based on a folder inside a Git repo. Every page inside your wiki is a separate markdown file. This means that you can change the content of your wiki outside Azure DevOps and push the changes when you are ready, the same way you handle your code inside your Git repo. If you are a developer, this is probably the way you’ll create any content, but for people who are less technical, they can directly add/delete/change pages inside the wiki.  All interactions with the Git repo is handled behind the scenes making it a very user friendly experience for most people. Today I had to make a small change inside the wiki of one of my clients. I had to move a page in the file hierarchy. As I didn’t had the repo available on my local machine, I decided to directly apply the change inside the wiki instead of creating a local git repo,  pulling the source code, making my change and push it again. So I simple dragged the page to a different

XML External Entity Attack and .NET Core

Improving the security of the systems I help design and build for my clients is a continuous effort where every day new vulnerabilities are discovered. That being said, the OWASP Top 10 hasn't change that much since it's original introduction. This means that using the OWASP Top 10 remains a good starting point and the first important step towards more secure code. During a security audit, we identified that one of our older (.NET) applications had an XML External Entities(XXE) vulnerability. What is the XXE vulnerability? An XML eXternal Entity injection (XXE) is an attack against applications that parse XML input. An XXE attack can happen when untrusted XML input with a reference to an external entity is processed by a weakly configured XML parser. It is a high risk vulnerability as it can lead to: A denial of service attack on the system A Server Side Request Forgery (SSRF) attack The ability to scan ports from the machine where the parser is locat

VSCode Day and Azure Developers .NET Day are coming!

April is a great month if you are a developer. This month you can attend both VS Code Day 2024 AND Azure Developers .NET Day 2024 . VS Code Day 2024 Start by attending the VS Code Day(in fact it are 2 days) on April 23 and 24 .  During VS Code Day you learn everything about the latest and greatest features of Visual Studio Code. Of course, it will be no surprise that there will be a big focus on AI. Day 1 will be a kind of ‘preshow’ event where Sonny Sanghe will build a LinkedIn clone with Azure and NEXT.JS. It will be a deep dive into using Microsoft Azure, GitHub Copilot, Cosmos DB, and TypeScript to craft robust, scalable web applications. On Day 2 it is time for the main event where multiple sessions will be hosted. A sneak peak of some of the available sessions: JavaScript developers: Build fast and have fun with VS Code and Azure AI CLI by Natalia Venditto Real World Development with VS Code and C# by Leslie Richardson & Scott Hanselman Beyond the Editor: Tips to get t

SQL Server–Export varbinary column to disk

At one of my customers we store files in the database in varbinary(max) columns. To debug an issue we wanted to read out the files. Of course we could create a small program to do this, but we wanted to do it directly from the SQL Server Management Studio. We created a small database script that uses OLE Automation procedures: To use this script for your own purposes, replace the query after the cursor creation: DECLARE FILEPATH CURSOR FAST_FORWARD FOR <Add your own SELECT query here> The first time that we executed this script, it failed with the following error messages: Msg 15281, Level 16, State 1, Procedure sp_OACreate, Line 1 [Batch Start Line 0] SQL Server blocked access to procedure 'sys.sp_OACreate' of component 'Ole Automation Procedures' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ole Automation Procedures' by using sp_configure. For more

ASP.NET Core - Use factory based middleware with scoped services

Yesterday I talked about a problem we encountered when trying to inject a scoped service into ASP.NET Core middleware. The middleware used was convention based middleware, one of the ways to construct middleware in ASP.NET Core. With convention based middleware there isn’t a base class or interface to implement. The only rules your middleware class needs to apply to are: It has a public constructor with a parameter of type RequestDelegate . It contains a public method named Invoke or InvokeAsync . This method must: Return a Task . Accept a first parameter of type HttpContext . Convention based middleware is registered with a singleton lifetime, so you can only constructor injection for the dependencies with a singleton lifetime. For transient and scoped dependencies you need to add extra parameters to the InvokeAsync() method: There is a log of magic going on when using convention based middleware and it shouldn’t be a surprise that pe

ASP.NET Core–Cannot resolve from root provider because it requires scoped service

A colleague contacted me with the following problem; when running his ASP.NET Core application it failed with the following error message: Cannot resolve IApiLoggingService from root provider because it requires scoped service NHibernate.IInterceptor In this post I walk you through the different steps we took to investigate the issue and explain how we solved it. But before I dive into the problem itself I first want to give some background info on dependency injection in ASP.NET Core and service lifetimes. Dependency injection and service lifetimes ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. Registration of a dependency is done in the built-in service container, IServiceProvider . Services are typically registered at the app's start-up and appended to an IServiceCollection . Once all services are added, you use BuildServiceProvider to

Seq–Event JSON representation exceeds the body size limit 262144;

At one of my clients, Seq is used as the main tool to store structured log messages. If you never heard about Seq before, on their website they promote Seq like this: The self-hosted search, analysis, and alerting server built for structured logs and traces. It certainly is a great tool, easy to use with a lot of great features. But hey, this post is not to promote Seq, I want to talk about a problem we encountered when using it. A developer contacted me and shared the following screenshot: Instead of the structured log message itself being logged, we got the error message above for a subset of our messages. The problem was that the structured log message contained a large JSON object exceeding the default limit of 262144 bytes. Although you could wonder if it’s a good idea to log such large messages in general, for this specific use case it made sense. So you can override the default for a specific application by setting the eventBodyLimitBytes argument when configurin

Giving the .NET smart components a try–The Smart Combobox

Microsoft announced last month, the .NET Smart Components, an experimental set of AI-powered UI components that can be added to your .NET apps. They asked us to give these components a try and share our feedback. And that is exactly what we are going to do in this blog post. Right now we have 3 components available: Smart Paste Smart Textarea Smart Combobox If you want a good overview of the available components, check out the video from Steve Sanderson: Although the video shows some compelling use cases for each of these components, we have to start somewhere. So in this post I’ll focus on the Smart Combobox as it doesn’t require any language model backend. Here is the main use case that Smart Combobox tries to solve: The problem with a traditional combobox is that if there are a lot of options available, it can be a challenge to select the right item from the list. With Smart Combobox,  the component uses semantic matching to find an item from the list t

Running large language models locally using Ollama

In this post I want to introduce you to Ollama . Ollama is a streamlined tool for running open-source LLMs locally, including Mistral and Llama 2. It bundles model weights, configurations, and datasets into a unified package managed by a Modelfile. Ollama supports a variety of LLMs including LLaMA-2, uncensored LLaMA, CodeLLaMA, Falcon, Mistral, Vicuna model, WizardCoder, and Wizard uncensored. Installation To install Ollama on Windows, first download the executable available here: https://ollama.com/download/OllamaSetup.exe Run the executable to start the Installation wizard: Click Install to start the installation process. After the installation has completed Ollama will be running in the background: We can now open a command prompt and call ollama: Download a model Before we can do anything useful, we first need to download a specific language model. The full list of models can be found at https://ollama.com/library . Here are some examples: Model

Building platforms–Strike the right balance

There is a lot of hype around platform engineering these days. The concept of creating platform teams and building platforms to deliver software at scale is not new as companies like Google, Facebook, Netflix etc. have a long history of building developer platforms. And also the much quoted Team Topologies book by Matthew Skelton and Manuel Pais was already released in 2019. Some wonder if this is just a fancy new name for existing practices and if there is a risk that these developer platforms become a bottleneck, exactly what they are supposed to alleviate.  Some dare even say that we made today’s development landscape so horrendously complex that we need these platforms to hide all this complexity. No matter if you think Platform Engineering is overhyped or not, before you go on this journey I would like to share the following quote: If your users haven’t build something that surprised you, you probably didn’t build a platform I saw this quote in the Build abstracti

Autonomous Computing and how it influenced the way I build software

There are a lot of concepts and papers that have influenced the way I design and build software. One concept that certainly should be on the list is 'Autonomous Computing' as introduced by Pat Helland more than 20 years ago. If you have never heard about this concept, I would recommend to first read this paper before you continue reading my blog post. Back? Let’s continue. In the paper Pat introduces the concept of Fiefdoms and Emissaries and Collaborations . Fiefdoms refer to independent, autonomous components within a computing system. Each fiefdom is responsible for a specific aspect or function of the overall system. They operate independently and have their own decision-making capabilities. Emissaries are entities that facilitate communication and coordination between fiefdoms. They act as messengers, relaying information and requests between different components of the system. Emissaries enable fiefdoms to interact and collaborate without direct dependencies o

Azure Static Web App–Distributed Functions

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 – Authorization Part XII -  Assign roles through an Azure function Part XIII -  API integration Part XIV – Bring your own API Part XV – Pass authentication info to your linked API Part XVI(this post) – Distributed Functions As I mentioned in a previous post, when creating an Azure Static Web App, you get a managed function for free. However where the static part of your Azure Stat