My .NET focused coding blog.

Creating a React App From Scratch

A tutorial of how to setup a React web application from scratch without using any build tools, frameworks or compilers and then gradually evolving it, step-by-step, to include support for the following:

  • JSX in-browser transformation using a standalone build of Babel
  • JSX precompilation using the Babel command-line interface
  • JavaScript/ECMAScript 6 modules (ESM)
  • Consuming packages using the Node Package Manager
  • Bundling and caching using Webpack
  • Live reloading of changes in development mode using the Webpack Development Server
  • CSS including modules and pre-processing using Sass
  • Unit testing using the React Testing Library and Jest
  • JavaScript and CSS linting using ESLint and Stylelint respectively
  • Browser backwards compatibility and polyfilling using Babel, Browserslist, Core-js and PostCSS
  • Type safety and improved tooling support using TypeScript

 
You’ll end up with something that you can use a boilerplate for any React project that doesn’t need any full-stack framework specific features. Hopefully you will also get a better understanding of some of the most commonly used components in the open-source JavaScript ecosystem and what role they play in the context of developing, building and testing a client-side rendered React web application.
Read »


Binding To a Parent Element in UWP and WinUI 3

In a WPF application, it’s easy to bind to a property of a parent element in the visual tree by setting the RelativeSource property of the binding to a RelativeSource object that specifies the type of ancestor to bind to.
Read »


Creating Azure Resources in Azure Pipelines

If you intend to build infrastructure in Azure as part of your build or release pipelines, for example using Azure Resource Management (ARM) templates, you should use a service principal to connect to your Azure subscription. In this post, I’ll show you how to use the Azure CLI to create a service principal with sufficient permissions for both creating resources and assigning roles to them, and how to setup a service connection to use it in Azure DevOps.
Read »


Custom Data Types in ASP.NET Core Web APIs

If you have issues with how Swagger generates the documentation for custom types in your ASP.NET Core Web APIs, you should read this post.
Read »


Custom Entry Points in WPF on .NET Core

To create a custom entry point for a WPF application that is created using the default template in Visual Studio and targets the .NET Framework, you can change the Build Action property of the App.xaml file from ApplicationDefinition to Page and create a class with a static Main method. That’s what I did in a previous post about handling protocol activation and redirection in packaged apps.
Read »


Single-file executables in .NET Core 3

The new PublishSingleFile option in .NET Core 3 lets you package an application into a single executable (.exe) file that contains all assemblies, resources, content files and other stuff that the app requires at runtime. This means that the output directory of an app that previously would contain a bunch of framework specific and referenced DLLs, configuration files and other content can now be reduced to contain only a single .exe file that you can simply double-click on to run the app. These single-file executables do however come with some gotchas.
Read »


Override TestRunParameters in .NET Core

Using a .runsettings file with a <TestRunParameters> element is a convenient way to keep sensitive information required by your integration tests, such as for example username and passwords, out of source control. At least if you run your tests on Windows using Visual Studio Test or the VSTest@2 task in Azure Pipelines.
Read »


Handle Protocol Activation and Redirection in Packaged Apps

An example of how to handle Uniform Resource Identifier (URI) protocol and file extension activation in a packaged WPF application.
Read »


WPF on .NET Core

Microsoft announced at Build 2018 back in May that they are bringing .NET Core to the Windows desktop applications frameworks, including both WPF and Windows Forms. This means that your client applications will be able to take advantage of the various performance improvements that have been introduced in .NET Core and that you will be able to deploy them as self-contained executables (.exes) that have no dependency upon any pre-installed version of .NET. Read »


Using Azure Pipelines to Publish your GitHub project to NuGet

Azure Pipelines is Microsoft’s new cloud-based continuous integration (CI) and continuous deployment (CD) service that lets you build and test software written in any language and deploy it to any platform. And one of the best things is that it’s completely free to use for open source projects. In this post you will learn how easy it is to set up it up to build, test and package a .NET standard project that is hosted on GitHub before deploying it to NuGet. Read »


Platform Conditional Compilation in .NET Core

