C Sharp

Current time abstraction coming to .NET

Oliver Brown
— This upcoming video may not be available to view yet.

It is often necessary in computer systems to get the current date and time. .NET has had a straightforward way to do that since its inception. What it hasn’t had is a built-in way to customize the behavior, particularly for mocking during automated tests.

Quite why this situation has persisted for so long is a bit of mystery. The importance of automated tests has only risen over time and questions about how to deal with this crop up quite frequently. The general solution is to provide an abstraction that you can inject and mock easily.

The popular date and time library Noda Time includes IClock, and any developers are often directed to use Noda Time for anything making use of anything but the simplest of time-based logic. But it is still odd there is nothing built-in, especially considering there is an existing private implementation in .NET, as well as several in ASP.NET.

Well .NET 8 will finally be getting System.TimeProvider:

namespace System
{
    /// <summary>Provides an abstraction for time. </summary>
    public abstract class TimeProvider
    {
        protected TimeProvider();
        public static TimeProvider System { get; }
        public static TimeProvider FromLocalTimeZone(TimeZoneInfo timeZone);
        public abstract DateTimeOffset UtcNow { get; }
        public DateTimeOffset LocalNow { get; }
        public abstract TimeZoneInfo LocalTimeZone { get; }
        public abstract long GetTimestamp();
        public abstract long TimestampFrequency { get; }
        public TimeSpan GetElapsedTime(long startingTimestamp, long endingTimestamp);
        public abstract ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period);
    }
}

Here is the original GitHub issue and the pull request implementing it.

As well as providing a mockable abstraction to get the current time (including a default implementation providing the system time), it also adds supports to a bunch of other APIs to use a specified instance instead including Task and Timer.

And, best of all, despite my earlier claim that this is a .NET 8 feature, this will also be made available as a package targeting .NET Standard 2.0, so it can be used on .NET Framework and other targets.

Blazor Numbers Game

Oliver Brown
— This upcoming video may not be available to view yet.

Over the weekend I was playing around with Blazor and created a little number game based on part of a popular British TV show.

In the future this may expand in functionality as part of my exploration into Blazor.

You can try the number game full screen.

Blazor custom elements

Oliver Brown
— This upcoming video may not be available to view yet.

There is now a preview package for Blazor that allows creating custom elements.

Custom elements are part of the Web Components standards and are intended to be a way of defining tags that can be consumed in HTML and interoperate with each other.

The docs mostly focus on using them with Angular or React, but that isn’t why they are interesting to me.

The site for Tic-tac-toe Collection includes pages that show some information about specific game mode (for example four-player Tic-tac-toe misère rumble).

That content is rendered as a custom element (in this case <ttt-settings short-code="T_D4_S6x6_W3_T0_P0_M1_O1_F0"></ttt-settings>). Since the site is statically generated with no frontend framework, I wrote the element in vanilla JavaScript. Blazor support for custom elements means I could rewrite that component in C#.

Accessing the UI in Xamarin.iOS

Oliver Brown
— This upcoming video may not be available to view yet.

An interesting discussion happened recently, triggered by a code review of (something like) the following C#:

public class ProductViewController
{
    private UIView _detailsView { get; set; }
    private ProductViewModel _viewModel { get; set; }

    private void Process()
    {
        if (_viewModel.ProcessDetails)
        {
            InvokeOnMainThread(() =>
            {
                if (_detailsView != null)
                {
                    UpdateDetailsView();
                }
            });
        }
    }
}

One of the reviewers suggested moving the second if outside the call to InvokeOnMainThread (and then combining it with the other if).

The theory was that it would more efficient to check if we need to be on the main thread before we do it, instead of doing the check on the main thread and finding out we have nothing to do.

The original author pushed back saying you can’t access _detailsView off the main thread since you would get an exception.

On the surface this sounds reasonable - everyone knows you can only access UIKit objects on the main thread. But it naturally leads to the question: what does “accessing a UIKit object” actually mean?

So I wrote a quick sample that intentionally tries to do lots of UIKit manipulation on background threads in various ways:

The tests

