Wednesday, July 17, 2019

Velocity Weapon (The Protectorate #1), by Megan E. O'Keefe

book cover I can't decide if Velocity Weapon is brilliant or stupid. What I can say is that I didn't like it. Megan O'Keefe tells a story of three characters: a gunnery sergeant who ejects her pod during a space battle and is picked up by an intelligent spaceship, her brother who is a member of the Prime Protectorate and does everything to find her and a thief on some other planet who stumbles upon a strange lab that changes her entire life.

The writing is competent, nothing inspiring, though, and probably that is why I had difficulty finishing the book. But there are also some features of the story that I didn't like. For example of the three main characters who start the book on equal ground, the thief gets less and less space and, worse, her story never connects to the others. It's like O'Keefe wrote a book and a novella and then merged them into a larger book, even if their only commonality is the same universe. Then there is a part of the story that I got invested in, only to be aborted midway; I can't say more without spoiling the story, but I didn't like that.

The thing that bothered me most, though, is how the plot meanders instead of getting to the point. I used to think that a good story would be less straightforward, but now that I read one that just comes and goes, gives you glimpses of the world, then does nothing with them... it just felt like wasted time. Don't get me wrong, the author builds a world with vast opportunities, a universe of multiple colonized worlds connected by star gates which are controlled by the Primes and their technology originated from an alien artifact. She is just beginning the story. The characters might yet come together, the villains might become clearer, the whole thing felt potentially epic, only one would probably have to read all of the books to understand where O'Keefe is planning to go.

Basically the book is a string of almost random events, driven by forces that are never made clear, then somehow brought together by incredible coincidence, while the characters are barely sketched and hard to relate to, especially the male ones. The world has a lot of potential, but little is built on it so far. It feels like Star Wars, a little: a galaxy far far away where everybody is related or knows each other and everything in a chapter happens on one planet only. And it felt dated, as well.

So I can't decide: is this the start of a wonderful epic universe with immense potential or is it just a stupid space opera book that is not very good? I just didn't like it.

Tuesday, July 16, 2019

A .NET Core ServiceProvider that allows adding of services after it was created

.NET Core comes with its own dependency injection engine, separated in the Microsoft.Extensions.DependencyInjection package, and ASP.Net Core uses it by default. In a very simplistic description, it uses an IServiceCollection to add services to, then it builds an IServiceProvider from that list, an interface which returns an implementation based on a type or null if finding none. Any change in the list of services is not supported. There are situations, though, where you want to add new services. One of them being dynamically resolving new types.

Therefore I set up to create a custom implementation of IServiceProvider that fixes that, using the mechanisms already existing in .NET Core. Note that this is just something I did from frustration, "because I could". Most people choose to replace the entire IServiceProvider with an implementation that uses some other DI container, like StructureMap.

First attempt was proxying a normal ServiceProvider and keeping a reference to the collection. Then I would just change the collection and recreate the service provider. That has two major problems. One is that the previous serviceProvider is not disposed. If you try, you automatically dispose all services already resolved and if you do not, you remain with references to the created services. The second, and more dire, is that recreating the service provider will generate new instances for services, even if registered as singletons. That is not good.

I thought of a solution:
  1. keep a list of service providers, instead of just one
  2. use a custom service collection which will let us know when changes occurred
  3. whenever new services are added, add them to a list of new services
  4. whenever a service is resolved, go through the list of providers
  5. if any provider returns a value, provide it
  6. else if any new service create a new provider from the new services and add it to the list
  7. else return null
  8. when disposing, dispose all providers in the list

This works great except the newly added providers are separate from the existing providers so when you try to resolve a type with a second provider and that type has in its constructor a type that was registered in the first provider, you get nothing.

One solution would be to add all services to the second provider, not only the new ones, but then we get back to the original issue of the singletons, only a bit more subtle:
  1. register type1 as a singleton
  2. get an instance of type1 (1)
  3. build the provider
  4. get an instance of type1 (2)
  5. register type2 which receives a type1 in its constructor
  6. get an instance of type2
  7. now, type1 (1) is the same as type1 (2), because it was resolved by the same provider
  8. type1 is different from type2.type1, though, because that was resolved as a different singleton by the second provider in the list

One solution would be to add all previous services as factories, then. For Itype1, instead of returning typeof(type1), return a factory method that resolves the value with our system. And it works... until it reaches a definition (like IOptions) that was registered as an open generic: services.AddSingleton(typeof(IType3<>),typeof(Type3<>)). In case of open generics, you cannot use a descriptor with a factory, because it returns an object, regardless of the generic type argument used. It would not to do return a Type3<Banana> for a requested type of IType3<int>.

So, final version is this:
  1. keep a list of service providers, instead of just one
  2. keep a dictionary of the last object resolved for a type
  3. use a custom service collection which will let us know when changes occurred
  4. whenever new services are added, add them to a list of new services
  5. whenever a service is resolved, go through the list of providers
  6. if any provider returns a value, return it
  7. if no new services registered return null
  8. create a new provider from all the services like this:
    • if it's a new registration, use it as is
    • if it's an open generic definition type:
      • if singleton, add first all the existing resolutions for types that are defined by it
      • use the original descriptor afterwards
    • use a registration that proxies to the advanced resolution mechanism we created
  9. when disposing, dispose all providers in the list


So here is the final version. Use it like this:
// IAdvancedServiceProvider either injected 
// or resolved via serviceProvider.GetService<IAdvancedServiceProvider>
// or even serviceProvider as IAdvancedServiceProvider
advancedServiceProvider.ServiceCollection.AddSingleton...

And this is the source code:
/// <summary>
/// Service provider that allows for dynamic adding of new services
/// </summary>
public interface IAdvancedServiceProvider : IServiceProvider
{
    /// <summary>
    /// Add services to this collection
    /// </summary>
    IServiceCollection ServiceCollection { get; }
}
 
/// <summary>
/// Service provider that allows for dynamic adding of new services
/// </summary>
public class AdvancedServiceProvider : IAdvancedServiceProvider, IDisposable
{
    private readonly List<ServiceProvider> _serviceProviders;
    private readonly NotifyChangedServiceCollection _services;
    private readonly object _servicesLock = new object();
    private List<ServiceDescriptor> _newDescriptors;
    private Dictionary<Type, object> _resolvedObjects;
 
    /// <summary>
    /// Initializes a new instance of the <see cref="AdvancedServiceProvider"/> class.
    /// </summary>
    /// <param name="services">The services.</param>
    public AdvancedServiceProvider(IServiceCollection services)
    {
        // registers itself in the list of services
        services.AddSingleton<IAdvancedServiceProvider>(this);
 
        _serviceProviders = new List<ServiceProvider>();
        _newDescriptors = new List<ServiceDescriptor>();
        _resolvedObjects = new Dictionary<Type, object>();
        _services = new NotifyChangedServiceCollection(services);
        _services.ServiceAdded += ServiceAdded;
        _serviceProviders.Add(services.BuildServiceProvider(true));
    }
 
    private void ServiceAdded(object sender, ServiceDescriptor item)
    {
        lock (_servicesLock)
        {
            _newDescriptors.Add(item);
        }
    }
 
    /// <summary>
    /// Add services to this collection
    /// </summary>
    public IServiceCollection ServiceCollection { get => _services; }
 
    /// <summary>
    /// Gets the service object of the specified type.
    /// </summary>
    /// <param name="serviceType">An object that specifies the type of service object to get.</param>
    /// <returns>A service object of type serviceType. -or- null if there is no service object of type serviceType.</returns>
    public object GetService(Type serviceType)
    {
        lock (_servicesLock)
        {
            // go through the service provider chain and resolve the service
            var service = GetServiceInternal(serviceType);
            // if service was not found and we have new registrations
            if (service == null && _newDescriptors.Count > 0)
            {
                // create a new service collection in order to build the next provider in the chain
                var newCollection = new ServiceCollection();
                foreach (var descriptor in _services)
                {
                    foreach (var descriptorToAdd in GetDerivedServiceDescriptors(descriptor))
                    {
                        ((IList<ServiceDescriptor>)newCollection).Add(descriptorToAdd);
                    }
                }
                var newServiceProvider = newCollection.BuildServiceProvider(true);
                _serviceProviders.Add(newServiceProvider);
                _newDescriptors = new List<ServiceDescriptor>();
                service = newServiceProvider.GetService(serviceType);
            }
            if (service != null)
            {
                _resolvedObjects[serviceType] = service;
            }
            return service;
        }
    }
 
    private IEnumerable<ServiceDescriptor> GetDerivedServiceDescriptors(ServiceDescriptor descriptor)
    {
        if (_newDescriptors.Contains(descriptor))
        {
            // if it's a new registration, just add it
            yield return descriptor;
            yield break;
        }
 
        if (!descriptor.ServiceType.IsGenericTypeDefinition)
        {
            // for a non open type generic singleton descriptor, register a factory that goes through the service provider
            yield return ServiceDescriptor.Describe(
                                    descriptor.ServiceType,
                                    _ => GetServiceInternal(descriptor.ServiceType),
                                    descriptor.Lifetime
                                );
            yield break;
        }
        // if the registered service type for a singleton is an open generic type
        // we register as factories all the already resolved specific types that fit this definition
        if (descriptor.Lifetime == ServiceLifetime.Singleton)
        {
            foreach (var servType in _resolvedObjects.Keys.Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == descriptor.ServiceType))
            {
 
                yield return ServiceDescriptor.Describe(
                        servType,
                        _ => _resolvedObjects[servType],
                        ServiceLifetime.Singleton
                    );
            }
        }
        // then we add the open type registration for any new types
        yield return descriptor;
    }
 
    private object GetServiceInternal(Type serviceType)
    {
        foreach (var serviceProvider in _serviceProviders)
        {
            var service = serviceProvider.GetService(serviceType);
            if (service != null)
            {
                return service;
            }
        }
        return null;
    }
 
    /// <summary>
    /// Dispose the provider and all resolved services
    /// </summary>
    public void Dispose()
    {
        lock (_servicesLock)
        {
            _services.ServiceAdded -= ServiceAdded;
            foreach (var serviceProvider in _serviceProviders)
            {
                try
                {
                    serviceProvider.Dispose();
                }
                catch
                {
                    // singleton classes might be disposed twice and throw some exception
                }
            }
            _newDescriptors.Clear();
            _resolvedObjects.Clear();
            _serviceProviders.Clear();
        }
    }
 
    /// <summary>
    /// An IServiceCollection implementation that exposes a ServiceAdded event for added service descriptors
    /// The collection doesn't support removal or inserting of services
    /// </summary>
    private class NotifyChangedServiceCollection : IServiceCollection
    {
        private readonly IServiceCollection _services;
 
        /// <summary>
        /// Fired when a descriptor is added to the collection
        /// </summary>
        public event EventHandler<ServiceDescriptor> ServiceAdded;
 
        /// <summary>
        /// Initializes a new instance of the <see cref="NotifyChangedServiceCollection"/> class.
        /// </summary>
        /// <param name="services">The services.</param>
        public NotifyChangedServiceCollection(IServiceCollection services)
        {
            _services = services;
        }
 
        /// <summary>
        /// Get the value at index
        /// Setting is not supported
        /// </summary>
        public ServiceDescriptor this[int index]
        {
            get => _services[index];
            set => throw new NotSupportedException("Inserting services in collection is not supported");
        }
 
        /// <summary>
        /// Count of services in the collection
        /// </summary>
        public int Count { get => _services.Count; }
 
        /// <summary>
        /// Obviously not
        /// </summary>
        public bool IsReadOnly { get => false; }
 
        /// <summary>
        /// Adding a service descriptor will fire the ServiceAdded event
        /// </summary>
        /// <param name="item"></param>
        public void Add(ServiceDescriptor item)
        {
            _services.Add(item);
            ServiceAdded.Invoke(this, item);
        }
 
        /// <summary>
        /// Clear the collection is not supported
        /// </summary>
        public void Clear() => throw new NotSupportedException("Removing services from collection is not supported");
 
        /// <summary>
        /// True is the item exists in the collection
        /// </summary>
        public bool Contains(ServiceDescriptor item) => _services.Contains(item);
 
        /// <summary>
        /// Copy items to array of service descriptors
        /// </summary>
        public void CopyTo(ServiceDescriptor[] array, int arrayIndex) => _services.CopyTo(array, arrayIndex);
 
        /// <summary>
        /// Enumerator for service descriptors
        /// </summary>
        public IEnumerator<ServiceDescriptor> GetEnumerator() => _services.GetEnumerator();
 
        /// <summary>
        /// Index of item in the list
        /// </summary>
        public int IndexOf(ServiceDescriptor item) => _services.IndexOf(item);
 
        /// <summary>
        /// Inserting is not supported
        /// </summary>
        public void Insert(int index, ServiceDescriptor item) => throw new NotSupportedException("Inserting services in collection is not supported");
 
        /// <summary>
        /// Removing items is not supported
        /// </summary>
        public bool Remove(ServiceDescriptor item) => throw new NotSupportedException("Removing services from collection is not supported");
 
        /// <summary>
        /// Removing items is not supported
        /// </summary>
        public void RemoveAt(int index) => throw new NotSupportedException("Removing services from collection is not supported");
 
        /// <summary>
        /// Enumerator for objects
        /// </summary>
        IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)_services).GetEnumerator();
    }
}

