One of the nifty new templates for .NET Core will spit out a console app that runs a "Hosted" worker service. That is, code that runs in the background and takes advantage of all the new configuration and dependency injection APIs that were originally introduced along with ASP.NET Core. This is all documented over on docs.microsoft.com.

However, if there is a need for it, it is still possible to setup a .NET Framework application that takes advantage of all of the same APIs and hosting model. (Note: the full working sample for this is posted on my Github repo).

The first thing to do is, to create a regular ol' .NET Framework Console app. Then add in the following Nugets (I also like to go ahead and convert my project to use Package References and tidy things up a bit):

Install-Package Microsoft.Extensions.Configuration.UserSecrets

Install-Package Microsoft.Extensions.Hosting

Install-Package Microsoft.Extensions.Hosting.WindowsServices

The WindowsService package is optional, but if you're planning on running your worker service as a Windows Service then you'll have to bring that in as well.

Next, let's go ahead an create a Worker class. The example doesn't do anything besides print a message every time it runs, but it also demonstrates that we'll be able to have the hosting service inject both an ILogger and an IConfiguration instance.

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly int _timeout;

    public Worker(ILogger<Worker> logger, IConfiguration config)
    {
        _logger = logger;
        _timeout = config.GetValue("WorkerTimeout", 5000);
    }

    protected async override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while(!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Executing Worker at {time}", DateTimeOffset.Now);

            await Task.Delay(_timeout, stoppingToken);
        }
    }
}

Next, wire up the Host Builder in Program.cs. The important part is the call to AddHostedService<Worker> which is what wires up service host to our Worker class. 

class Program
{
    static void Main(string[] args) =>
        CreateHostBuilder(args).Build().Run();

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(configBuilder => configBuilder.AddJsonFile("appsettings.json"))
            .UseWindowsService()
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
            });
}

There are two other optional pieces that I added as examples.

  • The call to ConfigureAppConfiguration is used to load config settings from appsettings.json
  • The call to .UseWindowsService() - again, if you're not going to host as a Windows Service, then that call can be removed.

And that's all there is to it! Of course, you can add in other extensions supported by the Hosting API's, e.g. other types of configuration providers, secrets, different logging etc. 

In my previous post, I briefly described the tools that I use on Windows 10 for managing cryptocurrency (Litecoin specifically) and the steps needed to get going. In this post I’ll go into a bit more detail on how to actually complete the steps. Please refer to the end of this post for a list links for reference.

The first step will be to download both the KeePass and Electrum-LTC programs. While optional, I highly recommend taking the time to verify the programs as well and establish the habit going forward. While not completely bullet proof (you’ll at least have to trust the site that you download the verification keys from), it will prevent you from accidentally using a version of the program that has been altered by a third party.

To perform the verification of the downloaded programs, I use the GPG tooling in Linux. Alternatively, you could install Gpg4win; however, since Windows 10 has new support for true Linux distributions why not go directly to the source? To do so, you will need to first enable the Windows Subsystem for Linux (see the link at the end of this document or search how to in your favorite search engine.) Once WSL is enabled, visit the Windows Store and pick a distribution of Linux (I use Ubuntu, but there is Suse and others.) Once installed, launch the Bash command line shell.

Optional Step – Mounting a Removable Drive in WSL

If you are doing everything on an internal hard drive, then this next step can be skipped. In my case, I have a MicroSD card slotted into my Surface Pro and encrypted with BitLocker. WSL does not automatically mount a removal drive so this needs to be done manually. For example, if the MicroSD is mounted to drive letter D: in Windows then the following commands need to be run the mount it in WSL.

$sudo mkdir /mnt/d

Then, to mount the drive (and again on subsequent Bash sessions):

$ sudo mount -t drvfs D: /mnt/d

When I’m finished, I can unmount it with.

$ sudo umount /mnt/d

Download and Verify KeePass

I will be keeping all of my downloaded files in D:\software (so in WSL that will be /mnt/d/software)

Start by downloading the latest version of KeePass. I prefer the Portable version so as to keep my system cleaner (it simply runs out of a folder and does not need to modify the Windows Registry etc.) Next, from the signatures page, download the PGP .asc file corresponding to the version of the program that you downloaded and place it in the same folder as the downloaded program file. For example, if you downloaded the portable version KeePass-2.37.zip then also download KeePass-2.37.zip.asc. The other piece of information that you need off of the signatures page is the Key ID of the program signer (see screen shot below).

KeePassASC

Over in the Bash window, run the following command (make sure you grab the actual Key ID off of the page when you run it)

$ gpg --keyserver pool.sks-keyservers.net --recv-keys <keyIDvalue>

Below is an example with output.

image

Once the key has been imported to your local “key ring,” the KeePass .zip file can be verified with the .asc file by running the gpg --verify command. See the example below.

image

The main thing that you are looking for here is the “Good signature” message, and the warning message here can be ignored. You can also compare the key fingerprint to the one that was displayed on the website where you downloaded the .asc file from.

Download and Verify Electrum-LTC

The good news is that now that you’ve verified KeePass, the process for Electrum-LTC is nearly identical. Head over to the Electrum-LTC site and first download the .exe (once again, I recommend the portable version) and the corresponding .asc file. Also, visit the link to the “Pooler” signature. I’ve highlighted all three items for the portable version in the image below.

image

Import the Pooler public key (example below) and then run the gpg --verify command on the Electrum files.

image

