Category Archives: .Net Core

Using Blazor Components

Imagine that you’re writing a Blazor application – maybe it’s similar to this one. Now, imagine that you have a large chunk of HTML in your main view. You might think: I wish I was using React, then I could separate this into its own component.

You can also do this in Blazor. Here’s how.

Components in Blazor

Let’s start with moving your code. The first step is to cut your HTML and paste it into a new Razor Component:

The format of your new component, from scratch, will be:

<h3>Component Name</h3>

@code {

}

Your existing code should go beneath, or instead of:

<h3>Component Name<h3>

Parameters

The @code section allows you to put all kinds of crazy C# code in a code behind type model – so you probably don’t want to use that, except for passing parameters; for example:

@code {
    [Parameter]
    private string MyParameter { get; set; }
}

This allows you to pass a string into your component; for example (in your main view):

<MyComponent MyParameter="test" />

Complex Parameters

So far so good. But what if you need a complex type? You could, for example, pass a View Model into your component:

[Parameter]
private MyViewModel MyViewModel { get; set; }

You can pass this into the component as though it were a primitive type:

<MyComponent MyViewModel="@MyViewModel" />

This means that you can lift and shift the code with no changes.

Using External Namespaces

As with standard C#, you can access anything within the current namespace. Should you need any classes that are not in your current namespace, you can declare them at the top of the file, like this:

@using MVVMShirt

<h3>My Component</h3>

Summary

Blazor is still in its infancy, but hopefully, adding actual code to these @code sections will become as frowned upon as code-behind.

UWP using Unity and EF Core and Sqlite

If you intent to use IoC with a UWP application, there are a lot of options. Most of them come with MVVM packages, like MVVM Cross. These are excellent packages – I’ve used MVVM Cross and MVVM Light myself and can highly recommend them.

However, if you didn’t want all that baggage, how would you implement a very simple IoC system in UWP?

In this example, I’m using Unity, however, I believe this will work for any IoC container. I’m also using the IoC container to resolve a View Model – but you don’t need to use View Models (although IMHO, it makes your life so much easier.)

Secondly, I’ll be showing how to use Ef Core with your UWP app. This sounds very trivial, but there’s a bit of fiddling about to get it to work.

Entity Framework Core Set-up

In my project, I’ve separated the data access layer, but you don’t need to do that. Start by creating a data context:

public class MyDbContext : DbContext
{
    public DbSet<Data> MyData { get; set; }
 
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Data Source=mydata.db");
    }
}

You’ll need the following packages:

Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.Design
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.EntityFrameworkCore.Sqlite

You’ll also need to create a console application – why? Because you can’t use any of the EF tools with UWP! If you set your UWP app as the start-up and create your migration, you’ll get this error:

Startup project ‘SendMessage.UWP’ is a Universal Windows Platform app. This version of the Entity Framework Core Package Manager Console Tools doesn’t support this type of project.

Set the console app as startup and add the migration:

Add-Migration "InitialDbCreate"

Don’t worry about updating the DB, we’ll get the app to do that (it just can’t use the tools, but it can perform a migration.)

UWP

From a new, blank, UWP app; in app.xaml.cs:

sealed partial class App : Application
{
    public static IUnityContainer Container { get; set; } = new UnityContainer();
 
    /// <summary>
    /// Initializes the singleton application object.  This is the first line of authored code
    /// executed, and as such is the logical equivalent of main() or WinMain().
    /// </summary>
    public App()
    {
        this.InitializeComponent();
        this.Suspending += OnSuspending;
 
        using (var db = new MyDbContext())
        {
            db.Database.Migrate();
        }
        
        Container.RegisterType<MainViewModel>();
    }

We’re creating a static UnityContainer in App.Xaml.cs. Register the type (in this case a MainViewModel, but it could as easily be an interface).

The next step is resolving the interface. Unfortunately, because of the way that the UWP navigate works, Unity won’t perform constructor injection for us. A little trick around this is to create a parameterless constructor and have that call the injected constructor. It’s not quite constructor injection, but semantically it’s the same thing. Here’s the code from my MainPage.xaml.cs:

public sealed partial class MainPage : Page
{
    public MainPage() : this(App.Container.Resolve<MainViewModel>()) { }
 
