Skip to main content

Posts

Showing posts from March, 2023

TypeScript–Template literal types

Although I spend most of my time in C# land, I like to explore other programming languages to stretch my brain. Recently I was looking again at TypeScript where I noticed the concept of Template Literal Types . How to explain Template Literal Types? Not easy to give a good explanation. But let’s give it a try: Template Literal Types are string literals on steroids. Add a type variable to a Template Literal and Typescript will create a type with all the possible combinations for you. This allows you to compose types from others in a quick and easy way. Not clear yet? Maybe I should switch to an example: I’ve created a string literal ‘Person’ and a Template Literal Type ‘Greeting’ using the string literal. Now only valid combinations of the two are possible: Of course this is a contrived example, let us create a more realistic one for example to specify a valid padding value:

Azure - Data API Builder

While browsing through Github, I discovered the following project: Data API builder for Azure Databases (DAB). With data API builder, database objects can be exposed via REST or GraphQL endpoints so that your data can be accessed using modern techniques on any platform, any language, and any device. With an integrated and flexible policy engine, native support for common behavior like pagination, filtering, projection and sorting, the creation of CRUD backend services can be done in minutes instead of hours or days, giving developers an efficiency boost like never seen before. Sounds cool and a perfect fit for a small application where you only need an API to expose some data. Let’s give it a try! Setup Data API builder provides a CLI tool to help us with the configuration and the setup of our project. Install the tool using the following command: dotnet tool install --global Microsoft.DataApiBuilder Now that the tool is installed successfully, we need to create a co...

Learning from failure in software

Although not everyone in my team would agree, I dare to say that building software is easy. The difficult part starts AFTER your first release when you need to start maintaining the application you've build while at the same time introducing new features, keeping the technical debt under control, evolve the application architecture under ever changing business needs and all of this at a minimal cost. Building software is easy During the lifetime of our application failures will happen. Although this is difficult to explain to our business stakeholders, failure in software is inevitable; people make mistakes, requirements are misunderstood, business needs change, … Rather than engaging in a man hunt to avoid failure, we embrace it and focus on learning from our mistakes. Embrace failure An important tool in our toolbox here is incident analysis ; we need to figure out what happened, what caused a failure and most important how we can improve. In the complex (distribu...

C# - Clean up your exception handling logic with Exception Filters

While doing a code review I noticed the following code: In the code above we handle 2 exceptional cases. One specific case when the Task is cancelled and an OperationCancelledException is thrown. In that case we ignore the exception and decide to not log it anywhere (we can discuss if this is a good idea or not, but that is not what I want to talk about). And a second exceptional case when any other error type occurs we write it to our logs. Although there is nothing wrong with the code above, we can further simplify it by introducting an Exception Filter . This allows us to catch and handle exceptions based on requirements you define for the exception. These filters use the catch statement with the when keyword: Nice! Another trick I noticed in the documentation where exception filters are useful is when you want to examine all exceptions but not handle them. This is useful for example when you want to log the exception:

Share reusable UI components through a Razor class library

One ASP.NET Core feature that I really like and most people are not aware of it existence are Razor Class libraries (RCL). With RCL you can package Razor views, pages, Razor components and view components and reuse them in different applications. I blogged about RCL before and although I really like the feature I got feedback from my development teams that the behavior was not consistent and they sometimes couldn’t get it working. I never had time to really investigate the root cause until now. So this blog post is here to explain my findings. The development environment First of all it is important to understand that the behavior of RCL is different in Development compared to other environments. When running the app that uses the RCL from build output ( dotnet run ), static web assets are enabled that allow ASP.NET Core to load static web assets from locations outside the wwwroot. This is required because ASP.NET Core will load the assets directly from the RCL NuGet location....

The lost art of writing SQL queries

These days, with Entity Framework Core being so good, it became rare that developers had to write their own SQL queries. Of course this is a great productivity one and even helps us to avoid security issues like SQL injection but this all comes with a cost. I noticed that most (junior) developers no longer are able to write anything but the most trivial SQL queries.  Time to fix that! If you want to sharpen your SQL skills, have a look at https://www.sql-practice.com/ . Here you  get a whole list of exercises that require writing SQL queries. If you get stuck hints are available that help you get on the right track:  

Executing HTTP requests through Visual Studio