Fwew! That was a bit of work, but now with both the programs verified we are finally ready to setup our Litecoin wallet. However, I am going to end this post here and will save that for the next one.

Reference Links

While I am not going to claim any expertise in cryptocurrency, I have spent a bit of time dabbling in it in order to gain a working knowledge as well as keep a bit on hand as an alternative investment. There are many options out there for acquiring cryptocurrencies and storing or spending them on a variety of computer platforms. I am going to document one option that I use on Windows and the steps and tools needed to make it work. I will focus specifically on Litecoin here, but working with Bitcoin would be nearly identical. This Part 1 post will be fairly brief – I’ll describe the list of tools and steps that I use and then in a subsequent post (or posts) I will go into a little more detail on how to complete the steps.  Some of the steps here are optional and really depend on how careful you want to be. I’ll label the optional steps, but I think they are good habits to follow anyway.

First off, why go through all this trouble in the first place when one could simply buy some coins on Coinbase or another online wallet and leave them there? Also, why Windows?? Well, to answer the first question, ideally you should keep as much control over your money as you can. Once your local wallet is setup, it’s trivial to transfer your coins to it. There’s always the risk that an online site could be infiltrated by hackers and your money taken out. Obviously, there’s also risks to storing it yourself, but you are also a much smaller target to go after and you have more control (and at the end of the day, that’s what cryptocurrency is all about, having control over your money.) As for the use of Windows, the simple answer is that I am a long-time Windows user who enjoys the OS. I spend a lot of time on my Surface Pro so that is the environment in which I am most comfortable getting setup to work with cryptocurrency. There are a lot of mobile apps and wallets out there that are fairly turnkey, but setting up a wallet on a PC is a bit more involved. I am not sure how much documentation is out there on how to get started on Windows so I thought that it might be helpful to record a few notes on my blog.

Here are the list of tools that I use:

  • Windows 10 Pro (Windows 10 Home can be used for most of this, but I recommend the Pro version mainly for the next point which is…)
  • BitLocker – this is optional, but BitLocker allows drives to be encrypted. This includes SD cards, so that, for example, I can encrypt a MicroSD card plugged into my Surface and then remove it to store offline.
  • Windows Subsystem for Linux (WSL) – I use the GPG (GNU Privacy Guard) tools to verify file downloads – again, an optional step but recommended. There are also other ways to do this, but this is the methodology that I went with.
  • KeePass – a password manager – I use this to store the local wallet password and my wallet seed.
  • Electrum-LTC – Litecoin wallet (there’s also an Electrum version for Bitcoin)
  • Coinbase.com – very easy to use site for buying Bitcoin, Litecoin, or Ethereum

The basic steps to getting setup will be:

  • Download and verify KeePass and Electrum-LTC
  • Setup both of the above tools
  • Receive and send some Litecoin

That’s it for this post. If any of this sounds interesting to you, then stick around for another write-up where I’ll have details about each of the steps above.

A few weeks ago I watched an episode of the ASP.NET Community Standup that was recorded with Sebastien Ros where they covered updates around the Orchard Core CMS product. While Orchard Core appears to be coming along nicely, one of the demos in particular caught my eye, in that it has support for Liquid templates built in. Years ago, I had utilized Liquid when doing some work with Shopify and I remembered coming away fairly impressed at how easy it was to use (here’s an intro to Liquid on the Shopify blog.) The demo piqued my interest to see how Orchard Core supported Liquid, and to see how hard it might be to add similar support into something that I might build myself. Fortunately, Orchard Core is all open source, so it was easy enough to track down that it is using a package named Fluid.Core that is maintained by Sebastien Ros.

The steps getting going are pretty straight forward. (I will show a few samples below from a little proof of concept app that I built called FluidTagHelper, so check that out if you want to just browse some code instead.)

First, obviously you need to add the Fluid package. Currently, Fluid.Core is in prerelease so…

dotnet add package Fluid.Core --version 1.0.0-beta-9399

Then, before you can render a template, you need to white list the Types that will be used in the template. Think of these as similar to your View Model types. The easiest way is to register an entire class at startup (but you can also define specific members). For example, in my TagHelper demo I registered a Fruit type during Startup.

TemplateContext.GlobalMemberAccessStrategy.Register<Fruit>();

Now, in a view you can take a template string and some data, and call FluidTemplate.TryParse and then construct a TemplateContext to render the data with. In my demo app, this is split between the Index.cshtml.cs and the FluidTagHelper.cs.

string fluidTemplate = @"<ul class=""list-group"">
{% for fruit in model %}
<li class=""list-group-item"">{{fruit.Name}} - {{fruit.Weight}} lbs</li>
{% endfor %}
</ul>";

Fruit[] fluidModel = new[]
{
    new Fruit()
    {
        Name = "Banana",
        Color = "Yellow",
        Weight = 0.75m
    },
    new Fruit()
    {
        Name = "Orange",
        Color = "Orange",
        Weight = 1.0m
    }
};

if (FluidTemplate.TryParse(fluidTemplate, out var template))
{
    var templateContext = new TemplateContext();
    templateContext.SetValue("model", fluidModel);
    string renderedTemplate = template.Render(templateContext);
}

And that’s it in a nutshell! I think that Liquid templating could be useful in any scenario where you may want a (fairly technical) end user to be able to customize application views, or even for an application developer who may want to customize various displays without having to redeploy new code. Fluid.Core looks to be a nice option that is coming along in the ASP.NET Core space.