    public MainPage(MainViewModel mainViewModel)
    {
        this.InitializeComponent();
 
        this.DataContext = mainViewModel;
    }
}

That’s pretty much it; you can run this, and it’ll migrate the data, and resolve the dependency.

References

https://docs.microsoft.com/en-us/ef/core/get-started/uwp/getting-started

Adding Logging to Client Side Blazor

Whilst there are some pre-built libraries for this, I seemed to be getting Mono linking errors. What finally worked for me was to install the pre-release versions of:

Install-Package Microsoft.Extensions.Logging -Version 3.0.0-preview6.19304.6
Install-Package Microsoft.Extensions.Logging.Console -Version 3.0.0-preview6.19304.6

Now, in your View Model, accept the Logger:

public MyViewModel(ILogger<MyViewModel> logger)

Then you can log as normal:

_logger.LogInformation("Hello, here's a log message");

You should now see the debug message in the F12 console.

You might be wondering why you don’t need to explicitly inject the logging capability; the reason is that:

BlazorWebAssemblyHost.CreateDefaultBuilder()            

Does that for you.

The “LegacyFrameworkPackages” parameter is not supported by the “ResolveFrameworkReferences” task

I got this error recently while updating a project that I’m working on. It had been ported from WinForm to .Net Core 3.0, and worked fine – but suddenly I started getting errors where it claimed to not know what Form was. The output showed the error:

The “LegacyFrameworkPackages” parameter is not supported by the “ResolveFrameworkReferences” task

Unbeknownst to me, MS have changed the namespace for desktop apps; where previously your csproj might look like this:

<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <LangVersion>8.0</LangVersion>
    <NullableReferenceTypes>true</NullableReferenceTypes>
    
    <AssetTargetFallback>uap10.0.18362</AssetTargetFallback>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>

It now needs to look reference the WindowsDesktop SDK:

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

Mocking IConfiguration Extension Method

In this post I wrote about the use of app settings in Asp.Net Core. One thing that I didn’t cover at the time was the fact that, as an extension library, the configuration extensions weren’t very easy to include in unit tests. Of course the intention is that you read the configuration at the start, pass through a model class and no mocking is required.

However, sometimes you’ll find yourself wanting to mock out a particular setting. Before I get into this, this post is heavily based on this article which describes the same process.

The following is a code sample using Moq:

            var configuration = new Mock<IConfiguration>();

            var configurationSection = new Mock<IConfigurationSection>();
            configurationSection.Setup(a => a.Value).Returns("testvalue");

            configuration.Setup(a => a.GetSection("TestValueKey")).Returns(configurationSection.Object);            

This will cause any call to get the app settings key “TestValueKey” to return “testvalue”. As is stated in the linked article, whilst GetValue is an extension method, GetSection is not, but is (internally) called by GetValue.

References

https://dejanstojanovic.net/aspnet/2018/november/mocking-iconfiguration-getvalue-extension-methods-in-unit-test/

Read a Document in a .Net Core Application Baked into the Project File

This isn’t a difficult thing to achieve, but it is one that frequently has me reaching for Google to get the exact syntax. By creating this post (I create all my posts on OneNote first), it’s now offline for me.

There’s more than one way to do this; I’ve covered two. All the examples here are using a CSV file from an Assets folder:

Embedded Resource

These are embedded into the compiled assembly; which means in order to change them, you would need to recompile your code. This works well for images, but less well for data files.

First, you need to add your resource to your project, and set the properties to be an embedded resource:

Because it’s embedded, copying makes no sense. To read the file:

public string GetResourceTextFile(string filename)
{
    using Stream stream = this.GetType().Assembly.
                       GetManifestResourceStream($"SalesOrder.Generate.{filename}");
    using StreamReader sr = new StreamReader(stream);                           
            
    return sr.ReadToEnd();
}

Content

This allows you to include a file within your project; however, content files are not compiled. Combined with the “Copy To Output Directory” they place files in the binary directory of your project. The advantage here is that you can change this file after compilation:

Because this just copies the file to the executing directory, it’s easier to read the file:

public string GetContentTextFile(string filename)
{
    return File.ReadAllText($"Assets/{filename}");
}

References

https://stackoverflow.com/questions/145752/what-are-the-various-build-action-settings-in-visual-studio-project-properties

My XUnit Tests won’t run in a .Net Standard 2.0 Class Library

Firstly, this isn’t a bug, or something that you might have done wrong; it’s intentional. Essentially, you can’t run a .Net Standard Library, so your tests aren’t runnable.

Okay – so I want to convert to .Net Core 3.0!

Yep – that’s exactly what you want, and it’s this easy; open up the csproj file – it’ll look like this:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

And replace it with this:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

And that’s it – your tests should now run!

Creating a Windows Service using .Net Core 2.2

Up until very recently, creating a Windows Service was the domain of the .Net Framework. However, since the release of the Windows Compatibility Pack that has all changed. In this article, we’ll create a .Net Core Windows Service from scratch.

I’m using the preview version of Visual Studio 2019 for this post. As far as I’m aware, there is absolutely no functional difference between this and VS2017; however, the initial New Project screen does look a little different.

Create the Project

There are no “New Windows Service (.Net Core)” options in Visual Studio, so we’re just going to create a console application (everything is a console application in .Net Core):

The .Net Core application can target .Net Core 2.2:

Windows Compatibility

The next step is to install the Windows Compatibility NuGet package:

Install-Package Microsoft.Windows.Compatibility

Write the Service

Let’s start with the main method:

static void Main(string[] args)
{
    using (var service = new TestSevice())
    {
        ServiceBase.Run(service);
    }
}

You’ll need to Ctrl-. ServiceBase. TestService doesn’t exist yet, so let’s create that:

internal class TestSevice : ServiceBase
{
    public TestSevice()
    {
        ServiceName = "TestService";
    }