In Visual Studio 2022 v17.5, a new feature was introduced that allowed you to execute HTTP requests directly from the Visual Studio IDE. This is great of you want to test an API endpoint without leaving your IDE. To use this feature, open a Visual Studio project, right click on it and choose Add –> New Item . Search for http to find the HTTP file template , specify a name and click on Add . Now we can start writing our HTTP requests inside this file. You even get Intellisense while building up your requests. Once you are done, you can either click on the play icon next to the line or right click on the line and choose Send Request from the context menu. It is possible to have multiple calls in the same file, therefore separate your requests with a comment line using three hashes: You can also create variables by prefixing them with an @ and use these variables using double curly braces:  

Azure Pipelines error - User lacks permission to complete this action. You need to have 'ReadPackages'.

A colleague contacted me because she couldn't get the build pipeline running successfully. The build always failed on the NuGet restore task: This is the error that we got: ##[error]The nuget command failed with exit code(1) and error(Unable to load the service index for source https://tfs.server.be/tfs/DefaultCollection/_packaging/797f899f-9ad1-4158-93bc-8f3293cf4a59/nuget/v3/index.json. Response status code does not indicate success: 403 (Forbidden - User 'Build\534a066a-3992-4851-a816-b189836bee69' lacks permission to complete this action. You need to have 'ReadPackages'. (DevOps Activity ID: 8D53BF1D-E45E-49C4-879F-6CBD8635D1CE)). The error above indicates that the account running the build agent doesn’t have the necessary rights to connect to our Azure Artifacts nuget feed. This is because by default Azure DevOps automatically restrict the scope of the job agent to the agent itself. As a result, it has no visibility of any services outside of it, in...

Import a .pfx file at build time

For our desktop applications (WPF and even Winforms), we are still using ClickOnce . Although the technology is rather old, it still serves our needs. An important part to securely deploy our applications through ClickOnce is signing the application and the deployment manifest using a public/private key pair. During local development, you can use a PFX file and select it on the Signing tab for your project. If you build the project for the first time and you didn’t provide the PFX password yet, you get an error like this: C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(3476,5): Error MSB3326: Cannot import the following key file: . The key file may be password protected. To correct this, try to import the certificate again or import the certificate manually into the current user’s personal certificate store. C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\Microsoft.C...

.NET Core - Remove older SDKs and runtimes

Last week I talked about a bug we discovered in the latest(at the moment of writing) .NET core runtimes that caused our Razor ViewComponents no longer being rendered. We found a workaround by explicitly setting the SDK version using a global.json file: The global.json file above selects 6.0.300 or any later feature band or patch for 6.0 that is installed on the machine. Although this is a good workaround we wanted to avoid to have all developers update their projects. So on the build server we tried a different approach. Our first attempt was rolling back the Visual Studio build tools but that didn’t turn out to be a good solution. Luckily we can also uninstall a .NET Core SDK version using the .NET Uninstall Tool ( dotnet-core-uninstall ) . This tool is not installed out-of-the-box so you first need to download it here . After downloading it, run the MSI to install it. Running the tool Now that we have the uninstall tool installed, we can execute it. First run the do...

dotnet publish error - The "TransformWebConfig" task failed unexpectedly.

When trying to publish an ASP.NET Core web application through the dotnet publish command on our build server, it failed with the following error message: C:\Program Files\dotnet\sdk\7.0.201\Sdks\Microsoft.NET.Sdk.Publish\targets\TransformTargets\Microsoft.NET.Sdk.Publish.TransformFiles.targets(50,5): error MSB4018: The "TransformWebConfig" task failed unexpectedly. [D:\b\3\_work\222\s\SOFACore\Example\eShopExample\eShopExample.csproj] C:\Program Files\dotnet\sdk\7.0.201\Sdks\Microsoft.NET.Sdk.Publish\targets\TransformTargets\Microsoft.NET.Sdk.Publish.TransformFiles.targets(50,5): error MSB4018: System.Exception: In process hosting is not supported for AspNetCoreModule. Change the AspNetCoreModule to at least AspNetCoreModuleV2. [D:\b\3\_work\222\s\SOFACore\Example\eShopExample\eShopExample.csproj] C:\Program Files\dotnet\sdk\7.0.201\Sdks\Microsoft.NET.Sdk.Publish\targets\TransformTargets\Microsoft.NET.Sdk.Publish.TransformFiles.targets(50,5): error MSB4018: at Microsoft.N...

Https redirection in IIS Express