Quick refresher. The View property of a newly constructed UIViewController is not populated until it is first accessed. Some of the tests below refer to accessing this property either before or after it is created. By default properties declared in C# will not be visible to any native iOS code. They can be made visible by adding the [Export] attribute.

  • Create a UIViewController.
  • Create a UIView.
  • Create a UIColor.
  • Check if a view controller’s View property is equal to null.
  • Check if a view controller’s View property is null using pattern matching.
  • Check if a view controller’s IsViewLoaded property is equal to true.
  • Check if a view controller’s View property is equal to null after previously creating View on the main thread.
  • Check if a view controller’s View property is null using pattern matching after previously creating View on the main thread.
  • Check if a view controller’s IsViewLoaded property is equal to true after previously creating View on the main thread.
  • Check if a new UIView property, that is not exported is equal to null.
  • Check if a new UIView property, that is not exported is null using pattern matching.
  • Check if a new UIView property, that is exported is equal to null.
  • Check if a new UIView property, that is exported is null using pattern matching.
  • Check if a view controller’s NavigationController property is equal to null.
  • Check if a view controller’s NavigationController property is null using pattern matching.
  • Set a new UIView property, that is not exported, with a view created on the main thread.
  • Set a new UIView property, that is exported, with a view created on the main thread.

Results

Test Result
Create UIViewController Exception
Create UIView Exception
Create UIColor OK
Check if View is equal to null Exception
Check if View is null pattern Exception
Check if View is loaded Exception
Check if View is equal to null after creating View Exception
Check if View is null pattern after creating View Exception
Check if View is loaded after creating View Exception
Check if non-exported view is equal to null OK
Check if non-exported view is null pattern OK
Check if exported view is equal to null OK
Check if exported view is null pattern OK
Check if NavigationController is equal to null Exception
Check if NavigationController is null pattern Exception
Set non-exported view OK
Set exported view OK

Summary

This is by no means exhaustive, but it seems in general, acessing properties declared natively in iOS will throw an exception whereas accessing properties you have declared yourself will be fine. I had a suspicion that an exported view might behave the same as a native property, but apparently not.

The code for this test is available on GitHub.

Silverlight is pretty cool

Oliver Brown
— This upcoming video may not be available to view yet.

More than two months since my last post. Which means I suddenly have a lot to say. Beware, rambling may follow… Nearly five months ago I claimed to be making “rapid progress with language learning”. Well obviously not rapid enough to actually reveal anything. Well that might be at an end soon.

One of the problems of writing the app using things like LINQ means most people will have other things to install to use the app (.NET 3.5 specifically - and possibly .NET 3.0 for non Vista users) and even then it’s limited to Windows users as Mono support for Windows Presentation Foundation will be a long way off (if they do it all). Since Silverlight 2.0 is supposed to be really cool and now supports a big chunk of the widgets from standard WPF (and has has quickly developing Moonlight support), why not write the app in that? So that’s what I’ve been doing. And it was a lot easier than I thought.

The first piece of easiness I found was that I only had to make like three changes to my non-UI code to make it compile as a Silverlight DLL. Unfortunately I can’t persuade Visual Studio to compile it as a Silverlight DLL and a normal DLL in one go, so I’ve currently got the same code added as two different projects and I copy the code between them (not ideal). The only real work I had to do was reimplement my data provider. When I started, I cunningly made sure that all resources (lessons, media, user progress) were grabbed from a data class. I wrote a new class that fetches it from a RESTful server (more on that in another post). So hopefully, a nice Silverlight version of the app will be public soon.

About Silverlight

For those that don’t know, Silverlight is Microsoft’s answer to Flash. Apparently. I’m not sure if it’s that a good analogy really. Silverlight 1.0 basically gave you access to a nice environment to draw things in the browser and then manipulate it with Javascript. Or something. To be honest I didn’t really care about version 1.0 since writing complicated things in Javascript doesn’t sound like fun. Silverlight 2.0 (formerly Silverlight 1.1) on the other hand gives you that same environment but the ability to manipulate the things with compiled .NET assemblies written in any CLR language and comes with implementations of a lot of the widgets in the WPF.

Google Docs rule - if you use them right

Oliver Brown
— This upcoming video may not be available to view yet.

I’ve been vaguely using Google Docs (specifically Spreadsheets) since it came out but never to do anything actually important. Most of the time I just had a list I need sorting, or if I was feeling sophisticated I’d use it to decide on what was best value for money (how much £/GB a range of hard drives were for instance). Recently I started using it to plan lessons for the language learning app. The ability to use it from work (or any other computer I might be on - including viewing it on my Nokia 770) was useful, but in the end I was only really writing a list with it.