    protected override void OnStart(string[] args)
    {
        string filename = CheckFileExists();
        File.AppendAllText(filename, $"{DateTime.Now} started.{Environment.NewLine}");
    }

    protected override void OnStop()
    {
        string filename = CheckFileExists();
        File.AppendAllText(filename, $"{DateTime.Now} stopped.{Environment.NewLine}");
    }

    private static string CheckFileExists()
    {
        string filename = @"c:\tmp\MyService.txt";
        if (!File.Exists(filename))
        {
            File.Create(filename);
        }

        return filename;
    }

}

Not exactly a complicated service, I’ll grant you.

Installing

For Framework apps, you could use InstallUtil, but if you try that on a Core app, you get an annoyingly vague error! Instead, you need to find the place where the binary has been compiled; for example:

C:\Users\pcmic\source\repos\ConsoleApp3\ConsoleApp3\bin\Debug\netcoreapp2.2

Now, launch a command prompt as admin, and type the following:

>sc create [service name] binpath=[full path to binary]

For example:

>sc create pcmtestservice binpath=C:\Users\pcmic\source\repos\ConsoleApp3\ConsoleApp3\bin\Debug\netcoreapp2.2\ConsoleApp3.exe

You should get the response:

[SC] CreateService SUCCESS

You can then either start the service from here:

>sc start pcmtestservice

Or locate it in the services utility and start it from there. You should now be able to start and stop the service and see it logging the events as you do so.

If you need to remove the service, use:

>sc delete pcmtestservice

References

https://stackoverflow.com/questions/7764088/net-console-application-as-windows-service

Short Walks – 406 Error While Creating a .Net Core Api

I’m afraid this is another of those: “What has AddMvc()” ever done for us posts.  Today, I was creating a brand new .Net Core 2.1 Api and, instead of calling AddMvc in ConfigureServices, I instead used AddMvcCore:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvcCore();

When I tried to access the API, I got a 406 error.  The fix is very simple (and one that using AddMvc() does for you:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvcCore()
            .AddJsonFormatters();

Unity Lifetime Manager

If you’ve ever used an IoC container, you’ll know that one of their benefits and burdens is that they abstract away from you the hassle of managing your dependencies. Just declare your interfaces as constructor parameters and then register those dependencies at startup, and the IoC container will propogate your class. Your registration may look like this:

    container.RegisterType<IMyService, MyService>();

But what about when your class has state? For example, what if I have this sort of thing:

    container.RegisterType<IMyData, MyData>();

Here we’re using unity, but it appears that the default behaviour for most IoC containers is transient – that is, they are created each time they are resolved. This is important, not just because you will lose data that you thought you had (in fact that’s one of the better scenarios – because it’s obvious that it’s not behaving how you expect), but because if you’re caching results of queries and so forth, you might find your application is going back for data that you thought it already had. Here’s an example, using Unity, that proves this:

static void Main(string[] args)
{
    var container = new UnityContainer();
 
    container.RegisterType<IMyService, MyService>();
    container.RegisterType<IMyData, MyData>();
 
    container.Resolve<IMyData>().Test = "testing";
    container.Resolve<IMyService>().TestFunction();
 
    Console.ReadLine();
}

The service class might look like this:

public interface IMyService
{
    void TestFunction();
}
 
public class MyService : IMyService
{
    private readonly IMyData myData;
 
    public MyService(IMyData myData)
    {
        this.myData = myData;
    }
 
    public void TestFunction()
    {
        Console.WriteLine($"Test Data: {myData.Test}");
    }
}

And the data class:

public interface IMyData
{
    string Test { get; set; }
}
public class MyData : IMyData
{
    public string Test { get; set; }
}

If you run that, you’ll see that the output is:

Test Data: 

Different IoC containers have slightly different life times – in fact, in the .Net Core IoC, you have to now explicitly register as Singleton, Transient or Scoped. In Unity, you can do something like this:

static void Main(string[] args)
{
    var container = new UnityContainer();
 
    container.RegisterType<IMyService, MyService>(new ContainerControlledLifetimeManager());
    container.RegisterType<IMyData, MyData>(new ContainerControlledLifetimeManager());
 
    container.Resolve<IMyData>().Test = "testing";
    container.Resolve<IMyService>().TestFunction();
 
    Console.ReadLine();
}