I think everyone agrees that using HTTPS for your web applications is the default. Therefore it makes sense to have the HttpsRedirection middleware always active in your ASP.NET Core application: However when I tried to run this ASP.NET Core application using IIS Express , I always arrived at the root url of my local IIS instance( https://localhost/ ): I found the source of this behaviour in the launchsettings.json file where I had only http configured: The https middleware causes the redirect to https but as there is no IIS Express https endpoint active I end up on https://localhost (and get the default IIS web page): The solution is to active an https endpoint by specifying the sslPort :

Postman GraphQL Client

I talked about interacting with GraphQL API's through Postman before. It started with no specific support at all and evolved to some basic features over time. With the 10.10 release GraphQL became a first class citizen , a good indication of the popularity and maturity of the GraphQL ecosystem. When you open up Postman and you click on New , you get a GraphQL request among the list of available options: Now you get a request window specifically tailored to GraphQL request. If we enter the schema url in the request url bar, the client will automatically introspect the schema: Now we can use the built-in query builder to start writing our GraphQL queries. This is really useful for people who are new in the GraphQL ecosystem and are not used yet to the specific syntax. We can click on the fields we want to fetch and can specify any parameters inline: This not only works for writing queries, but we can also use the query builder for Mutations and Subscriptions: ...

Using Github Copilot in Visual Studio

With GitHub Copilot you get autocomplete-style suggestions from an AI pair programmer as you code. Let me show you how to get started with Github Copilot in Visual Studio. Remark: Before you can start you need to have an active GitHub Copilot subscription . Install the extension You can install the extension directly in Visual Studio. Therefore go to Extensions –> Manage Extensions in Visual Studio. Search for Github Copilot and click on Download . After restarting Visual Studio, Visual Studio will ask you to active Github Copilot on your device. After walking through the device activation flow, you are finally ready to go. Writing code with Github Copilot Now that our extensions is up and running, let us write some code. When using Github Copilot it feels like you have a lot smarter Intellisense available. I create a Book class and when I try to add a property Visual Studio is aware that I want to add typical properties for a book, so I get sugg...

GraphQL HotChocolate - Method overloading for queries

When building my GraphQL schema with HotChocolate , I typically use the code first or annotation first approach. Annotation-based example Code-first example In both cases I start from a class where I add multiple methods where each method maps to a different query. But what if I use method overloading and introduce a second implementation of the method using different arguments? HotChocolate will not complain and you will be able to succesfully run your GraphQL endpoint. However when you look at the generated GraphQL schema only one of the methods is available: To make this work we need to tell HotChocolate to use a different name for our overloaded method: Annotation-based example Code-first example That should do the trick.

Visual Studio 17.5 - ViewComponents are broken

On our last architecture board, one of the architects shared the following problem. After upgrading to Visual Studio 17.5 Razor ViewComponents were no longer rendered. Instead the viewcomponent tag remained on the page. *UPDATE: In the meanwhile Visual Studio 2022 version 17.5.2 got released which contains a fix for the issue I'm explaining below* This problem manifested not only on the local developer machine but also on the build server after upgrading the Visual Studio Build tools to 17.5.  The root cause is a bug in the latest dotnet runtimes that are installed as part of the Visual Studio upgrade. It affects the following dotnet runtimes  6.0.14 and 7.0.3 that match with this SDK version: 6.0.114, 6.0.309, 6.0.406 for .Net 6 and 7.0.103, 7.0.200 and 7.0.201 for .Net 7. As a workaround we included an extra build step in our yaml pipeline that uses a non affected SDK version: Of course this would require all our teams to update their projects. So what we did instead...

Azure DevOps Server- Update Git credentials

Oh no, after writing a lot of posts about what I thought would be an easy operation, I'm back again with a last follow up post on moving an Azure DevOps Server instance from HTTP to HTTPS. If you missed the previous posts: Azure DevOps Server–Switch from HTTP to HTTPS–Part 1 – IIS changes Azure DevOps Server–Switch from HTTP to HTTPS–Part 2 – Version Control changes Azure DevOps Server–Switch from HTTP to HTTPS–Part 3 – Build changes Azure DevOps Server–Switch from HTTP to HTTPS–Part 4 – NuGet changes In this last post(I really promise) I want to talk about Git Credential Manager . Git Credential Manager simplifies authentication with your Azure Repos Git repositories. Credential managers let you use the same credentials that you use for the Azure DevOps Services web portal. It can be installed as part of Git for Windows and thanks to it you don’t need use SSH keys or Personal Access Tokens to connect to your Azure DevOps G...

Papers we love

Short post today as I’m actively debugging a production issue. (What a fun way to start your day...) To understand the future you first need to understand the past. That is why I think it is important to spend time reading academic papers both old ones that form the foundation of the current state of programming and new ones that introduce new ideas and allow you to peek in a possible future. A good way to get started is through Papers We Love : You can start reading some of the papers at their Github repo or watch one of the videos on their Youtube channel .

Visual Studio –Git line staging

Visual Studio supports staging files from the moment Git support was introduced and most of the time that is sufficient. But sometimes it can be useful to stage chunks of changes in a file instead of a complete file. This feature (also known as interactive staging) was introduced in Visual Studio 2022 v17.2. I never used the feature before so let's see how this works... Git line staging is still marked as a preview feature but if you are using Visual Studio 2022 v17.2 or higher, it should be enabled by default. The first thing you should notice when line staging is enabled, is that individual changes are visible in the editor margin. Added, edited or deleted lines are all shown using a different color and annotation: If we now click on a color margin, an inline Peek Difference view is opened. Now you can  stage the selected change by clicking on the + Stage Line <LineNumbers> button: You can also select one or more lines in the Peek Difference view, right...

Elastic Search–Help! My indices are not cleaned up

Last week, one of the server admins contacted me that the disk of our ElasticSearch instance was filling up quite fast. He asked me if this was normal? :-) Short answer, no. Let's investigate the issue together... I started by opening up Kibana and opened Stack Management through the menu on the left. On the Stack Management page, I clicked on Index Management . Here I can see the list of all indices. I sorted on Storage size and noticed that MetricBeats was causing the issue. That is strange as I know for sure that I had configured a lifecycle policy that would cleanup old data. But then I noticed that the health of one of the indices is ‘yellow’. Let’s see what causing this by executing the following request: GET /.ds-metricbeat-8.2.0-2022.12.03-000011/_ilm/explain?human This returns the following result: Notice line 24. The problem was that the index was configured to have at least one replica. As we are running a single node cluster in development, the...