Thursday, July 11, 2019

Stranger than we can Imagine: Making Sense of the Twentieth Century, by John Higgs

book cover Stranger than we can Imagine feels like a companion book to the 2002 documentary The Century of the Self. Both are really well done and discuss the brusque changes that define the 20th century and they complement each other in content. I recommend them highly to just about everyone except maybe little children.

John Higgs starts the book comparing history to a landscape and the works describing it as maybe roads. There are well trodden paths on this landscape, but also deep forests where few dare enter. He then promises that his book will try to describe the twentieth century by exploring these dark places, avoided by others. I didn't feel that was completely the case, but certainly it was a novel path to take to explain history: Einstein, Heisenberg, Gödel, Lorenz, Mandelbrot, Freud, Picasso, Dalí, Joyce, Leary, Stravinsky, Crowley, Thatcher, The Rolling Stones, Miyamoto and so on. Its basic premise is that an abrupt change occurred at the beginning of the 20th century, when the general belief in absolutes (which he generically calls omphaloi) was replaced with relativism and individuality.

How would classical empires survive these changes when at their core stands the belief in a supreme leader, representing and supported by a supreme god, who protects and enforces rules that are culturally accepted by everyone? They would not, therefore the world wars that ended them. What absolute pillar of belief would survive general relativity, the uncertainty principle, quantum mechanics, the incompleteness theorems, the id and individualism, impressionism, cubism, modernism, postmodernism and finally, the corporation? None of them. Religion not so much dies as it breaks apart in small fragments that then fade away. Morality shakes under the reign of individual desires and psychopathic legal entities. Social norms, economical behavior, even the foundation of money are wiped out and replaced with the new. Art fractures as well, constantly redefining and contradicting itself and everything else. It is the century where value exists only when seen from certain perspectives and nothing has any intrinsic value.

