Modernize WinForms and WPF apps with BlazorWebView

You may have heard about Blazor Desktop, Blazor Hybrid, or maybe Blazor Native. All of them are the same, just different names. What it really is, is the BlazorWebView. A control for .NET MAUI (and Xamarin.Forms), WinForms and WPF.

BlazorWebView can be seen as the third option about how you will host your Blazor app. If you are a Blazor web developer you probably already know about Blazor Server and Blazor WebAssembly. With BlazorWebView you will host Blazor inside of your native app, in the same process as the rest of the app.

So why is this an interesting thing for WPF or WinForms developers?

  • You can reuse your Blazor components from your web projects.
  • You can use Blazor components from the community or third-party vendors, like Progress Telerik and Syncfusion.
  • You can develop your app with web technology and have full native access (to what the platform offers).
  • You can take your website and add it to a native shell and improve the experience with some native features.

Modernize your app

Because you can use BlazorWebView as all other controls, you can use it wherever you want in your app. This means that you can use BlazorWebView to modernize your apps. For example, if you have an old WinForms app that you maybe want to replace with a website or you want to add new features to it that you already have on your website you can easily take your Blazor component and add them inside of your app. Instead of developing that feature again for the app, you are reusing what you already have developed. In the long run, you maybe will replace the whole app with a website but with this strategy you can do it step by step instead. Or you will keep the app, but with just web UI, but you have specified the website up with some native stuff.

Combine native and web UI

A common strategy with BlazorWebView will be to keep some parts of the app native, navigation for example. In a WinForms or a WPF app, you probably want to have the menu native, but the actual content can be in a BlazorWebView and you can share it with your websites or with a .NET MAUI app for, iOS, Android, and/or MacOS. If you spcify a control that are a Router, you can also navigate inside of your BlazorWebView.

How to use BlazorWebView

To use BlazorWebView you need to install the platform-specific Nuget package to your app project. In this repository on GitHub you can see how I am using Blazor WebView in a project I am working on, https://github.com/dhindrik/CodeBlogger.

You have to create a wwwroot folder in your project and that need to contain an HTML file and you need to include the following script:

<script src="_framework/blazor.webview.js"></script>

Note, the script tag should not include autostart="true". That is only for .NET MAUI apps.

The HTML file needs to contain a container where the component should be inserted. For example, you can insert a div with an id set to “app”. You will point to that selector from your code.

<div id="app"></div>

CSS file or other content should be placed inside of the wwwroot folder.

In the project file you should change the top line from:

<Project Sdk="Microsoft.NET.Sdk">

to

<Project Sdk="Microsoft.NET.Sdk.Razor">

If you not are changing that, it will not work to have razor components inside of that project.

In the project file, you also have to add this rows to handle the web content.

<ItemGroup>
    <Content Update="wwwroot\**">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
</ItemGroup>

WinForms

The NuGet package you need to install is Microsoft.AspNetCore.Components.WebView.WindowsForms

Open the code view for the form where you want to add the BlazorWebView to. You need to create a ServiceCollection because WinForms will not have that in the startup as a .NET MAUI app. If you are using BlazorWebView in multiple places in your app you can of course reuse the same ServiceCollection between them. You need to add the following using:

using Microsoft.AspNetCore.Components.WebView.WindowsForms;

When you have done that you can call AddBlazorWebView() to add it to the ServiceCollection.

After that, you can create the BlazorWebView and add the component you want to show to it. For the HostPage property you should specify the path to the HTML file.

The last step is to add the BlazorWebView to the view, in this case to the root control of the view. But you can add it to which control supports subcontrols that you want.

var services = new ServiceCollection();
services.AddBlazorWebView();

var blazorWebView = new BlazorWebView()
{
    Dock = DockStyle.Fill,
    HostPage = @"wwwroot\index.html",
    Services = services.BuildServiceProvider(),
};

blazorWebView.RootComponents.Add<Editor>("#app");

Controls.Add(blazorWebView);

WPF

The NuGet package you need to install is Microsoft.AspNetCore.Components.WebView.Wpf

To add a BlazorWebView to a WPF is very similar to how it works for WinForms, but you will do it from "the code behind" and you need to create an instance of the RootComponent object and set the ComponentType property to the type of component you want to use.

The reason I don't do this in the XAML is that we need to pass the ServiceCollection. It is doable in XAML too, if you prefer it, but I think this way is more simple.

var services = new ServiceCollection();
        services.AddBlazorWebView();

        services.AddSingleton<IPostService, PostService>();
        var blazorWebView = new BlazorWebView()
        {
            HostPage = @"wwwroot\index.html",
            Services = services.BuildServiceProvider(),

        };

        blazorWebView.RootComponents.Add(new RootComponent()
        { 
            ComponentType = typeof(Editor),
            Selector = "#app"
        });

        Content = blazorWebView;

Review of Apple Macbook Pro M1

It is now about two weeks since I got my Apple Macbook Pro M1 delivered. It is the one with 16 GB of RAM and 2 TB SSD. Delivery time was quite long, I ordered it at the beginning of December. But now when I have used it as my primary machine for a while it is time for a review.

I primarily use it for .NET development including app development using Xamarin and backend development using .NET Core 3 and .NET 5. I also, do some development using Blazor from time to time.

Overall

To overall impression is that it is a really fast machine. macOS and applications that are optimized for the machine are really fast. Applications that not are optimized are faster or at least not slower than on my old MacBook Pro from 2017.

What is great is that it never became hot, not so far, it can be a little bit warm, but I have never heard the fan. On my old MacBook, the fan sounded like a jet plane.

