WinForms – Date and time input

When you need to let the user select a date and/or time of day, you can use the DateTimePicker control: You can set the control properties in the UI or programmatically: If you don’t set an initial value, it’ll default to DateTime.Now (at the time the code is executed). The value the user picked is … Read more

C# – Get the last day of the month

The last day of the month is the number of days in that month. To get the number of days in a month, use DateTime.DaysInMonth(year, month): This outputs the following: Notice that it handles leap years (2024) appropriately. Using the number of days in the month, you can get the last day of the month: … Read more

C# – How to use JsonConverterAttribute

You can use JsonConverterAttribute (from System.Text.Json) to apply a specific JsonConverter to a property. Apply this attribute on a property and specify the JsonConverter type to use, like this: In this example, it’s applying ExpirationDateConverter (a custom JSON converter) to handle the ExpirationDate. For reference, here’s ExpirationDateConverter’s definition: Now serialize the object to JSON: Here’s … Read more

C# – Changing the JSON serialization date format

When you serialize a date with System.Text.Json, it uses the standard ISO-8601 date format (ex: “2022-01-31T13:15:05.2151663-05:00”). Internally, it uses the built-in DateTimeConverter class for handling DateTime, which doesn’t give you a way to change the date format. To change the date format, you have to create a custom JSON converter and pass it in: This … Read more

C# – Using top-level statements

The top-level statements feature makes the Main() method implicit. This feature was added in C# 9 (.NET 5) with the purpose of decluttering a project’s entry point. Here’s what a console app looks like using a top-level statement: The compiler generates the Main() method implicitly from the top-level statements. The code above is functionally equivalent … Read more

C# – Convert an object to JSON

Converting an object to a JSON string is referred to as serialization. The best way to do serialization is by using a good JSON serializer. There are two primary options: I’ll show examples of both options below. Using JsonSerializer.Serialize() (in the built-in System.Text.Json) Here’s an example of using the built-in JsonSerializer.Serialize() (in System.Text.Json) to convert … Read more

C# – Get inserted identity value with Dapper

When you insert a record into a table with an identity column, the value for the identity column is automatically generated for you. The simplest way to get the inserted identity value is to put OUTPUT INSERTED.<identity column name> in the insert statement: To get the output value with Dapper, use ExecuteScalar<int>(): This inserts the … Read more

Error MSB4226 Microsoft.TextTemplating.targets not imported

Problem You have a project that is using text templating (such as for auto-incrementing the version number) and you’re upgrading to a new version of Visual Studio. When you open the project, you get error messages about not being able to import the Microsoft.TextTemplating.targets project: Project “…\v16.0\TextTemplating\Microsoft.TextTemplating.targets” was not imported by “…SomeProject.csproj” at (7,3), due … Read more

C# – Adding dynamic parameters with Dapper

The simplest way to add dynamic parameters when executing queries with Dapper is by passing in Dictionary<string, object>, like this: Read more about how to add items to a dictionary. You can also add dynamic parameter by using the DynamicParameters class. You can use whichever approach is simplest in the given scenario. In this article, … Read more

C# – Using SQL transactions with Dapper

When you want to execute multiple SQL commands with Dapper in a transaction, using TransactionScope is the simplest option. Here’s an example of how to use it: When you call TransactionScope.Complete(), it commits the transaction. If you don’t call Complete(), it’ll rollback the transaction once it leaves the TransactionScope block. This keeps the code nice … Read more

C# – Execute a SELECT query with Dapper

You can query the database with Dapper by using Query() with a SELECT, specifying the type to map the results to, and optionally adding parameters. Here’s an example: Note: It returns an empty list when there’s no results. Dapper abstracts away the repetitive code involved in executing SQL queries, including mapping parameters and query results. … Read more

C# – The performance gains of HttpClient reusing connections

When you use the same instance of HttpClient for multiple requests (sequential and concurrent) to the same URL, it’ll reuse connections. Requests that get to reuse a connection are 5.5-8.5x faster than requests that have to open a new connection. There are a few scenarios that benefit from this connection reuse: Measuring the performance gains … Read more

C# – Disposing the request HttpContent when using HttpClient

In versions before .NET Core 3.0 (including .NET Framework), HttpClient disposes the request HttpContent object for you. This is surprising default behavior (a violation of the principle of least surprise for sure). This causes multiple problems, but one of the main problems is it prevents you from reusing the HttpContent object (you’re greeted with an … Read more

C# – How to send a file with HttpClient

In order to send a file in a request with HttpClient, add the file into a MultipartFormDataContent object, and send this object as the request content. Here’s an example: This sends the following multipart/form-data POST request: In this article, I’ll explain a few details about MultipartFormDataContent, and show a few other file-sending scenarios. MultipartFormDataContent Add() … Read more

C# – How to programmatically update the User Secrets file

User Secrets are stored in secrets.json. This file is specific to your application. Once you know the path of secrets.json, you can load and update it. Here’s an example of how to update secrets.json programmatically: Note: 1) For brevity, this isn’t showing all using statements. 2) This is using Newtonsoft because it’s better than System.Text.Json … Read more

C# – How to read response headers with HttpClient

When you send a request with HttpClient, it returns an HttpResponseMessage. You can read the response headers through the HttpResponseMessage.Headers property: This outputs the response headers: Raw response headers are really just key/value(s) pairs. When the response comes in, the headers are loaded into the Headers property (which is of type HttpResponseHeaders). This parses the … Read more

EF Core – Inheritance mapping

There are two ways to do inheritance mapping in EF Core: Let’s say we have a database with employees. All employees have an id and a name. There are currently two types of employees: programmers and drivers. Programmers have a language (ex: C#), and drivers have a car (ex: Honda). We can model this with … Read more

C# – Deserializing JSON with quoted numbers

There are two ways to represent numbers in JSON: as number literals (ex: 123) or as quoted numbers (ex: “123”). In this article, I’ll explain how quoted numbers are handled during deserialization in Newtonsoft and System.Text.Json and how to change the behavior. At the end, I’ll show how to write quoted numbers during serialization. Quoted … Read more