The book ends with a chapter that heralds the coming of a new age, the 21st century: the Internet and the erosion of the last remaining omphalos: truth. If truth also depends on the observer, if there is no one truth, if science if just a belief like any others, what awaits us in the post-truth era?

Overall it is a very interesting and informative book. More than simply stating facts, it is the unexpected connections between things that bring value to the reader, rather fitting considering the subject. Maybe not going into the depths of dark forests, but certainly exploring their edges and the strange beings that live there. Top marks!

Tuesday, July 09, 2019

Setting the NuGet package folder location for Visual Studio solutions

Long story short, check out this answer to a StackOverflow question: Package destination of restore of .net-core projects is always global package directory

The scenario is this, you are used to .NET Framework projects for which Visual Studio restored NuGet packages in a packages folder in the solution folder and then you switch to .NET Core. No packages folder! You google it and you find that there is a global folder in your user's profile where NuGet will download all of these projects, that .NET Core uses it by default and also that you might change this behavior used on a property in nuget.config. So here are the issues you have take into account:
  1. There are two ways of configuring NuGet packages for your projects: a packages.config file and PackageReference elements in your .csproj file
  2. The name of the property you need to set is different based on the type of configuration: repositoryPath and globalPackagesFolder, respectively
  3. There are two formats for configuring nuget properties: using the add element inside the config element and using the repositoryPath element inside the settings element
  4. The format that worked for me in VS 2017 was the config element
  5. There are two locations for the nuget.config file: in a .nuget folder inside your solution folder and directly in the solution folder (or any of its parent folders)
  6. The location that is accepted by the latest versions of NuGet is directly in the solution folder
  7. Sometimes you need to restart Visual Studio for the change in nuget.config files to considered
  8. The path you specify is relative to the nuget.config file, no matter where it is