As always with a Macbook it is very solid. I like that they have switched back to the old keyboard. The only downside is that it only has two thunderbolt/USB-ports. So you probably need a USB-hub. I have a display connected with USB-C that has USB-ports and it also powers the computer.

Xamarin development

As we could expect, iOS development is not an issue, because Apple has of course optimized XCode for the new M1 Macs. And Visual Studio for Mac runs good with Rosetta 2, But what about Android? The development worked well, but to run my app on an emulator I had to go and download a preview version of the emulator for the new Macs. But the emulator works really well and it is really fast. But right now (preview 3) you cannot run Chrome on it. You can download it from here. https://github.com/google/android-emulator-m1-preview

Backend development

To do backend development with .NET Core 3+ and .NET I had to install the beta of Big Sur 11.2. Before that, it crashed every time that I tried to debug an application. But with the beta, it is working like a charm.

For Visual Studio Code there is an insider build that is compiled for ARM. That version is really good, it is much faster than the "old" Visual Studio Code.

Docker

Docker has a preview for M1, https://docs.docker.com/docker-for-mac/apple-m1/. It works great, there are some problems with images that not are for ARM. I tried with an SQL Server 2019 image for example and that one did not work. https://github.com/docker/for-mac/issues/5170#issuecomment-767803717. But a colleague found an image that I can use for SQL-server that had enough features for me, mcr.microsoft.com/azure-sql-edge. I also run a container for MongoDB without any issues.

Streaming and media

I have tried Streamlabs OBS and there are no problems running it with Rosetta 2. It feels more smooth compared to running it on my old Mac.

For editing videos, I have tried iMovie, an app that Apple has optimized for M1. It works really great, I imported and 6-hour long video with a size of 13 GB and it worked like I imported just a short video.

I also have tried Adobe Photoshop without any issues.

Other applications

Microsoft Office including Word, Excel, Outlook, and Teams, etc. runs fine. But I could not get OneDrive sync working. The same with Google Drive sync.

Running Windows

You cannot run Bootcamp on the M1 Macs. But Parallels Desktop has a technical preview, https://www.parallels.com/blogs/parallels-desktop-apple-silicon-mac/, that are able to run Windows ARM. The problem is that Windows ARM images can be hard to find. But after I asked on Twitter I got an answer that there are insider builds that is available for download. So I did and Windows runs much better on Parallels now than compared with the x64 version on my old Macbook. I also was able to run Visual Studio (x86) on it and it works ok, it is as good as running it on Parallels on my old Macbook.

Summary

MacBook Pro M1 is a really good and fast computer, there are some small issues, but if you should buy a new Mac now, I recommend you to buy an M1, Intel Mac feels old!

.NET 5

Vi är på episod 5, vad passar bättre än att då prata om .NET 5. Microsoft jobbar mot ett .NET efter att .NET började bli spretigt, med .NET Framework, Mono och .NET Core. Daniel och Johan pratar om statusen på ihopslagningen och vad som är nytt .NET 5.

https://devblogs.microsoft.com/dotnet/announcing-net-5-0-preview-8/
https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers

Xamarin.Forms Projects – Second Edition

The second edition of Xamarin.Forms Projects is now published. You can buy it from Packt or Amazon. It will also be available in other book stores.

More Information

An example-driven guide to help you build native cross-platform mobile apps using Xamarin, .NET Core 3, and Visual Studio 2019.

Set up Xamarin.Forms for building native apps with code-sharing capabilities

Understand the core aspects of developing a mobile app such as its layout, UX, and rendering

Use custom renderers to gain platform-specific access

Discover how to create custom layouts for your apps with Xamarin.Forms Shell

Use Azure SignalR for implementing serverless services in your Xamarin apps

Create an augmented reality (AR) game for Android and iOS using ARCore and ARKit, respectively

Build and train machine learning models using CoreML, TensorFlow, and Azure Cognitive Services

Xamarin.Forms is a lightweight cross-platform development toolkit for building apps with a rich user interface. Improved and updated to cover the latest features of Xamarin.Forms, this second edition covers CollectionView and Shell, along with interesting concepts such as augmented reality and machine learning.

Starting with an introduction to Xamarin and how it works, this book shares tips for choosing the type of development environment you should strive for when planning cross-platform mobile apps. You’ll build your first Xamarin.Forms app and learn how to use Shell to implement the app architecture. The book gradually increases the level of complexity of the projects, guiding you through creating apps ranging from a location tracker and weather map to an AR game and face recognition. As you advance, the book will take you through modern mobile development frameworks such as SQLite, .NET Core Mono, ARKit, and ARCore. You’ll be able to customize your apps for both Android and iOS platforms to achieve native-like performance and speed. The book is filled with engaging examples, so you can grasp essential concepts by writing code instead of reading through endless theory.

By the end of this book, you’ll be ready to develop your own native apps with Xamarin.Forms and its associated technologies such as .NET Core, Visual Studio 2019, and C#.

Develop mobile apps, AR games, and chatbots of varying complexity with the help of real-world examples

Explore the important features of Xamarin.Forms 4 such as Shell, CollectionView, and CarouselView

Get to grips with advanced concepts such as AR and VR and machine learning for mobile development

Poco2Js

We have started to develop a web version of WordRoom. We will use web socket to communicate with our backend. All messages (POCOs) that is used in our versions of WordRoom is written in C#. We don't want to rewrite all messages to JavaScript for use with web sockets. To solve this problem we created a tool called "Poco2Js", it is available at CodePlex, https://poco2js.codeplex.com/. What it does is that it convert .NET POCOs to JavaScript classes. You just choose an assembly and all types in the assembly will be converted to JavaScript classes.