.NET Core 1.0 introduced the System.Runtime.InteropServices.RuntimeInformation type that lets you dynamically detect which operating system (OS) your app currently runs on. Read »


Non-suspending UWP Desktop Apps

A traditional Windows desktop application such as a .NET or a classic Win32 application is either running or non-running. This is not true for a Universal Windows Platform (UWP) app however. These kind of apps that run across all Windows 10 devices including phones, IoT devices and even Xbox consoles, enter an additional suspended state when being minimized or switched away from. Read »


Creating a minimal UWP app using the WRL

Continuing from my last post abut how to create a minimal UWP app in C#, this one takes a closer look at what actually happens under the hood when the app interacts with the Windows Runtime (WinRT) and how you can interact with WinRT yourself in a native way without using any language projections.
Read »


A minimal UWP app

The introduction of Windows Template Studio makes it easy to set up a well-formed Universal Windows Platform (UWP) app that implements the (Model-View-View Model) MVVM design pattern according to best practices in no time.

This kind of wizard-based experiences may be appealing to some developers, but in this post I will show how you can create a minimal UWP app from scratch without using any wizards nor auto-generated code.
Read »


Implicit Data Templates in UWP

In WPF the use of implicit data templates without an x:Key makes it easy to associate a template with a particular type of object. You just set the DataType property of the DataTemplate to the corresponding type and the template is then applied automatically to all instances of that particular type.

The Universal Windows Platform (UWP) however has no concept of implicit data templates. Each DataTemplate that you define in a UWP app must have an x:Key attribute and it must be set to a string value.
Read »


Enabling ClearType on a TextBox in a transparent WPF window

If you try to improve the readability and smoothness of the text in your WPF application by simply setting the RenderOptions.ClearTypeHint attached property to System.Windows.Media.ClearTypeHint.Enabled on a TextBox in a transparent window, the text in the TextBox will still not be rendered using ClearType.

This post explains how to enable ClearType – a subpixel anti-aliasing technique for improving text smoothness – also for TextBoxes.
Read »


Disabling selection of some items in a UWP ListView

Setting the SelectionMode property of a ListView control to Multiple (Windows.UI.Xaml.Controls.ListViewSelectionMode.Multiple) in a Universal Windows Platform (UWP) app enables you to select several items by checking an automatically generated CheckBox element for each item that you want to select:

ListView
Read »


Implementing global hot keys in WPF

If you want your WPF application to be able to detect and handle key presses even when it is not currently activated or focused on the screen you could implement what is known as global hot keys in Windows.

A global, or system-wide, hot key is a key or a combination of keys that is associated with a particular window, which will receive messages whenever the user presses this key or key combination from anywhere in the system.
Read »


Enumerating collections that change in C#

If you try you remove an item from an IEnumerable while enumerating it using a foreach loop in C# you will get an InvalidOperationException saying that “Collection was modified; enumeration operation may not execute”.
Read »


Customizing the creation and initialization of content in the Modern UI for WPF

This post is about how you could customize the creation and initialization of the content of a ModernWindow in the Modern UI for WPF library by creating a custom class that implements the FirstFloor.ModernUI.Windows.IContentLoader interface.

The Modern UI for WPF is an open source project on CodePlex that contains a set of controls and styles that WPF developers can use to quickly change the appearance of a WPF desktop application into a great looking “Modern UI” app. There are some screenshots available here that demonstrate what this “Modern UI” look is all about.
Read »


Disabling or hiding the minimize, maximize or close button of a WPF window

There may be situations when you want to hide or disable the minimize, maximize, or close button of a window without having to modify the style of the window in any other way. In a Windows Forms application there are the MinimizeBox and MaximizeBox boolean properties that lets you disable the minimize and maximize button of a Form respecively or hide them both (setting both of these properties to false will effectively hide both these buttons):

public partial class Form1 : Form
{
  public Form1() {
    InitializeComponent();

    this.MinimizeBox = false;
    this.MaximizeBox = false;
  }
}

Read »


Generic type parameters and dynamic types in C#