Architectural thinking

As a developer you have a lot of opinions; tabs or spaces, Angular or React, Visual Studio or Jetbrains Rider, ... Your personal preferences have a large impact on your productivity and help you be the great developer that you are. But if you ever take the step to become an architect, you need to get rid of all your opinions and start with something I call ‘architectural thinking’. It means starting from the facts, understanding the characteristics of every option and being able to effectively analyze the trade-offs . It means removing subjectivity from the equation, no more ‘I think that GraphQL is better than REST’. Instead compare the pro’s and con’s of every solution and use that as the basis of your design decisions. (And of course don’t forget to document them using an ADR ). There is no such thing as a silver bullet. If you don’t start applying tradeoff analysis a trap that I have fallen in myself is that you become an evangelist for certain technologies.  You st...

Package Validation

I recently discovered a .NET feature I didn’t know it existed; Package validation . Package validation was introduced as a part of the .NET 6 SDK. It allows you as a package author to check if your NuGet packages are consistent and well formed. At the moment of writing this post, the tooling provides the following checks: Validates that there are no breaking changes across versions. Validates that the package has the same set of publics APIs for all the different runtime-specific implementations. Helps developers catch any applicability holes. Enabling package validation is nothing more than setting the EnablePackageValidation property to true in your csproj file: Now 3 different validators can kick in everytime you run dotnet pack : The Baseline version validator validates your library project against a previously released, stable version of your package. The Compatible runtime validator validates that your runtime-specific implementation assemblies are...

Visual Studio–License validation task failed unexpectedly

Yesterday I talked about how I got into trouble after updating Visual Studio. No matter what I tried my Visual Studio instance closed after a few seconds without any error or warning. I explained how I found the root cause by activating the Activity log. There I found the following warning: License validation task failed unexpectedly. What higher in the document I found a related error message: The input is not a valid Base-64 string as it contains a non-base 64 character I started a search on the Internet to find a solution and discovered the following article: Visual Studio 2022 crashing on startup - Microsoft Q&A This brought me to the final solution. Here are the exact steps I took: I browsed to the C:\Users\<username>\AppData\Local\Microsoft\VSCommon\OnlineLicensing\VisualStudio folder. I removed both the 17.x folders. Now I reopened Visual Studio. Visual Studio noticed that my license information is gone and shows me the following screen: ...