C# – Use SqlDbType.Structured for table parameters

To use a table-valued parameter (TVP) with SqlCommand (ADO.NET), pass in a DataTable as a SqlDbType.Structured parameter, like this: I’ll show a full example, starting with creating a TVP type and then inserting it as a SqlDbType.Structured parameter as shown above. 1 – Create the TVP type in SQL Server To be able to pass … Read more

C# – Serialize and deserialize a multidimensional array to JSON

System.Text.Json doesn’t support serializing / deserializing multidimensional arrays. When you try, it throws an exception like this – System.NotSupportedException: The type ‘System.Int[,] is not supported. You have three options: In this article, I’ll show an example of how to create a custom JsonConverter that handles multidimensional arrays. In this example, I’ll specifically show how to … Read more

ASP.NET Core – Client-side custom validation attributes

I wrote about how to add custom validation attributes. These are used for model validation on the server-side. You can also use these for client-side validation, which I’ll show in this article. 1 – Implement IClientModelValidator The first step is to implement the IClientModelValidator interface in the custom validation attribute class. This has a single … Read more

C# – JSON value could not be converted to System.String

When you send a request to ASP.NET with a JSON body, you get the following exception: System.Text.Json.JsonException: The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1. You can’t deserialize JSON to a string. You’re either using a string parameter with [FromBody] or your model has a string … Read more

C# – How to parse XML with XElement (Linq)

Use the XElement class (from the Linq-to-Xml API) to parse XML and work with it in memory. You can use this to search for XML elements, attributes, and modify values. This is an alternative to using an XML (de)serializer (which requires you to define a class that matches the XML structure). I’ll show examples of … Read more

C# – Read XML element attributes with XElement (Linq)

XML elements can have attributes, which are key-value pairs. To read the attributes, use XElement to parse the XML string (from the Linq-to-Xml API). Then you can use these two methods for getting attributes: Once you have the attributes, use the XAttribute.Value property to read the attribute’s string value. Here’s an example of getting all … Read more

C# – Select a single row with Dapper

When you want to select a single row with Dapper, the simplest option is to use QuerySingleOrDefault() with a SELECT + WHERE query (and pass in the parameters / model type like usual). Here’s an example: This SQL query returns a single row from the Movies table and Dapper maps it and returns a Movie … Read more

C# – Update records with Dapper

You can update records with Dapper by using Execute() with an UPDATE statement and passing in the parameters. Here’s an example: Dapper maps the properties from the param object to the query parameters (ex: it maps year to @year). You can pass in the parameters with an anonymous type (as shown above) or by passing … Read more

C# – Delete records with Dapper

You can delete records with Dapper by using Execute() with a DELETE statement and specifying the record ID as a parameter. Here’s an example: This deletes a single record from the Movies table. Delete multiple records When you’re deleting multiple records, you can efficiently execute a single DELETE statement with a WHERE clause including all … Read more

C# – Execute a stored procedure with Dapper

You can execute stored procedures with Dapper by specifying the name, parameters, and CommandType.StoredProcedure. Let’s say you have the following stored procedure (single parameter, returns movie rows): Here’s how to execute this stored procedure with Dapper and map its results to Movie objects: Use an output parameter To get a stored procedure’s output parameter, add … Read more

SQL – Aggregate functions with GROUP BY

There are five main aggregate functions in SQL: COUNT(), SUM(), AVG(), MIN(), and MAX(). These calculate aggregate values for sets of rows. When you use them with GROUP BY, they calculate the aggregate values for each group. Let’s say you want to get movie streaming stats for each user. Here’s an example of using GROUP … Read more

SQL – Using GROUP BY with ORDER BY

GROUP BY groups rows based on one or more columns. ORDER BY sorts rows. You can use these together to sort groups. There are two options you can use for sorting groups: I’ll show examples below. At the end, I’ll talk about how SQL Server may implicitly sort groups (and why you shouldn’t depend on … Read more

How to debug .NET source code in Visual Studio

When you’re using the Visual Studio debugger to step through your code, sometimes it’s useful to be able to step into the .NET source code. I had to do this recently to figure out why my ASP.NET Core code wasn’t behaving as expected. You can enable .NET source code debugging with the following steps: Now … Read more

C# – How to change StreamWriter’s buffer size

StreamWriter buffers by writing data to an internal char array with a default size of 1024 (and a minimum size of 128). Once the buffer is full (or when you dispose the StreamWriter), it flushes the buffer to the underlying stream. You can change StreamWriter’s buffer size by passing in the bufferSize parameter. Here’s an … Read more

C# – How to make a file read-only

There are two ways to programmatically make a file read-only: Here’s an example showing both ways to make a file read-only: Using File.SetAttributes() is useful when you want to manage all of file’s attributes at once. FileAttributes is an enum flag, so you can use bitwise operations to add/remove multiple attributes at once. That’s why … Read more

C# – How to set permissions for a directory (Windows only)

When you want to set permissions for a directory (and its files/subdirectories), you can use DirectoryInfo.GetAccessControl() to get the directory’s security, add/modify/remove access control rules, and then use DirectoryInfo.SetAccessControl() to apply the changes. Access control rules are a complex combination of different settings. They control being able to do things like creating a file in … Read more

C# – How to delete a directory

The simplest way to delete a directory is by using Directory.Delete() (in System.IO). Here are a few examples: You have to specify the path of the directory to delete. This can be an absolute or relative path. You can pass in a recursive flag, which tells it to delete everything in the directory (files and … Read more

C# – How to create directories

You can use Directory.CreateDirectory() to create a directory at the specified path (absolute or relative), like this: This creates the directory if it doesn’t exist, otherwise it does nothing. That means you don’t need to check if the directory exists before calling Directory.CreateDirectory(). In this article, I’ll go into more details about using Directory.CreateDirectory(). CreateDirectory() … Read more

C# – How to update a file’s contents

There are three ways to update a file’s content: Which option you pick depends on the file’s format and size. For example, if you’re writing to an existing CSV file, you’d append new lines to the end of the file. If you’re updating a JSON file, you’d read all the JSON content, make changes, then … Read more

C# – Search for files in a directory

Use Directory.EnumerateFiles() to search for files in a directory and then loop over the file paths (and then reading the files, or whatever you want to do with the info). Here’s an example of searching for files containing “hello” in the file name: Note: Use the wildcard character * to match anything. It returns an … Read more

C# – How to read a text file

The simplest way to read a text file is by using a high-level method in the .NET File API (in System.IO), such as File.ReadAllText(). These high-level methods abstract away the details of opening a file stream, reading it with StreamReader, and closing the file. Here’s an example of reading a text file’s content into a … Read more

C# – How to create a file and write to it

There are a few ways to create a file and write to it using the .NET File API (in System.IO). The simplest way is to use high-level methods like File.WriteAllText() and File.WriteAllLines(), specifying the file path and string(s) to write to the file. Here’s an example of using these (and their async equivalents): These high-level … Read more