There may be times when you need to use some type in your application that is not known until runtime. This post will explain what you need to do in order to be able to use such a dynamically loaded type from a dynamically loaded assembly as a generic type parameter when you create an instance of some generic class in your application.
Read »


Binding the DatePickerTextBox in WPF

The default control template of the built-in DatePicker control in WPF and Silverlight consists of, among some other visual elements and panels that defines its appearance and internal layout, a Calendar control that lets the user select a date by using a visual calendar and an editable DatePickerTextBox where the currently selected date is displayed.

When you bind the SelectedDate property of a DatePicker to a DateTime source property and entering a new date in the TextBox using the keyboard, the source property don’t actually get set until the TextBox loses focus. This behaviour happens even if you set the UpdateSourceTrigger property of the Binding to PropertyChanged and may cause some issues in your application.
Read »


Adding right-aligned row numbers to a DataGridRowHeader in WPF

This post provides an example of how you can right-align or centre the text in a DataGridRowHeader in a DataGrid in WPF using Visual Studio 2012 or later. It also explains how you can display the correct row numbers in the DataGridRowHeader and automatically update these as you are adding or removing items to and from the DataGrid’s ItemsSource collection dynamically.
Read »


Tabbing between items in a ListBox in WPF

This post explains what XAML changes you need to make in order to be able to navigate between elements that are the defined in the ItemsTemplate of a WPF ListBox using the TAB key on the keyboard.
Read »


Merging cells in a WPF ListView

This post provides an example of how you can merge cells that contain the same value in a ListView in WPF and make it look like the cell spans several rows as shown in the rightmost picture below.

listview11arrowlistview2

Read »


Changing the background colour of a ComboBox in WPF on Windows 8

This post explains how to change the colours of a ComboBox in a WPF application by overriding the control’s default template in XAML using Visual Studio 2012 or 2013.
Read »


Handling changes to dependency properties in the view

This post provides an example of how you can perform view related actions in response to a change to an existing dependency property, in this case the TextBlock.Text property, and how you can determine which action to take based on the difference between the old value and current value of this dependency property.
Read »


Using the event aggregator pattern to communicate between view models

If you are developing a composite user interface that contains several parts that need to be synchronized with each other, you need to be able to communicate between these different parts of your application.

This can be done using ordinary .NET events or by keeping a direct reference to each subscriber from each publisher class and simply call a method on the subscriber class from the publisher class once you want to publish some information. However, using this approach will result in a tight coupling between publishers and subscribers that makes the application harder to maintain. It could potentially also lead to memory leaks if a publisher of an event lives longer than a subscriber and you forget to, or don’t know when to, unsubscribe from an event.
Read »


Using behaviours to bind to read-only properties in MVVM

If you have ever tried to for example bind the SelectedItem property of a TreeView control or the SelectedDates property of a Calendar control to some source property of a view model, you know that these properties are read-only, i.e. they don’t have a publicly accessible setter.

This post provides two different code samples on how you can use something called attached behaviours to be able to synchronize a source property of a view model class with a custom dependency property that acts as replacement for an existing read-only dependency property of some user interface control.
Read »


How to programmatically select and focus a row or cell in a DataGrid in WPF

You may have tried to select a row in a DataGrid in WPF programmatically by setting its SelectedItem property or SelectedIndex property only to find out that doing this doesn’t result in the exact same behaviour as when you select a row by clicking on it with the mouse.

Setting any of these properties in code does in fact select the row and give it some kind of focus but the behaviour is slightly different compared to when clicking on it. For example, the row doesn’t get highlighted the same way and if you try to use the arrow keys of the keyboard to navigate between the rows after you have set any of the mentioned properties in code the row will lose its focus.

It is however possible to select and focus a row in code and get the same behaviour as when using the mouse by accessing the visual user interface elements of the DataGrid control and calling the UIElement.Focus() method on a particular System.Windows.Controls.DataGridCell object as described in this post. You can also select an individual cell using almost the same approach.
Read »


Displaying and editing many-to-many relational data in a WPF DataGrid