A bit of an overkill, but try this as the beginning of your nuget.config file that sits next to the .sln file in your solution:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <config>
    <add key="repositoryPath" value="./packages" />
    <add key="globalPackagesFolder" value="./packages" />
  </config>
  <settings>
    <repositoryPath>./packages</repositoryPath>
  </settings>
  ...
</configuration>

Monday, July 08, 2019

Deathcaster (Shattered Realms #4), by Cinda Williams Chima

book cover Deathcaster is the final book in the Shattered Realms series, or at least it should be, since it kills off the villain and has everybody live happily ever after. It's one of the least satisfying endings I've read in a long time.

Cinda Williams Chima started slowly, by creating a complex world of realms, magic and a multitude of characters and factions. She spent two books on that. The third book, Stormcaster, was about introducing a powerful and mysterious villain and yet more characters, realms and factions. Deathcaster pretty much ends it all in an until then unknown place, at a random time, for a completely random reason. Imagine Luke Skywalker walking around, playing with his sword, thinking on how to defeat the Death Star and accidentally bumping into and killing the emperor and Darth Vader both. This is how this book feels, after wading through a zillion people, with their feelings described in detail while any military or political strategy is explained (poorly) in a paragraph or two, through their relationships with other people, through their random interactions that always seem to bring them together for no apparent reason and then split them apart randomly and then the villain basically stumbling and falling on their sword.

There is nothing interesting that actually happens, no moral in any of the stories and the development of the characters is basically just beefing up and aging a few years.

Bottom line: the ending of this book makes the reading of the three previous books and this one feel like a complete waste of time. How do you rate a book that makes all the previous ones unrateable? Cinda, you're a troll!

The Flight of Morpho Girl (Wild Cards #24.1), by Caroline Spector and Bradley Denton

book cover The Flight of Morpho Girl is a short story set in the Wild Cards universe. If you haven't read the books until now, you won't know who the characters are. Even so, this story is so basic that it feels like "The Unsuccessful Mugging of Batman" or "Murder of Crows v Superman": predictable and stakeless.

That doesn't mean that the authors didn't do a good job, it's just that it is a short that brings nothing to the table other than the introduction of Morpho Girl's (Adesina, the teenager daughter of Amazing Bubbles) post cocoon form: a teenage girl with very tough butterfly wings. For me it's like a collectible item in the Wild Cards set, nothing more.

Descendant of the Crane, by Joan He

book cover I have to admit that my expectations for this book were so high that it was probably doomed to not satisfy me. I was expecting something deeply Asian, with fantastic elements and fresh ideas and characters. What I got is something that is almost accidentally fantastical and has few cultural elements to make it fresh. Yet it does have interesting characters and, if it weren't for the plot, which meanders whichever way the author needs to further her agenda, it would have been a good book.

Joan He is American of Chinese descent (hence the name of the book?) and the culture described in Descendant of the Crane is based on an American's understanding of Chinese culture. That makes it both relatable and less Asian than I would have liked. What do I know, though? My feeling was that the author was exploring her own understanding of her origins instead of sharing something solid with the reader. There were some very intriguing ideas in the book, but they rode the story and the characters too strongly, making them inconsistent and irrational. This is an almost maybe book for me.

Bottom line: even without getting a lot of satisfaction out of it, I feel two stars out of five is too little, yet I am certain three is too much.