Until now. I now have a nifty little C# app that generates modules directly from a Google Spreadsheet which is definitely a Good Thing. I’ve been thinking of writing an app for module editing for a while since writing them by hand is tiresome and error prone. Google Spreadsheets does half the work for me by providing the user interface for generating a table and then provides access as simple XML. Which brings me to the matter of actually accessing the data. Google provide a client library in C# for accessing quite a lot of their API. I tried using it but found it a little confusing. Luckily since I was just wanting to query data, I discovered that raw access was actually easier. You simply make a GET request to http://spreadsheets.google.com/feeds/worksheets/_key_/public/values (where key is provided to you when you “publish” a spreadsheet - access to unpublished spreadsheets requires authorization which is more complicated). This gives you an Atom feed of URLs to the individual worksheets which them contain Atom feeds of either rows or columns (your choice). The query power of LINQ (along with XElement, XAttribute etc.) make transforming the feeds into modules really easy. In fact the code that does the hard work (takes a spreadsheet key and generates the XML) is only 102 lines long, and that’s including unnecessary spacing to make the LINQ more readable (the main LINQ query is 35 lines).

LINQ is magical

Oliver Brown
— This upcoming video may not be available to view yet.

The secretly named language learning app has been revamped to use LINQ for most of the XML handling. For those that don’t know, LINQ is a new technology that provides querying functionality in the .NET world. In my case I’m using LINQ to XML and it has seriously cut down on the size of the heaviest methods. Also, the part of LINQ to XML that I found least interesting when I read about it is actually the part I’ve found the best - the new XDocument API. Anyway, LINQ combined with a new USB headset that provides some actually quite good audio means that the important fundamental features have been implemented and work. At the moment it can:

  • Generate lessons based on vocabulary1 modules
  • Generate lessons containing past content with the correct repetition timing.
  • Actually play the lessons (but only on Windows2)

There are a few more things I want to add before I release any of it (like more audio for a start). But I thought I’d at least point out development is still happening :o) 1Instead of the Conversation > Phrase > Term style of Pimsleur I’ve decided to go for a more freeform approach to start with (inspired by me listening to Michel Thomas again). A vocabulary module just contains list of words and phrases that are processed in order. 2I still need a cross platform way to play audio. At the moment I use MCI which is part of winmm.dll which is obviously Windows only. Although Wine has apparently implemented it almost completely but I’m not sure how I’d go about making that help me.

So much for Gtk#…

Oliver Brown
— This upcoming video may not be available to view yet.

Well I’ve abandoned my plans to use Gtk# in the language app (which actually secretly has a name now).

The main reason for changing is simplicity. I had a look at the TreeView control in Gtk and decided it was too much work. Although the theory of good MVC separation is good, the user interface is such a small, simple part of my app it wasn’t worth it. The stuff I need from System.Windows.Forms should work in Mono (and .NET 1.1 and hopefully even the Compact Framework).

I still prefer the way Gtk handles layout of controls in general, but I console myself with the Windows form designer in Visual C# Express.

A safe language on a safe OS

Oliver Brown
— This upcoming video may not be available to view yet.

Have you heard of “managed” code? Generally it refers to code that has no direct access to memory and instead has to access everything through a protected interface of sorts. The main advantages are that a program can’t go poking memory that it shouldn’t and useful rules can be enforced like type safety.

The most prevalent example of managed code is nearly everything running under .NET/Mono. Admittedly you can mark parts as “unsafe” letting you use pointers and stopping the garbage collector arbitrarily moving your data around but most of the usefulness comes from avoiding this where possible.

The problem is, you can’t always avoid it. The main reason for this is you have to access existing non managed systems. Rewriting everything in managed code is not feasible and although you can lessen any problems by writing wrappers so there is only one point of contact between managed and unmanaged code, problems can still occur - the sort of problems the managed code was supposed to prevent.

Microsoft are investigating a solution. After reading that last paragraph, the form of the solution should be obvious but for the most part it’s unworkable in the real world - eliminate all unmanaged code.

A lot of people claim managed code, or specifically .NET is slow and inefficient. Well it is. But it can be made faster. Most inefficiency is caused by a lot of run time checks to make sure everything is as it should be. If the code lives in an entirely managed world however most of these checks can be removed since (barring random hardware failure) the program can be guaranteed to satisfy the run time checks at compile time.

For more details about Singularity, Microsoft’s research operating system written in C#, check out this article by James Larus, Galen Hunt, and David Tarditi over at MSDN.