This post provides an example of how you could display and let the user edit many-to-many relational data from Entity Framwork in a dynamic and data-bound DataGrid control in WPF by programmatically adding a DataGridCheckBoxColumn to the grid for every entity object that represents a row in the “child” table of the relationship between the two tables:

Dynamic DataGrid
Read »


How to export data from a DataGrid in WPF

The DataGrid control in WPF provides a flexible way to display, sort, group and filter tabular data. A common requirement is the ability to export this data to some physical file that can be imported into Microsoft Excel or some similar software for further processing.

This post provides an example of how you could create a .csv file out of a data-bound collection of objects of any type by using reflection and extending the functionality of the System.Windows.Controls.DataGrid control by implementing an extension method.
Read »


Data validation in WPF

A common requirement for any user interface application that accepts user input is to validate the entered information to ensure that it has the expected format and type for the back-end to be able to accept and persist it. This post is about how data validation works in WPF and the different validation options there are available including implementing custom ValidationRules and using the IDataErrorInfo interface and the INotifyErrorDataError interface that was introduced in the .NET Framework 4.5. It also contains an example that shows how you can validate data using data annotations.
Read »


How to bind a three-state CheckBox to some other CheckBoxes in a data-bound ItemsControl in WPF using MVVM

This post provides an example on how you can use a three-state Checkbox control to set the IsChecked property of several other related CheckBoxes in a data-bound ItemsControl, or any other control that derives from the ItemsControl such as the DataGrid, ListView or TreeView controls, in WPF using the MVVM (Model-View-ViewModel) pattern.
Read »


Handling events in an MVVM WPF application

In a WPF application that uses the MVVM (Model-View-ViewModel) design pattern, the view model is the component that is responsible for handling the application’s presentation logic and state. This means that the view’s code-behind file should contain no code to handle events that are raised from any user interface (UI) element such as a Button or a ComboBox nor should it contain any domain specific logic.

Ideally, the code-behind of a view – typically a Window or a UserControl – contains only a constructor that calls the InitializeComponent method and perhaps some additional code to control or interact with the view layer that is difficult or inefficient to express in XAML, e.g. complex animations.
Read »


Cascading ComboBoxes in WPF using MVVM

When a user is selecting an item from a cascading ComboBox, another ComboBox gets automatically populated with items based on the selection in the first one. This post is about how you can implement this behaviour in a WPF application using the MVVM (Model-View-ViewModel) pattern.
Read »


Implementing a generic data access layer using Entity Framework

This post is about how you can develop a generic data access layer (DAL) with full CRUD (Create, Read, Update and Delete) support using Entity Framework 5 with plain old CLR objects (POCOs) and short-lived contexts in a disconnected and stateless N-tier application.

Entity Framework (EF) is Microsoft’s recommended data access technology when building new .NET applications. It is an object-relational mapping framework (ORM) that enables developers to work with relational data using domain-specific objects without having to write code to access data from a database.
Read »


Implement a MVVM loading dialog in WPF

Continuing from my last post about how to display dialogs to the user in a MVVM WPF application using Prism without breaking the pattern, this one is about how you can extend the built-in functionality to implement a loading dialog to be shown to the user while running a background operation.
Read »


Implement a confirmation dialog in WPF using MVVM and Prism

If you are serious about implementing the MVVM pattern in your UI applications you should be well aware of the fact that any call you make to System.Windows.MessageBox.Show from your view models violates this pattern and the separation of concerns that exists between the application’s logic and its presentation.

By honoring the MVVM design pattern and its principles your application is likely to require less effort when you make changes in one area or another as the presentation layer (the view), the presentation logic layer (the view model) and the business model layer (model) are decoupled from each other. Other benefits include testability and the fact that designers and developers can work concurrently and independently.
Read »


Custom authorization in WPF

This post provides a code sample on how to implement your own custom authentication and authorization in a WPF application by implementing classes that derive from the IIdentity and IPrincipal interfaces and overriding the application thread’s default identity.
Read »


How to create a custom window in WPF

This introductory post will provide a walkthrough on how to create your own custom looking window control with resize, drag, minimize, restore and close functionality and how to use it in your WPF applications.
Read »