Siderite's Blog View RSS

No description
Hide details



Censorship, Wikipedia and manga online links 31 Aug 2019 10:55 AM (5 years ago)

I have a few posts that link to various sites that provide free online viewing of manga. Recently, I've been getting DMCA notifications about "copyright infringement", therefore I am replacing them with Wikipedia links. I am aware that whoever sent those notifications is wrong, since they can't possible have copy rights for links of sites they do not control, but I am not going down that rabbit hole. Google still works, after all.

And speaking of Wikipedia, I've recently been to Turkey where I was shocked to see that the entire Wikipedia site is blocked. According to Wikipedia, the site is or was censored in one way or another in China, France, Germany, Iran, Pakistan, Russia, Saudi Arabia, Syria, Tunisia, Turkey, United Kingdom, Uzbekistan and Venezuela. Hmm, France, Germany and the UK, huh? I wish you'd have said something, visitors from those countries... assuming my blog is not censored as well, [intense stare into the future, horizon and the wall in front] as the shining beacon of freedom it is for the entire world [snapping out of it].

Anyway, seems that only China and Turkey are seriously banning the Wikipedia articles, so I've added a way to "Fix" the links by replacing them with Google queries *if* you are in Turkey, China or Taiwan, thanks to ipapi for the user location detection service.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Istanbul, not Constantinopole 30 Aug 2019 1:30 AM (5 years ago)

Intro


Istanbul is a beautiful lie. You are being served, begged of, you can haggle any price and no one will get upset, you are a king among serfs, everything is ancient, colorful and traditional. But as you walk around in the high but pleasant sea-side heat you can't help but wonder: how high was that initial price if you can lower it again and again and again? How are you a king while walking in the most populous city of one of the most powerful countries in the region? Why are there armored cars here and there, watching you while you unsuccessfully try to reach Wikipedia on your cell phone in Democracy Park? How can all these traditional shops sell the exact same thing all over the city? Why are there so many types of tea in the bazaar, but when you go to a cafe they only serve one?

Now, I enjoyed my visit to Istanbul. My hotel was sub par, but I didn't care about it too much because the staff was doing their best to be accommodating. Yet there are some things I would have liked to know before going there. Here are my thoughts.

Prerequisites


The first thing to consider when going to Istanbul is if you want to rent a car. The answer to this is "I do not want to rent a car, because I want to survive this vacation". The driving is chaotic and the roads are steep and crowded. Most of the time you don't even want to take cabs. People cross the street randomly and there are scooters that speed onto any temporarily free surface. Yet, except a motorcycle guy that probably died on the freeway, I have not seen even a car bump in this mess. To be a driver in Istanbul is both a badge of honor and skill and a psychiatric condition. You've been warned!

The second thing you need is select the part of Istanbul you want to be based in, because the city is vast and split by the sea into three parts: two in Europe and one in Asia. If you are a touristy kind of person, go to the Sultanahmet, Eminonu side. If you want more authenticity, real people living their lives, go to the Asian side, while the other European side is more for the city lifestyle and shopping, like in Taksim square. I haven't been to the modern part of the city, but from afar the buildings there look tall and beautiful and I am told it's great, too.

You've got to be careful choosing your hotel. Istanbul is so chocked with them that when you look at the map you feel that you have not zoomed in enough. In fact every building in some areas is a hotel and all that separates them are small windy one car streets: no side walk, no parking spaces, no green space. You have to pay attention to the pictures of the hotel, to how may rows of windows they have, for example. It will tell you how tall they really are and how many windows your room will have. A lot of these places have large lobbies and terraces, but it's where you enter the hotel and where you get breakfast in the morning, while your room might have just a window overlooking a fence. I've seen rooms that had no windows. So it is vital you speak directly to the hotel and discuss the conditions of your rooms (do not trust they will get the information from Booking or act on it). It's not that they want to cheat you, but everything in Istanbul is negotiable. You need to speak to an actual person. The city abhors algorithms.

One more important thing is your infrastructure. You need information and transportation. In Istanbul a lot of transportation works with an IstanbulKart, an electronic card you can put money on and then pay for trams, buses, ferries, etc. Cabs, of course, are different. Careful with the cabs: you might get a perfectly good one from the airport, with a meter and a credit card reader, then get another that only accepts cash and you must negotiate the price. Now, it might feel like a waste, but I recommend you get one kart for each person. While you can very well use only one for an entire group, I got into the situation where my wife passed and I didn't, so she had to wait until I found a recharging station and had to negotiate with the Turkish only interface.

That gets me to the information portion: Turkey is not in the EU. That means that calls and SMS messages are very expensive and probably mobile Internet as well. While most shops have WiFi, when you are on the road you need Internet. If you have a dual SIM phone (and even if you don't) I recommend you buy a prepaid Turkish card for your Internet and local calls. I didn't do that, so I got stuck a lot of times. As so many translation systems work online, too, I think it's a good idea. Everything in Istanbul is in Turkish, with occasional afterthoughts about other languages. People there know very little English and when they do, you are not sure if they understood what you told them or they simply don't want to appear stupid.

The fun


The fun is all on you! I won't tell you what is good and what is not, because not one of the people that prepared me for my trip had an experience even close to mine. It's not that I am special, but people really are different and Istanbul provides differently depending on your style. What I can tell you is that it is a city worth visiting, but perhaps not for the usual reasons. It feels different. It's not a clone of all the other cities I've been to. It really has its own culture, it's not overwhelmed with the same multinational corporations, it doesn't have banks and pharmacies everywhere, and the lack of rules (or the difference in them) opens the mind to possibilities.

For me the mosques were all the same, the palaces were just buildings with old furniture in them, the museums collections of objects with little life to them. For example I went to the Royal Kitchens in Topkapi; there was nothing to reflect the life that went on there. Just random kitchen implements nicely ordered inside transparent cages. I didn't find the haggling with shop owners pleasant or the ice cream seller antics entertaining. The food was nice, but not extraordinary. The bazaars were full of shops that sold the exact same things. I couldn't get close to a shop without someone harassing me about buying or entering. These are not the reasons why I enjoyed Istanbul.

Instead, it was the weird combination of new and old, of people living their lives differently, the all present sea breeze which made the heat bearable. It was the way people did all of these annoying things and yet I felt no malice from or toward them. It all felt viscerally eternal, like this city had the power to survive the world encroaching on it.

I don't know, maybe you just need to have played Quest for Glory II to feel this way. Or maybe it's just me. I don't think I would want to return soon, but it's an experience I recommend. And now, try to get this out of your head:

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Vita Nostra (Метаморфозы #1), by Marina Dyachenko, Sergey Dyachenko 29 Aug 2019 2:08 PM (5 years ago)

book cover Imagine Harry Potter were a Russian girl named Sasha Samokhina. Instead of an Oliver Twist childhood followed by the happy admission to a place of high learning, she starts off within a happy family and then is forcefully inducted into a village institution apparently bent on making people crazy upon punishment of hurting said family. Instead of a loyal gaggle of friends to help the hero through random quests, it's a bunch of normal kids that either hate her, ignore her or get infatuated with her for their own random reasons. Instead of a nasty revenant with superpowers, she has only her own weakness and her insane teachers to fight against. And most of all, everything she achieves she does through effort, not by being lucky, getting powerful items from mysterious friends or being helped by previously unknown actors.

This is Vita Nostra - and not a book about Italian mobsters as the title made me believe, a book written by two married writers, Marina and Sergey Dyachenko, who wrote 26 other books before this you probably have never heard of because they are in Russian and no one bothered to translate them to English. I wonder if I would have ever heard of them if there weren't currently living in California. There are, of course, similarities to Harry Potter: the same idea that teachers perceive pupils as incompetent infants that cannot be trusted with information and power, for example. The same underestimation of children leads to both the successes of Potter and Samokhina (if hers can be called successes, it's a Russian book after all). There is also the isolation of children, away from family, friends and the rest of the world, a typical indoctrination move. Will our hero keep her morals or succumb to the ideas forced upon her by cruel educators? Will the teachers be proven right and their methods validated, or are they just assholes? Is this really a Hogwarts thing or more the Stanford Experiments meet 120 Days of Sodom? Well, that is for the reader to find out, as they go through the three books (yes, Russians are affected by trilogiopathy as well).

Warning, though, the book starts very slowly and with a style reminiscent of a lot of stories I disliked profusely: the dream sequence, where you cannot be certain that what the character perceives is real or not. Also, the ending is abrupt and says almost nothing. Oh, yes, I can speculate, but would be the point of that? In order to understand what is going on, you just have to read at least the second book as well.

Bottom line is that I liked the book after I got through the slow beginning, I was captivated by the lead character and I found it hard to put the book down, but it's not always easy to empathize with Sasha and the rest of the characters are not deeply explored.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Quakeland: On the Road to America's Next Devastating Earthquake, by Kathryn Miles 29 Aug 2019 1:37 PM (5 years ago)

book cover We trust the ground beneath our feet as something solid that can take our weight, keep our structures straight, holds fast. Yes, we read things, we know about tectonics, but other than that, everything is stable. In the very beginning of Quakeland, Kathryn Miles thoroughly debunks that idea: Earth is an ocean of lava upon which very thin amalgamations of sand and rubble float precariously. What we call faults are just the largest of cracks, stable and classifiable; there are many more that we have no idea exist, fragile enough to be affected or even created by human activity. At this point, I was expecting an exciting journey through the center of the Earth. If the book would have continued as it started, it would have been a solid five stars, an educational tool to teach what most of the people have no idea about: the fragility of the thin crust we call solid ground. Alas, it was not to be.

The rest of Quakeland, let's say the last 80%, was a very US-centric analysis of how neglected earthquakes are when constructing and maintaining American infrastructure and a fear inducing series of "what-ifs" and possible disasters affecting that one country. I shouldn't have expected anything else, I mean the subtitle is pretty clear, but how can someone switch registers from talking about the very structure of the planet to the measly issues of one country and its weird measuring units? And maybe she did not use the almost ubiquitous bus size, but Miles did use the swimming pool together with the M-scale (do not let any "serious" seismologist hear you talk about Richter), the miles, the feet, the pounds, etc. The writing is competent and almost formulaic in structure, but I can't say I had any issues with it.

The bottom line is that the beginning was brilliant, the information that fracking (and mining in general) - regardless if it is toxic, damages the ground water or anything else activists throw at it - causes long series of earthquakes that affect whole areas while and even after operations cease, as powerful political and economic forces deny and actively fight the science that demonstrates this was new and important. Yet other than that it was just a normal reporter speculating about the possibilities of quakes - man made or not - causing serious harm. A lot of terribilism and fear mongering. That is why I can't really recommend this book and I will rate it as average only.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Installing emacs on Windows 10 linux subsystem and Android 21 Aug 2019 12:57 AM (5 years ago)

Here are the steps for installing Emacs on Windows 10:


At this time you should have Emacs running in the Linux subsystem on Windows 10.

You can also install it on Android:
But why would you need to install Emacs at all? Because now you can run 'emacs -batch -l dunnet'. Don't forget to 'save'! :D
Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Timers that capture the execution context, evil AsyncLocal and the quick and ugly solution used by Microsoft devs 19 Aug 2019 4:02 AM (5 years ago)

It all started with the source code for NonCapturingTimer, a static factory class that was creating a System.Threading.Timer without capturing the execution context and was described as "A convenience API for interacting with System.Threading.Timer in a way that doesn't capture the ExecutionContext. We should be using this (or equivalent) everywhere we use timers to avoid rooting any values stored in asynclocals.". What did that even mean?

An issue opened by David Fowler sheds some light on this: "Any lazy activation of timers will capture the ExecutionContext. Combining this with a lazy initialization of the HttpClient and the handler graph may end up holding onto AsyncLocals for longer than expected. This could end up looking like a memory leak". This follows a Twitter thread from Fowler declaring AsyncLocal as evil.

There are also multiple issues that have crystallized into a proposal for a future version of .NET: "Timer static Create methods that make rooting behavior explicit".

And if you look at the ASP.Net sources on GitHub, they do use the class mostly for one time timer calls and periodic cleanup calls. I should mention that Ben Adams from Microsoft calls this way of creating timers ugly.

I don't have the time to go down further on this rabbit hole, but maybe people will find answers here when looking into this and comment on their findings.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The Ten Thousand (The Macht #1), by Paul Kearney 19 Aug 2019 12:29 AM (5 years ago)

book cover The Macht series is not related to anything Germanic, as the name might imply, but is instead inspired by the Greek Hoplites. Even if The Ten Thousand happens on another planet that has different continents and two moons and three intelligent races, Paul Kearney could have written it just as well as a historical novel set in ancient Greece, with Greek mercenaries getting hired by Persians as weapons in a civil war that went awry. In fact, the story really is inspired by an actual historical group called the Ten Thousand and the main character, with the unfortunate name of Rictus, seems to be inspired by that of real life Xenophon. The book seems to be a retelling of Anabasis.

Now, the story is well written and short. I read the whole thing in a day. It's like a 300 novel, with the courageous and lethal Macht force finding itself on a foreign continent, surrounded by overwhelming hostile forces and having to march through rough and deadly terrain in order to get home. There is a lot of fighting, technical and military, some romance, bro-mance and feudal politics, but it's essentially the story of a huge march seen through the eyes of an experienced soldier, but young and new to the mercenary troupe.

Bottom line: I don't know if I am going to read any other Macht book. This one felt self contained and I am not that much into ancient fights in the Bronze Age. I liked The Ten Thousand, though, and I recommend it as a short and captivating read.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The Luminous Dead, by Caitlin Starling 18 Aug 2019 11:57 PM (5 years ago)

book cover The Luminous Dead has only two active characters: a cave diver, covered in a special suit that enhances her strength and completely isolates her from the environment, and her handler, the person who guides and provides support remotely. At first glance it's a sci-fi story, as it happens on another planet, with futuristic technology, different rules, alien lifeforms, etc. However, it starts to itch at you that with the tech that was described, the tasks at hand could have been completed a lot more efficiently and safely, so what gives?

Turns out the story is more of a metaphor than a fantastic cave adventure on another planet. Probably inspired by the death of Caitlin Starling's mother, it explores the damage done by losing your parents, the obsessions that drive the affected, the extent to which someone will go to quiet those voices in their heads. But I liked it. It's got just enough action and adrenaline to keep you going while it touches the painful emotional bits that the book was really about.

Bottom line: I urge you to ignore all technical aspects of the story. It's not that the author did not made the effort to make them believable, it's that they are irrelevant to the moral of the book. Also ignore the wild emotional fluctuations of the characters: they are supposed to behave that way. The book feels as if following a personal journal with the events of the story being just sci-fi versions of the items there.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The giant house spider 18 Aug 2019 11:58 AM (5 years ago)

While being hosted in a small house in the Arges county, I found myself face to... err... hairy body to hairy body with a large spider, at least 10 cm from the tips of the front legs to the tips of the hind legs. The body itself was about 2 cm in length. I tried to catch it, but it ran away and I didn't exactly feel safe handling it. However, from my standpoint, the adventure was just beginning. It starts with a picture:


In a previous post, I was telling you about a web site that recognized plants from blurry pictures I had taken. I assumed that somewhere there was something similar for spiders. Alas, it doesn't seem to be the case, so I reverted to the classic Google search with descriptive words: a European spider 10 cm in length. I found it almost immediately, clearly a member of the genus Tegenaria in the family Agelenidae. Or is it?

Funny enough, most of the spiders assigned to Tegenaria were recently (2013) moved to another genus, Eratigena, based on DNA and molecular analysis. So my spider, likely a "giant house spider", can be found either as Tegenaria atrica or Eratigena atrica (not to mention Tegenaria duellica, Tegenaria gigantea and Tegenaria saeva). I also can't be completely sure of the identification. As far as I can tell, it's a male, based on the large (pedi)palps, used not only to hold on to prey, but also to deposit sperm in the females. But while I think it looks most like an atrica, based on the pictures I found online, it could also be an Agelena labyrinthica or a Tegenaria parietina, even if the first is found in Denmark and should be smaller and the second is rare and native to Central Asia.

Considering it's a giant spider I found in a house, I will go with Eratigena atrica, but one has to wonder how active biology as a science is to have species of common arthropods reassigned from one genus to another just a few years ago. So yeah, a nice little story, for me at least, all starting from a picture of a spider in a bathroom.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Tate no Yuusha no Nariagari, or Rise of the Shield Hero. A ridiculous, but fun anime. 14 Aug 2019 12:39 PM (5 years ago)

Tate no Yuusha no Nariagari is one of those isekai animes where a normal Japanese boy is summoned in a magical realm to fight monsters. Once there, he realizes that the world and his character work exactly as in a fantasy video game, complete with items with upgradeable stats, waves of monsters and revealing female armor. He is summoned there with three other heroes, also from Japan, only from alternate universes, each of the heroes having their own magical item that defines their style. His item is a shield and immediately he notices that he is treated differently, with all honors given to the other three and only disgust for him. Long story short, he is forced to hone his skills through his will and efforts alone, while the others, spoiled by their environment, make no effort and therefore level up less.

I liked this anime and I will continue to watch it, although it's a bit ridiculous. I've read the manga as well, which is also new, and there are slight differences in the sense that the anime is a little more serious. If you want a mindless game like experience in anime form, go for it. Here is a trailer:

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Violet Evergarden, a really nice anime, with an uncertain future 14 Aug 2019 12:19 PM (5 years ago)

Violet Evergarden is set in a steampunk universe in which technology, other than metal prosthetics, is at the 19th century level, and the main character is a girl that was used as an elite child soldier in a terrible war who now has to find a purpose in a civilian life. She takes on the job of a "auto memory doll", a person who needs to put into words the feelings of others. That's a bit of a stretch, because she doesn't know how to feel herself... it's like me taking on a job in psychology or artistic design so as to learn a new skill. Certainly great for me, but kind of sucks for my employer!

Anyway, the animation is really well done and the acting is top notch. The story itself is beautiful, even if at times inconsistent. After watching the 14 episodes of the first season, I was itching for more, only to hear from a colleague that the studio responsible for the animation, Kyoto Animation, was destroyed in a terrible arson attack. That doesn't bode well for a sequel, yet a spin-off film had already been announced, so who knows?

Bottom line: it's not for everyone. PTSD romance, I would call it. But it nicely animated and I liked the story. I felt that the characters were a bit off, but not annoyingly so. Here is a trailer, in English:

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The Binding, by Bridget Collins 13 Aug 2019 2:14 AM (5 years ago)

book cover There is a trope in fantasy writing that goes like this: young person is uprooted from their life as they learn a new skill or gain a new power, while people in authority teach them things so slowly and inefficiently that the young person needs to make efforts to learn by themselves. Harry Potter had it. The Binding has it. Only in the case of this book, the young person is someone who is always sick without knowing why, is suddenly sent off from home to be an apprentice for someone he doesn't know and while he understands nothing of what he is supposed to do. Months later and 25% of the book in, he still hasn't learnt anything, although he is always tired and exhausted for no good reason whenever he is about to. If he doesn't collapse, his mentor will! And, spoilers ahead, his mentor then dies.

So after a quarter of the book, absolutely nothing happened while I had to suffer a depressed weak and barely teenage boy who didn't want, know, or want to know anything. Bridget Collins' writing is competent and I am sure things are going to get better from here (I mean, they can hardly get worse), but I just won't continue to read the book.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Magic for Liars, by Sarah Gailey 9 Aug 2019 1:50 PM (5 years ago)

book cover Magic for Liars is one of those stories where magic exists in a hidden layer of our world, yet it doesn't bring any happiness. People are still people, regardless of their power. And what better way to explore human nature than writing a detective story in a high school for magical kids?

Sarah Gailey writes the story from the viewpoint of the detective, a woman who's greatest frustrations stem from her sister being a magician, while she is just "normal". Yet when she is tasked to find out the circumstances of the death of one of the teachers in the magic school, she jumps on it, making her realize more about herself and the relationships with family and other people.

Yes, the magic is quite incidental and the detective part quite secondary and it could just as well been written in a space academy or science lab or anywhere where flawed people have to manage each other and the balance of power between them. And while I feel the main character was compelling and the story well written, I can't quite shake the feeling I've been duped into reading a touchy-feely type of drama that I didn't really intend to read. You will not read about the specifics of magic in any kind of way; it is quite bluntly used as a tool that the reader needs not understand. You will not be amazed by the amazing feats of deduction of a fascinating detective; the main character is by definition a very normal person with a penchant for introspection and focusing on her own messed up feelings.

In the end you know the spouse did it, or the butler, or the person who flirts with the detective, or the god-like magician, or the weird kid. The culprit isn't even that important for the plot. It's all about the theoretical dynamics between the people and what makes them tick.

Bottom line: a fine investigation into the core motivations of people, woven in a rather short and bland story which purely incidentally features detectives and magic.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

When is efficiency bad? TED talk: The human skills we need in an unpredictable world, from Margaret Heffernan 8 Aug 2019 10:00 PM (5 years ago)

The talk is a bit overreaching, doing more things than it should have tried to do, in other words not very efficient, but it contains some really interesting ideas and it's extremely well articulated. As a software developer, I always thrive for efficiency, but what Margaret Heffernan says is that efficiency is good only when the future is predictable. In a fast changing world (and getting faster), efficiency doesn't just not help, it makes things worse. Sometimes you can't plan, but you can prepare.

As expected, I wasn't as interested in the humanistic part of the talk as I was in the technical aspects: algorithmic efficiency is only good with things that can be measured. If you want to innovate or to adapt, it's trial and error that works best. I got that giddiness I get when people tell me "you can't do THAT in software!". Oh, ye of little faith! But there is something there, something extremely useful, a tool that I can use whenever I get stuck in logic loops or some manager tells me that he needs data in order to make a decision about the project that would generate the data.


Margaret Heffernan: The human skills we need in an unpredictable world

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

.NET Core: Cannot resolve scoped service 'Microsoft.Extensions.Options.IOptionsSnapshot...' from root provider 6 Aug 2019 1:19 AM (5 years ago)

I was trying to create an instance of an object from a service provider to resolve any dependencies, using ActivatorUtilities.CreateInstance<MyObject>(_serviceProvider) and I was getting the exception:

System.InvalidOperationException
HResult=0x80131509
Message=Cannot resolve scoped service 'Microsoft.Extensions.Options.IOptionsSnapshot`1[ExternalConfiguration]' from root provider.

My object was receiving a parameter of type IOptionsSnapshot<ExternalConfiguration> and upon further investigation, my service provider (which came as a resolution from the dependency injection for IServiceProvider) was actually a ServiceProviderEngineScope which just refused to resolve any IOptionsSnapshot! Funny enough, if I replaced IOptionsSnapshot with IOptionsMonitor, which in my mind is a heavier interface, it worked without issues. Further still, the problem appeared only inside an IHostedService (a BackgroundService hooked up with services.AddHostedService<T>); if I wrote the same code in a controller action, for instance, it worked fine.

The .NET 2+ implementation of IOptionsSnapshot<T> is OptionsManager<T>. If I manually resolved an instance of OptionsManager before my object, then added it as a parameter, the code worked:
var optionsSnapshot = ActivatorUtilities.CreateInstance<OptionsManager<TestOptions>>(_serviceProvider);
var myObject = ActivatorUtilities.CreateInstance<MyObject>(_serviceProvider, optionsSnapshot);

So, specifically, the issue is that in .NET Core, the service provider implementation cannot resolve IOptionsSnapshot interfaces in worker services. You can still do that manually, but I suspect it is a bug, since there is no problem using an IOptionsMonitor instead of IOptionsSnapshot.

A possible solution is to use an additional service provider only for IOptionsSnapshot. Warning, this will not work in a general situation if the dependencies from the additional service provider also need parameters that would be found in the original service provider:

// initialization code
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(
typeof(IOptionsSnapshot<>),
typeof(OptionsManager<>)
);
serviceCollection.AddSingleton(
typeof(IOptionsFactory<>),
typeof(OptionsFactory<>)
);
_additionalServiceProvider = serviceCollection.BuildServiceProvider();
 
// resolution code
var constructor = typeof(MyObject).GetConstructors()
.Where(ci=>ci.IsPublic)
.Single();
var args = constructor.GetParameters()
.Select(p =>
{
try
{
return _serviceProvider.GetService(p.ParameterType);
}
catch
{
return _additionalServiceProvider.GetService(p.ParameterType);
}
})
.ToArray();
return ActivatorUtilities.CreateInstance<MyObject>(_serviceProvider, args);
Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Blackfish City, by Sam J. Miller 5 Aug 2019 8:34 AM (5 years ago)

book cover There are writers like Steven Erikson, describing worlds so vast that characters seem to drown in them, there are writers like William Gibson or Charles Stross, who go so far into the future that people seem to lose their relevance, yet none of them dare to ignore their characters or fail to make them interesting. Yet, that's what Sam J. Miller does in Blackfish City.

10% in and I couldn't bare reading any more of this book. I couldn't care less about the asexual person that is whining about his life, I couldn't care less about the orphan girl whining about her life, I couldn't care less about the sick homosexual boy who is whining about his life and I couldn't care less about the anonymous radio show that narrated what the city was instead of the action showing me. Should I care about all the world getting sunk under the water until the only livable places are floating megacities reminiscent of Waterworld and run by semi abandoned AIs? Should I care about the artificial drama, weird futuristic disease or the grey whining world that Miller describes? No. I refuse!

Bottom line: a poor man's cyberpunk story, with the mechanical "woke", but irrelevant to anything else, sexual and cultural references, with boring characters and a story that I had to make an effort to wade through and still didn't seem to go anywhere.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

City of Miracles (The Divine Cities #3), by Robert Jackson Bennett 4 Aug 2019 12:58 PM (5 years ago)

book cover It takes the third book to see that the "hero's journey" is actually Sigrud's, even if he is the lead character only in this final book of the Divine Cities series. And yes, it is the final book, with a satisfying and very permanent ending, with no hope of dragging it on. Hell, if you consider there are three books and two cities and no gods left, you could wonder how would anyone continue the story if pressured by publishing companies.

Robert Jackson Bennett did not disappoint with City of Miracles, switching registers a little by turning the usual steampunk-noir detective story into more of a chase and revenge thriller. The villain is revealed quite soon, the mystery split into multiple little quirks that nag at you until the end of the book and a massive divine battle to top it all up. Yet I was a little disappointed with the ending. I know, rationally, that it is a great ending, but emotionally I didn't get what I needed from it, especially as I was still fired up on the penultimate chapter only to get an "aftermath" chapter for last.

Maybe it was that one of the options they employed at the end could have easily been the first and solved a lot of problems to boot. Or the fact that a lot of the grief in the final third of the book came from Sigrud not checking his kills, which is something he would never ever do. It felt a little stretched and tired compared to the other stories.

Sometimes I wonder, is it easier or harder for a writer to just abandon a world that he so carefully crafted? Is it a burden that everything that is successful needs to be turned into a trilogy or a series, or is it like coming home, writing about good friends living in your head? Either way, I am kind of grateful to Bennett for ending it all. I would have read more and more books like these if he wrote them, because I am an addict at heart, but I believe both of us can do better.

Bottom line: It's kind of difficult to compare the three books in the series. The first one was the most captivating, but also first, the second one was darker, yet in the same vein, while the last felt philosophical and like the writer wanted to get it done with. You can read either as standalone, although it makes more sense to read the whole trilogy from first to last. I recommend it and I will read more from the author.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

City of Blades (The Divine Cities #2), by Robert Jackson Bennett 31 Jul 2019 12:33 PM (5 years ago)

book cover Robert Jackson Bennett caught my attention with the first book in the Divine Cities series: City of Stairs. It was a steam-punk and magic detective story featuring a strong female character and her trusty sidekick, with great world building and character work. City of Blades is kind of the same, but slightly darker.

What surprised me in this book was that the author chose to abandon his hero of the previous volume and bring forth one that was a secondary character in that. It's still a whodunit, it's still a strong female lead fighting divine but malevolent forces. If it ain't broke, don't fix it, right? Only City of Blades is more about the personal pain of people, their sacrifice and service, their (dashed) hopes and dreams, the promise of the afterlife.

Long story short, I was planning to read something else at the end of the book, but instead I've just started immediately with City of Miracles, the third and last book in the trilogy. I love this series!

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Nature in Valcea 28 Jul 2019 11:56 AM (5 years ago)

I am going to try something new with this blog post. Usually, when I go somewhere on vacation, the things that capture my attention are not what interest about anybody else in my entourage. I am also not a very lyrical writer, so what's the point of enumerating the places I've been from the perspective (oh, so much used!) of the casual tourist. I imagine myself writing one of those horrid "10 things to do in..." articles, promptly vomit and desist from thinking about it.

With this post, though, I am going to tell you of the wild (but accessible) area that I've explored and where to find it, how I felt and, if I can find the references, what plants and animals live there. You see, when I go somewhere, I avoid people and take really bad pictures of flowers and plants, butterflies, weird things and sometimes landscapes.

The place


I've been to Cheile Bistritei Valcene (the canyon of the river Bistritza from Valcea - there is another one in the north of the country) and in the valley of the Luncavatz river. The vegetation and insects are very similar, so I am going to treat this as a single area, even if their locations are 20 KMs apart:
The area is very nice, easy to get to by car, but not very touristic yet, so not a lot of people having picnics and listening loudly to music. Leave your car and walk on the sides of the river(s) and the scenery is verdant and quiet. I have to warn you that even if in Romanian they are called rivers, they are more like creeks, especially at this time of the year. You can even find some caves in the area and if you are the long walk type of person, some 4-5 hour hike routes to more remote areas. Some flowers are white, but the vast majority of them are either yellow-orange or violet in color and probably are much more interesting in ultraviolet than human vision.

Animal life


I haven't seen any animals other than birds, a running lizard and a lot of insects.

I saw several species of butterflies, the most common by far being a medium sized orange with black spots, a fritillary, probably the Silver-washed fritillary (Argynnis Paphia) or mantia imparatului in Romanian. They were frolicking on these tall yellow flowers with large leaves: the yellow oxeye (Telekia speciosa) or brusture and ochiul-boului in Romanian. The next most common was a shy dark butterfly with a crimson edge on its wings. Probably the Woodland ringlet (Erebia Medusa), I have no idea what the Romanian popular name for it is.


Argynnis Paphia on a Telekia speciosa




Erebia Medusa



Some other butterflies: the cabbage white (Pieris rapae) or fluturele de varza in Romania, the peacock (Aglais io) or ochi de paun de zi in Romanian, the swallowtail (Papilio machaon) or coada de rindunica in Romanian and even one glimpse of what I think was a marbled white (Melanargia galathea) or tabla de sah in Romanian.


Pieris Rapae




Aglais Io (during my youth Innachis Io)




Papilio Machaon




Melanargia Galathea



One fascinating specimen looked similar to a peacock butterfly from afar only for it to settle in a triangular black and white shape when it stopped. It must have been a moth! I've identified it as a Jersey tiger moth (Euplagia quadripunctaria) or fluturele urs dungat in Romanian.


Euplagia Quadripunctaria



What I also found fascinating is a tree that had apparently been colonized by ants. A lot of wood dust was on the ground and a lot of activity was inside the trunk. Still, there was another hole in the trunk that was filled with wood dust, but no ant activity. Could it have been some sort of other factor, termites or perhaps a disease, that destroyed the tree trunk's interior and the ants were just opportunists?


Ants or termites? New behavior or opportunism?



Plants


Now, plants are easier to photograph, but harder to identify. I've mentioned the oxeye. Then there was the touch-me-not (Impatiens noli-tangere) or slabanog and bradulet in Romanian, which appears to have been used traditionally for its medicinal properties, mostly related to kidney or gynecological issues. The Spreading bellflower (Campanula patula) was there, together with its close relative, the Creeping bellflower (Campanula rapunculoides) - both are called clopotei in Romanian. There was the mountain geranium (Geranium robertianum) or napraznic and priboi and iarba sfintului Robert in Romanian, which appears to have anti-stress, anti-cancer and fertility related purposed in traditional medicine.


Impatiens Noli-tangere




Campanula Patula




Campanula Rapunculoides




Geranium Robertianum



Field mustard was present as well (Brassica rapa). This plant was and is used for a variety of reasons in many cultures. The leaves and roots are rich in oil. In Puglia they use the buds as cimedirape in the making of orecchiette pasta. It is a plant from the cabbage family of plants, probably explaining the presence of the cabbage butterflies.


Brassica Rapa



A very interesting flower has a very weird name: the Viper's bugloss (Echium vulgare) or iarba sarpelui in Romanian. It has blue flowers but the filaments of the stamens are red, contrasting with the petals and giving it a violet color per whole. It has medicinal uses as well, as an antidote for snake bites and for its antibiotic and astringent properties.


Echium Vulgare



Another violet flower, with uses in homeopathic medicine but also in poisonings, is aconite or wolfsbane (Aconitum napellus) or omag in Romanian. It contains powerful alkaloids and at one time it was forbidden to grow this plant anywhere in the Roman Empire on penalty of death. Death from intoxication with the plant can occur in as little as half an hour!


Aconitum Napellus



And since we are talking about a violet flower with medicinal properties, how can we ignore the heal-all (Prunella vulgaris) or busuioc salbatic in Romania. The young leaves and stems can be eaten raw in salads; the plant in whole can be boiled and eaten as a potherb; and the aerial parts of the plant can be powdered and brewed in a cold infusion to make a beverage and it is used as an astringent in folk medicine.


Prunella Vulgaris



Not often, but when it happened it was a whole field of them, I found the Orange mullein (Verbascum phlomoides) or luminarica in Romanian. It is also a medicinal plant, used for the calming, sweat inducing and expectorant effects.


Verbascum Phlomoides



I've seen some daisies in the area and also another flower from the same family: the fleabane (Erigeron annuus) or bunghisor in Romanian. Used in salads as well as against the common cold or stomach aches in folk medicine.


Erigeron Annuus



Last, but not least, the evening-primrose or sundrop (Oenothera biennis) or luminita noptii in Romanian. It started as an American plant, much like the fleabane, but it was brought and naturalized in Europe. It has been used medicinally by the native Americans for all kinds of ailments, as it is an edible plant containing an oil with anti inflammatory properties.


Oenothera Biennis



There were a lot of plants without flowers, but I haven't had the time or patience for them. There was one with huge leaves and I photographed it for identification purposes. It turns out it was either the butterbur (Petasites hybridus) or the burdock (Arctium lappa) both called brusture in Romanian, but different species altogether. It's probably the Arctium, but I can't be sure!


Petasites hybridus or Arctium lappa? A lot of stuff called brusture in Romanian!



Resources


It would have been a lot more difficult for me to write this post if it weren't for sites like:
Even with these great resources, it was obvious that not many people will publish nature related posts in any systematic manner. Even this post, three hours in the making, is a random mess of blurry pictures and random observations.
Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Dark Matter, by Blake Crouch 25 Jul 2019 12:06 PM (5 years ago)

book cover It wasn't the writing, it is competent, without having any other redeeming quality. It wasn't the story, which is as banal as the book cover and the title, but bearable. It was the main character, a person so ordinary that he freezes whenever he is in danger, loses everything he loves several times from people who threaten him with violence and who for seven chapters, under the guise of thinking like a scientist, attempted in vain to realize what was obvious to the reader from the start. Yeah, OK, how dare he not be a superhero with indomitable courage and magical powers! I accept my part of the responsibility, however I could not for the life of me continue to read Dark Matter past chapter 7.

I am going to go on a limb here, though, and guess that the rest of the book will be just the same: a perfectly ordinary man, thrown into another world, whining about everything and not understanding anything because he clings to his idea of normalcy and refuses to adapt, only to somehow find some strength in the end and reach a partially satisfying ending. It's not really science fiction, it's just one of those "what if you would have made other choices in life" things masquerading as science fiction. I have other things to do that read about the emotional torture of a guy who is just too easily tortured. It's like stealing candy from children. I know the hero's journey starts from a state of pleasant equilibrium then something happens to upend that and the hero must fight to reach another state of equilibrium, but the initial state for this book is a boring guy living with his family and incapable of the basest reasoning skills.

So, yeah, I stopped reading it midway. Sorry, Blake Crouch!

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The Invention of Nature: Alexander von Humboldt's New World, by Andrea Wulf 23 Jul 2019 10:47 AM (5 years ago)

Book cover The Invention of Nature is an ode to Alexander von Humboldt, the man who has practically invented our concept of nature, inspired Darwin and Goethe and Bolivar and Jefferson and so many others, created the ideas of ecology, Gaia (although it wouldn't be called that for some time), global connection between volcanic activity. He was among the first to popularize the idea that man's mindless exploitation of nature cannot last and will have dire consequences. The last true polymath, Andrea Wulf calls him, and on paper he seems a god: an avid reader, a great thinker, fluent in many languages, exploring on foot tirelessly until in his seventies, dabbling not only in natural sciences, but also politics, social revolution, physics, drawing, prose and poetry. He had been actively writing and corresponding until well in his eighties. The quintessential 19th century romantic scientist, he was interested in everything and anyone and wrote incessantly. At one time he remained out of money because he was paying for the publication of all his books, being interested in spreading the knowledge, not profit. He was collecting rocks, insects, plants, soil samples, etc. then he would send them to other scientists who were interested, for nothing in return.

His view of nature and the cosmos (term that he coined) permeates the vision of our society even now. So how come so few people know about him? To my shame, that includes me. I vaguely knew the name, but had no idea how grand his influence is. Wulf's explanation is that after the first world war (and I guess the second didn't help, either) an anti-German sentiment spread in Europe and America, leading to burning of books, lynching of German people and an overall erasure of anything Germanic from culture.

Now, half of the book is almost exclusively a Humboldt biography and it is awesome! I was imagining how great it would be if someone were to make a TV series about it (Netflix and National Geographic, I am looking at you!): so many details, so many adventures, so many important people of the age. I think the book would have been more accessible if it would been just that. But then the author also described some other people who were influenced by Humboldt, and while knowing that Darwin venerated the man and did everything he did from the moment he read one of the man's books, the others were less interesting or important.

Even so, the other people cover less than a quarter of the book... the rest is acknowledgements, bibliography, references, etc. Andrea Wulf did a wonderful job researching this and bringing Humboldt to life for me. Even if the ending of the book was not as satisfying as the beginning, it's hard for me to rate this any less than excellent. You need to read this!

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Velocity Weapon (The Protectorate #1), by Megan E. O'Keefe 16 Jul 2019 9:11 PM (5 years ago)

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.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

A .NET Core ServiceProvider that allows adding of services after it was created 16 Jul 2019 6:31 AM (5 years ago)

.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

This implementation also has a flaw: if a dependency parameter with a generic type definition descriptor was resolved as a singleton by an additional service provider, then is requested directly and can be resolved by a previous provider, it will return a different instance. Here is the scenario:
  1. the initial provider knows to map I<> to M<>
  2. you add a new singleton mapping from X to Y and Y gets a constructor parameter of type I<Z>
  3. you request an instance of X
  4. the first provider cannot resolve it
  5. the second provider can resolve it, therefore it will also resolve a I<Z> as an M<Z> singleton instance
  6. you request an instance of I<Z>
  7. the first provider can resolve it, therefore it will return a NEW singleton instance of M<Z>

This is an edge case that I don't have the time to solve. So, with the caveat above, 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();
}
}
Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Stranger than we can Imagine: Making Sense of the Twentieth Century, by John Higgs 11 Jul 2019 12:57 AM (5 years ago)

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!

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Setting the NuGet package folder location for Visual Studio solutions 9 Jul 2019 6:11 AM (5 years ago)

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>
Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Deathcaster (Shattered Realms #4), by Cinda Williams Chima 8 Jul 2019 8:29 AM (5 years ago)

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!

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The Flight of Morpho Girl (Wild Cards #24.1), by Caroline Spector and Bradley Denton 8 Jul 2019 8:09 AM (5 years ago)

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.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Descendant of the Crane, by Joan He 8 Jul 2019 7:58 AM (5 years ago)

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.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The Rithmatist (Rithmatist #1), by Brandon Sanderson 8 Jul 2019 7:40 AM (5 years ago)

book cover It was one of the few Brandon Sanderson books that I hadn't read and it is, at least at this moment, a standalone book. I know that title says that The Rithmatist is part of a series, but what successful book isn't? In truth, Sanderson started this book while working (and failing) on another and it took years to rethink and rewrite it into a finished story. It's best you take it as one of those wonderful accidents that successfully reach the reader despite the publishing industry.

Back to the book, it's almost classic Sanderson: the main character is young, passionate and intelligent, yet lacking power. Everybody else has it, though, and he is fascinated by it, while learning at a prestigious school that also teaches the techniques of power. In this gearpunk like novel, the power is magical and involves drawing lines with chalk and imbuing them with personal will. The lines then become defenses, attacks, weapons and even magical minions. When the school is attacked and his friends are in danger, it is up to him to solve the mystery.

It's obvious that the story has issues, and that is probably why Sanderson worked so much at it to make it publishable, but one can get past it quickly. The characters are not as funny or punny as his others or even very complex, being satisfied to have one or two goals in life and go for them (kind of like magical chalk drawings themselves, hmmm). The plot, involving the awesome power of carrying a piece of chalk with you and going through amazing duels that resemble tower defense games, it also not the most captivating. Yet the story kind of works.

Bottom line: a pleasant Brandon Sanderson classic, without being exceptional in any way.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Chasing New Horizons: Inside the Epic First Mission to Pluto, by Alan Stern and David Grinspoon 8 Jul 2019 7:22 AM (5 years ago)

book cover I thought long and hard how to start this review and I think the best place is the ending. In July 2015 the Internet and even the classic media exploded with the news of the American space probe named New Horizons reaching the last unexplored classical planet of the solar system: Pluto. Long thought to be a frozen piece of rock floating too far from the Sun to be of any interest, it has been ignored by NASA and every other space agency out there, only to be revealed to be one of the most intriguing and beautiful gem of our system. New Horizons had been launched in 2006 and it took one more year to get all the Pluto data back to Earth. As far as the general population was concerned and even most of the people passionate about space, this was an axis in time with three major events: launch, flyby and end of data download. As far as the media was concerned, it was a great discovery because it produced memeable pictures (the Pluto heart is one, for example).

heart or Pluto the dog? Chasing New Horizons starts in 1989, when Alan Stern deciding he would work for a NASA mission to Pluto, it takes us through the Herculean job of creating interest, gathering people, drafting a project, finding support and funding, fighting competing teams, bureaucracy and political apathy and even bad will, the ups and downs, the almost-theres, the Sisyphean and thankless work to get something up the Hill only to see it fall because of a change in administration, or a cut in the budget, or some hidden agenda and even people petty enough to demote Pluto's status as a planet as a personal grudge against the person who discovered it.

I liked how the book was written, even if at start I had to move over the usual platitudes meant to garner interest for space from the average reader and had to cope with the American units of measurement: feet, miles, Fahrenheit and, of course, the bus-size. However, no matter the small faults in the writing, the subject is so important than I can't rate the book lower than maximum. This is a must read, even if it skirts the technical aspects and mostly discusses the 25 year work from a managerial standpoint.

It's hard to describe how awesome these people are. Can you imagine working for a quarter century for something that can fail abruptly and with no positive outcome at literally any moment? I thought I had it bad when a project I was working on for six months was cancelled - imagine having to go through something like this several times, at the exact moment when you thought it will all sail smoothly from then on, when you had the funding, the assurances and even the construction of the probe nearly finished. Four days before one critical moment, the flyby, when New Horizons was supposed to do almost all of its work, the on board computer rebooted and lost all previously uploaded programming. In those four days, people had to scramble to recreate the entire software package they had worked for incrementally for the last 9 years and upload it to a machine that was 9 light hours away from Earth. One of the most critical moments of the mission (after 16 years of ground work to make it happen) was the launch, for example. The mission planners had no control over the mechanism of the launch vehicle. It could have blown on the pad or in the air.

There would be no redos. First, no way the project would have been approved again after a failure so senseless. Second, Pluto would have moved in a region of its 248 year long orbit where its atmosphere would freeze, making any other future probe return much less interesting data than at that exact moment. If it failed, it would have been the first and probably last APL planetary exploration mission, after they fought tooth and nail to be the ones doing it, rather than the usual and entrenched JPL. People had lived their entire lives working on this thing and it could have failed in so many different ways.

Bottom line: you have to be insane to do what Stern did. A wonderful flavor of insanity that is both admirable and terrifying. The system behind NASA should value and support these people even if, especially if, they are insanely driven enough that they don't actually need it. I would say that New Horizons succeeded despite the American space industry and political system, not because of them. It really shouldn't be that hard. This is a book for all space fans, but also people who had difficulties in their projects. While it might help with specific insights, this book will make almost any hardship you ever endured seem insignificant.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Dynamically loading types from assembly files in .NET Core and Standard 3 Jul 2019 4:15 AM (5 years ago)

We already know how to load types in .NET Framework and we know what they say we should use in .NET Core. But what about Standard? Is that a trick question? Sort of. Right now we have two .NET Standard and three .NET Core versions, albeit .NET Core 3 is in preview mode. The signature for AssemblyLoadContext and how it is used has changed dramatically. Core 3 enables context unloading, but Standard 2 does not. So you either are forced to build your library as Core 3 or you have to not use Unloading contexts or use reflection, which is not robust and probably will not be needed with the possible arrival of Standard 3.

But there are subtler issues at work. One of them is that, at least with .NET Core 3 Preview6, when you reference System.Runtime.Loader in a Standard library, so you can access AssemblyLoadContext, you get conflicts between the System.Runtime you are using and the one referenced by System.Runtime.Loader. The only solution is to use the System.Runtime.Loader NuGet package, but that returns you to the Standard 2 version of AssemblyLoadContext, even if the library version is higher!

The setup is this: I have an ITestInterface interface which resides in TestInterfaceLibrary.dll. I also have a TestImplementation class that can be found in TestImplementationLibrary.dll and implements ITestInterface. My program either does not reference any of these libraries or it only references the interface one. The task is to load both these types and then simply convert one instance of TestImplementation to ITestInterface. Simple test would be loading the types and then expecting interfaceType.IsAssignableFrom(implementationType) to be true.

Core 3


Let's first try the Core 3 way:
var context = new AssemblyLoadContext("testContext", true);
 
var interfaceAssembly = context.LoadFromAssemblyPath(interfaceAssemblyPath);
var interfaceType = interfaceAssembly.GetType("TestInterfaceLibrary.ITestInterface");
Console.WriteLine(interfaceType?.ToString()??"interface type not loaded");
 
var implementationAssembly = context.LoadFromAssemblyPath(implementationAssemblyPath);
var implementationType = implementationAssembly.GetType("TestImplementationLibrary.TestImplementation");
Console.WriteLine(implementationType?.ToString() ?? "implementation type not loaded");
 
Console.WriteLine("implementation implements interface: "+interfaceType.IsAssignableFrom(implementationType));
 
context.Unload();
The output is:
TestInterfaceLibrary.ITestInterface
TestImplementationLibrary.TestImplementation
implementation implements interface: True

It works! But only because the interface assembly is loaded first. If you try to load just the implementation type first, it will come up as empty. There are no exceptions thrown unless you get all the assembly types or specify the throwOnError parameter in GetType. The exception is "System.IO.FileNotFoundException: 'Could not load file or assembly 'TestInterfaceLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.'".

In order to solve this, we need to use the Resolve event of the AssemblyLoadContext class. Let's try this:
var context = new AssemblyLoadContext("testContext", true);
context.Resolving += Context_Resolving;
 
var implementationAssembly = context.LoadFromAssemblyPath(implementationAssemblyPath);
var implementationType = implementationAssembly.GetType("TestImplementationLibrary.TestImplementation", true);
Console.WriteLine(implementationType?.ToString() ?? "implementation type not loaded");
 
var interfaceAssembly = context.LoadFromAssemblyPath(interfaceAssemblyPath);
var interfaceType = interfaceAssembly.GetType("TestInterfaceLibrary.ITestInterface", true);
Console.WriteLine(interfaceType?.ToString() ?? "interface type not loaded");
 
Console.WriteLine("implementation implements interface: " + interfaceType.IsAssignableFrom(implementationType));
 
context.Resolving -= Context_Resolving;
context.Unload();
 
private static Assembly Context_Resolving(AssemblyLoadContext context, AssemblyName assemblyName)
{
var expectedPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyName.Name + ".dll");
return context.LoadFromAssemblyPath(expectedPath);
}

And now it works again, by assuming the assembly name is the same as the assembly file name and that it is found in the same place.

But... if we try this in different contexts:
var context = new AssemblyLoadContext("testContext", true);
context.Resolving += Context_Resolving;
 
var implementationAssembly = context.LoadFromAssemblyPath(implementationAssemblyPath);
var implementationType = implementationAssembly.GetType("TestImplementationLibrary.TestImplementation", true);
Console.WriteLine(implementationType?.ToString() ?? "implementation type not loaded");
 
context.Resolving -= Context_Resolving;
context.Unload();
context = new AssemblyLoadContext("testContext2", true);
context.Resolving += Context_Resolving;
 
var interfaceAssembly = context.LoadFromAssemblyPath(interfaceAssemblyPath);
var interfaceType = interfaceAssembly.GetType("TestInterfaceLibrary.ITestInterface", true);
Console.WriteLine(interfaceType?.ToString() ?? "interface type not loaded");
 
Console.WriteLine("implementation implements interface: " + interfaceType.IsAssignableFrom(implementationType));
 
context.Resolving -= Context_Resolving;
context.Unload();
the output will show
implementation implements interface: False

This means that if we want to encapsulate this in a TypeLoader class or something, we cannot use different contexts for dynamically loading types. Even if we had one context that we would unload in order to refresh all the types, it could still be different from the main context, in case the interface is loaded twice or referenced directly in the project.

For example, if you reference TestInterfaceLibrary directly and you load TestImplementation dynamically it will work as expected, because ITestInterface is resolved automatically from the main context. However, if you load ITestInterface dynamically, too, it will be a different type from the referenced ITestInterface, even if they apparently have the same name and full name and assembly qualified name! So it kind of makes sense to not load a type twice. Is this where the context unloading comes in? Not really. Let's define a method that counts the number of types with a certain name in the current domain as
private static int CountTypes(string typeName)
{
return AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes().Where(t => t.FullName == typeName))
.Count();
}

And now let's run this code:
var context = new AssemblyLoadContext("testContext", true);
context.Resolving += Context_Resolving;
 
var referencedInterfaceType = typeof(ITestInterface);
Console.WriteLine(referencedInterfaceType?.ToString() ?? "interface type not loaded");
 
var interfaceAssembly = context.LoadFromAssemblyPath(interfaceAssemblyPath);
var interfaceType = interfaceAssembly.GetType("TestInterfaceLibrary.ITestInterface", true);
Console.WriteLine(interfaceType?.ToString() ?? "interface type not loaded");
 
Console.WriteLine($"Types are the same: {interfaceType==referencedInterfaceType}");
 
Console.WriteLine($"Number of types with name {interfaceType.FullName}: {CountTypes(interfaceType.FullName)}");
 
context.Resolving -= Context_Resolving;
context.Unload();
Console.WriteLine($"Number of types with name {interfaceType.FullName}: {CountTypes(interfaceType.FullName)}");

There is the referenced type, then we load the type dynamically again, inside a new context. We count the types loaded in the current domain, we unload the context, we count the types again. The result is
TestInterfaceLibrary.ITestInterface
TestInterfaceLibrary.ITestInterface
Types are the same: False
Number of types with name TestInterfaceLibrary.ITestInterface: 2
Number of types with name TestInterfaceLibrary.ITestInterface: 2
The types are always 2!

Bottom line, even when unloading the AssemblyLoadContext, the types used are not unloaded and trying to find a type by name will result in duplicates.

OK, so let's just agree that types with the same name, once loaded, should remain there and no other type with the same name should be loaded. Let's try to incorporate this into a TypeLoader class:
public class TypeLoader : IDisposable
{
private readonly AssemblyLoadContext _context;
 
public TypeLoader()
{
_context = new AssemblyLoadContext(GetType().FullName, true);
_context.Resolving += Context_Resolving;
}
 
private Assembly Context_Resolving(AssemblyLoadContext context, AssemblyName assemblyName)
{
var expectedPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyName.Name + ".dll");
return context.LoadFromAssemblyPath(expectedPath);
}
 
public Type LoadType(string typeName, string assemblyPath)
{
var type = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes().Where(t => t.FullName == typeName))
.FirstOrDefault();
if (type != null)
{
return type;
}
var assembly = _context.LoadFromAssemblyPath(assemblyPath);
return assembly.GetType(typeName, true);
}
 
public void Dispose()
{
_context?.Resolving -= Context_Resolving;
_context?.Unload();
}
}

The code in our test is now much clearer:
var interfaceAssemblyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestInterfaceLibrary.dll");
var implementationAssemblyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestImplementationLibrary.dll");
var interfaceTypeName = "TestInterfaceLibrary.ITestInterface";
var implementationTypeName = "TestImplementationLibrary.TestImplementation";
 
using (var loader = new TypeLoader())
{
Type referencedType = typeof(TestInterfaceLibrary.ITestInterface);
var interfaceType = loader.LoadType(interfaceTypeName, interfaceAssemblyPath);
var implementationType = loader.LoadType(implementationTypeName, implementationAssemblyPath);
Console.WriteLine($@"
referenced type: {referencedType}
interface type: {interfaceType}
implementation type: {implementationType}
referenced and loaded interfaces are the same: {referencedType == interfaceType}
interface implemented: {interfaceType.IsAssignableFrom(implementationType)}"
);
}
and the result is
referenced type: TestInterfaceLibrary.ITestInterface
interface type: TestInterfaceLibrary.ITestInterface
implementation type: TestImplementationLibrary.TestImplementation
referenced and loaded interfaces are the same: True
interface implemented: True

But we still use Unload. Maybe it will work some day as I want it to work, but until then, why not get rid of Unload and make TypeLoader a class in a Standard 2 library?

Standard 2


For this I will create a new Standard 2 library project and then reference it in our test Core 3 project. Then I will move the TypeLoader class in the library project.

The errors in the library project are related to not knowing what an AssemblyLoadContext is, therefore the first solution is to reference System.Runtime.Loader from the framework. I get the immediate error "Assembly 'System.Runtime.Loader' with identity 'System.Runtime.Loader, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' uses 'System.Runtime, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' which has a higher version than referenced assembly 'System.Runtime' with identity 'System.Runtime, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".

Solution 2: load the System.Runtime.Loader NuGet package, which at the time of writing this, is version 4.3.0. The error is now gone, but several things are immediately apparent:
  1. the Unload method doesn't exist anymore
  2. the constructor doesn't receive a name and a bool anymore
  3. AssemblyLoadContext is now abstract

In order to solve this I am creating a DynamicAssemblyLoadContext class that inherits from AssemblyLoadContext and just return null from the Load method overload, and I give it an Unload method and a constructor with a string and a bool that don't do anything. And it works again. The updated TypeLoader class is now:
public class TypeLoader : IDisposable
{
private readonly DynamicAssemblyLoadContext _context;
 
public TypeLoader()
{
_context = new DynamicAssemblyLoadContext(GetType().FullName, true);
_context.Resolving += Context_Resolving;
}
 
private Assembly Context_Resolving(AssemblyLoadContext context, AssemblyName assemblyName)
{
var expectedPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyName.Name + ".dll");
return context.LoadFromAssemblyPath(expectedPath);
}
 
public Type LoadType(string typeName, string assemblyPath)
{
var type = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(ass => ass.GetTypes().Where(t => t.FullName == typeName))
.FirstOrDefault();
if (type != null)
{
return type;
}
var assembly = _context.LoadFromAssemblyPath(assemblyPath);
return assembly.GetType(typeName, true);
}
 
public void Dispose()
{
_context?.Resolving -= Context_Resolving;
_context?.Unload();
}
 
 
private class DynamicAssemblyLoadContext : AssemblyLoadContext
{
public DynamicAssemblyLoadContext(string name, bool isCollectible)
{
}
 
protected override Assembly Load(AssemblyName assemblyName)
{
return null;
}
 
public void Unload()
{
}
}
}

The safe way


The code above has an issue, though. If the interface type is dynamically loaded before its referenced type is used, this fails again. This is the case when you use dependency injection. You dynamically load the types in order to register the implementation relationship to the interface, but then, when you ask for a resolution for the interface type, now referenced by the main project, you get another type named just the same.

The safe way, considering that we don't really use Unload and we don't count on it every working, why not use the default context, the one where everything loads, and be done with it. When you do that, the code becomes a little uglier, but it works in all situations.

Final version.
public class TypeLoader
{
private readonly object _resolutionLock = new object();
 
private Assembly Context_Resolving(AssemblyLoadContext context, AssemblyName assemblyName)
{
var expectedPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyName.Name + ".dll");
return context.LoadFromAssemblyPath(expectedPath);
}
 
public Type LoadType(string typeName, string assemblyPath)
{
var context = AssemblyLoadContext.Default;
lock (_resolutionLock)
{
context.Resolving += Context_Resolving;
var type = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(ass => ass.GetTypes().Where(t => t.FullName == typeName))
.FirstOrDefault();
if (type != null)
{
return type;
}
var assembly = context.LoadFromAssemblyPath(assemblyPath);
 
type = assembly.GetType(typeName, true);
context.Resolving -= Context_Resolving;
return type;
}
}
}

You just gotta hate that adding and removing the event inside a lock, right? Well, if you find a better solution, let me know.
Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The Blood Mirror (Lightbringer #4), by Brent Weeks 30 Jun 2019 1:35 AM (5 years ago)

book cover The Blood Mirror felt like the weakest book in the series, but really, if I think about it, it's the pattern that unfolded through the entire Lightbringer saga that feels wrong. The first book was amazing, with interesting characters, great world building, an intriguing story, but then came the second book - and I didn't see it then - which upended much of the concepts in the first and added many more. It was not a continuation, per se, but a reframing of the story with other parameters. Instead of closing story arcs, Brent Weeks was transforming them, kept them open and added many more. The third book made this pattern obvious and in this book it became annoying.

Forget that everybody is the relative of everybody or in the extreme the member of an organization that we didn't know existed or cared about in previous books. Forget that after we follow a character as something, we have to follow them as something completely different in the next book, because of reasons that we didn't know (or cared) about. Forget even that threatening someone's loved ones seems to control everything with maximum efficiency in this universe, while actually harming them is a forgivable offense. Nothing. Ever. Ends. It just piles on. And since there is limited space in the book, important things - like the war or what the people are actually doing when the entire establishment blows in their faces and destroys their lives - get sidelined or completely eliminated in favor of whatever insecurity Kip feels while discussing hot sex with his friends or amazingly beautiful (and totally inconsistent) wife. And of course, the book ends in another cliffhanger.

In chess, when you are overwhelmed by the complexity of the position, you simplify it. You exchange pieces until the board is clearer. In Lightbringer, enemies just enjoy threatening each other and never following up while they work together for some completely pointless goal. Just like in TV soap operas, they all hate and love each other at the same time while things that could never have been predicted by the reader happen as chaotically as possible around them.

So, the fifth book will be published this year and I will read it, but my rating on the entire series just plunged dramatically. I don't expect things to really come to any conclusion, I don't expect characters to evolve in any meaningful way anymore or the lore behind it all to ever be explained. We started with seven colors and a god, now we have 11 colors and about 200 gods, for example. The chances that all of this mess will become clear in the future are remote.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The Broken Eye (Lightbringer #3), by Brent Weeks 27 Jun 2019 5:59 AM (5 years ago)

book cover The Broken Eye continues right after the shocking finale of The Blinding Knife! And that pretty much sucks, because the ending was the type of cliffhanger that just felt added on in order to make people quickly buy the next volume. Unfortunately, this book is no different. After a zillion story arcs that meet improbably and a lot of agitation one way or the other, Brent Weeks ends Broken Eye with an even shockier (is that a word?) ending.

And I will bite, I will read the fourth book in the series, The Blood Mirror, but only because I find the characters intriguing. Yet I definitely lost that feeling of respect for the story, the careful attention to detail that I enjoyed so much in the first volume. Weeks is a good writer, maybe even a great one, but instead of the series getting better, it just gets bloated until it needs over the top twists and abrupt cliffhangers. One of the most pervasive feelings when reading this volume was frustration that the stories of characters that I wanted to follow were interrupted by all of the others and how each and every one of even the secondary heroes needed their own grand achievement until it got claustrophobic. OK, you're the good guy, but when you see someone hurting everyone you know, you just kill them. You don't one up them, you don't talk to them, you don't strategize or play games. OK, you're a powerful psycho, but it doesn't mean everything needs to be a power show. I mean, does Andross Guile even go to the bathroom or just wills his bowels into submission? OK, you are young and inexperienced so you don't know what to do when you love someone, but doing the exact opposite? And how come in this universe there are at most two degrees of separation? More like one and a half. And how come everyone knows what they need to do when they need it, regardless if they ever learned it before?

I am already hooked into the story and Brent Weeks creates a complex and compelling one, however the experience of reading the books is only diminishing with stupid techniques like cliffhangers and hidden information and mindless expansions into new territories that absolutely did not need to be there. Too bad that now everything will need to at least maintain this insane level of tension and complexity, for fear of turning boring.

Bottom line: not bad, certainly not boring, but pointlessly exhausting.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Visual Studio and Visual Studio Code extensions 25 Jun 2019 12:35 AM (5 years ago)

This is more a backup for the extensions that I have installed on the two main IDEs I'm using for my job: Visual Studio and Visual Studio Code.

Visual Studio Code


In order to list the extensions installed, use the command code --list-extensions. For me, this results in this output:
code --install-extension aeschli.vscode-css-formatter
code --install-extension Angular.ng-template
code --install-extension christian-kohler.npm-intellisense
code --install-extension cmstead.jsrefactor
code --install-extension cssho.vscode-svgviewer
code --install-extension danwahlin.angular2-snippets
code --install-extension dbaeumer.jshint
code --install-extension dbaeumer.vscode-eslint
code --install-extension donjayamanne.jquerysnippets
code --install-extension donjayamanne.jupyter
code --install-extension DotJoshJohnson.xml
code --install-extension ecmel.vscode-html-css
code --install-extension eg2.vscode-npm-script
code --install-extension esbenp.prettier-vscode
code --install-extension fabianlauer.vs-code-xml-format
code --install-extension fknop.vscode-npm
code --install-extension HookyQR.beautify
code --install-extension humao.rest-client
code --install-extension joelday.docthis
code --install-extension k--kato.docomment
code --install-extension michelemelluso.code-beautifier
code --install-extension minhthai.vscode-todo-parser
code --install-extension mohsen1.prettify-json
code --install-extension mrmlnc.vscode-scss
code --install-extension ms-mssql.mssql
code --install-extension ms-vscode.csharp
code --install-extension ms-vscode.typescript-javascript-grammar
code --install-extension ms-vscode.vscode-typescript-tslint-plugin
code --install-extension msjsdiag.debugger-for-chrome
code --install-extension naumovs.color-highlight
code --install-extension pmneo.tsimporter
code --install-extension rbbit.typescript-hero
code --install-extension robinbentley.sass-indented
code --install-extension wayou.vscode-todo-highlight
In order to install them, use code --install-extension [extension name] for each line.

Visual Studio


For Visual Studio, funny enough, in order to export and import your extensions you need to use an extension: Extension Manager 2017, which on my system exports a file in .vsext format:
{
"id": "5f191824-b8a6-47c0-9f96-f607dfd3c09b",
"name": "My Visual Studio extensions",
"description": "A collection of my Visual Studio extensions",
"version": "1.0",
"extensions": [
{
"name": ".NET Portability Analyzer",
"vsixId": "55d15546-28ca-40dc-af23-dfa503e9c5fe"
},
{
"name": "Advanced Installer for Visual Studio 2017",
"vsixId": "Caphyon.AdvancedInstaller.23debb5a-cff4-4b91-88bf-6280f72a7ebb"
},
{
"name": "Azure Data Lake and Stream Analytics Tools",
"vsixId": "1e906ff5-9da8-4091-a299-5c253c55fdc9"
},
{
"name": "Azure Functions and Web Jobs Tools",
"vsixId": "Microsoft.VisualStudio.Web.AzureFunctions"
},
{
"name": "BuildVision",
"vsixId": "837c3c3b-8382-4839-9c9a-807b758a929f"
},
{
"name": "Clean Code .NET",
"vsixId": "CleanCode.NET.9ecfa9bb-0775-48d0-9898-4dbbbd529fe3"
},
{
"name": "Cloud Explorer for VS 2017",
"vsixId": "Microsoft.VisualStudio.CloudExplorer"
},
{
"name": "Code Cracker for C#",
"vsixId": "CodeCracker.Vsix..5b99e64c-1418-4a06-990c-fd4cf01f4f63"
},
{
"name": "Code Graph",
"vsixId": "CodeAtlasVSIX.Company.df5456fb-08ea-4256-b5ff-ecdb3a512ad3"
},
{
"name": "CodeMaid",
"vsixId": "4c82e17d-927e-42d2-8460-b473ac7df316"
},
{
"name": "CommentCop",
"vsixId": "CommentCop..0521EE68-1A5D-4C78-9970-B6A46B03FA6D"
},
{
"name": "EntityFramework Reverse POCO Generator",
"vsixId": "EntityFramework_Reverse_POCO_Generator..d542a934-8bd6-4136-b490-5f0049d62033"
},
{
"name": "Extension Manager 2017",
"vsixId": "e83d71b8-8bfc-4e06-b145-b0388910c016"
},
{
"name": "Fix Mixed Tabs",
"vsixId": "FixMixedTabs.9f1d3050-b986-4b10-ae36-97c6efc5e968"
},
{
"name": "Fix Namespace",
"vsixId": "f073da8c-bb52-41f8-b95a-a6346b1a0b52"
},
{
"name": "MetricsAnalyzer",
"vsixId": "MetricsAnalyzer..8026235d-7afc-401b-8f45-ba8624a07ef5"
},
{
"name": "Microsoft Code Analysis 2017",
"vsixId": "4db2d63d-3320-4fbd-bf80-07f8d1500bd3"
},
{
"name": "Moq.Analyzers",
"vsixId": "Moq.Analyzers..c3c7e3f8-2407-428d-beef-c4557253517b"
},
{
"name": "Object Exporter",
"vsixId": "07fb5b16-f4be-4488-9a19-b4f36d2c05a6"
},
{
"name": "Output enhancer",
"vsixId": "VSOutputEnhancer.Nikolay Balakin.a06be4c3-f97e-425c-8a0d-bdef08ac2abb"
},
{
"name": "Power Commands for Visual Studio",
"vsixId": "PowerCommands.3ecdd89b-f985-483d-8c94-be37de4dc083"
},
{
"name": "Ref12",
"vsixId": "SLaks-Ref12-086C4CE4-7061-4B1F-BC77-B64E4ED71B8E"
},
{
"name": "Reference Conflicts Analyser",
"vsixId": "ff477521-e67b-4ca3-931f-3edf36125d28"
},
{
"name": "Regular Expression Tester Extension",
"vsixId": "a65d58d2-ead8-4eea-a47d-fa60865a6043"
},
{
"name": "ResolveUR - Resolve Unused References",
"vsixId": "637ba02c-3388-4e54-9051-3eea7c51b054"
},
{
"name": "Roslyn Security Guard",
"vsixId": "RoslynSecurityGuard..45fa56c2-16f1-4395-8c10-a5a460084018"
},
{
"name": "Roslynator 2017",
"vsixId": "9289a8ab-1bb6-496b-9992-9f7ea27f66a8"
},
{
"name": "Security Code Scan (for VS2017 and newer)",
"vsixId": "955196A7-ACBF-4F6B-820B-51B8507CE853"
},
{
"name": "Solution Error Visualizer",
"vsixId": "SolutionErrorVisualizer.a392f96b-6b33-4b53-b4bb-3376a05f986c"
},
{
"name": "SonarLint for Visual Studio 2017",
"vsixId": "SonarLint.36871a7b-4853-481f-bb52-1835a874e81b"
},
{
"name": "SQL Search",
"vsixId": "Redgate.SQLSearch.VSExtension.9BD7AEDA-C291-4702-8191-4189B099F3A9"
},
{
"name": "Target Framework Migrator",
"vsixId": "TargetFrameworkMigrator..4f7666b9-e62c-46a1-af25-21ab8742ef00"
},
{
"name": "Trailing Whitespace Visualizer",
"vsixId": "4c1a78e6-e7b8-4aa9-8812-4836e051ff6d"
},
{
"name": "Unit Test Boilerplate Generator",
"vsixId": "UnitTestBoilerplate.RandomEngy.ca0bb824-eb5a-41a8-ab39-3b81f03ba3fe"
},
{
"name": "Visual Studio IntelliCode",
"vsixId": "IntelliCode.VSIX.598224b2-b987-401b-8509-f568d0c0b946"
},
{
"name": "Visual Studio Spell Checker (VS2017 and Later)",
"vsixId": "43EA967E-0DE2-4136-8E52-C6DCFB5C2748"
},
{
"name": "Wix Toolset Visual Studio 2017 Extension",
"vsixId": "WixToolset.VisualStudioExtension.Dev15"
}
]
}
Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The Blinding Knife (Lightbringer #2), by Brent Weeks 22 Jun 2019 2:17 PM (5 years ago)

book cover The Blinding Knife continues the story of Kip the bastard, Gavin/Dazen Guile the genius god-like Prism and just about every other person alive a mere mortal. It is just as entertaining as the first book, although more focused on action than lore. A lot of new concepts are explored here, like colors that are not on the spectrum but can be drafted, other gods, other chromatic skills, but, as fantasy focused on little boys taught us, always unexplained, mysterious, too young to understand, people dying before they can finish their sentence, etc. I hate that cliché and I really hope people would stop using it so much. I am talking to you, Brent Weeks!

Anyway, I can't say anything more about the story or the style or the author than I did when I read the first book in the Lightbringer series. It's a continuous story, split in book sized volumes. I will start reading the next book in the saga momentarily. I recommend the writing style and I like the attention to detail and the lore, although after a while the boy genius recipe feels more and more like a Japanese manga and less than a real story.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Serializing FileInfo or DirectoryInfo with Newtonsoft Json in .NET Core 20 Jun 2019 12:58 AM (5 years ago)

The Problem


Phew, that's a mouthful. But the issue is that trying to serialize a FileInfo or a DirectoryInfo object with Newtonsoft's Json library in .NET Core fails with a vague exception:
Newtonsoft.Json.JsonSerializationException: Unable to serialize instance of 'System.IO.DirectoryInfo'.
at Newtonsoft.Json.Serialization.DefaultContractResolver.ThrowUnableToSerializeError(Object o, StreamingContext context)
at Newtonsoft.Json.Serialization.JsonContract.InvokeOnSerializing(Object o, StreamingContext context)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.OnSerializing(JsonWriter writer, JsonContract contract, Object value)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)

It doesn't say why it fails, just that a method called ThrowUnableToSerializeError threw um... an unable to serialize error?

The Cause


Looking at the Newtonsoft code, we eventually get to this piece of code:
// serializing DirectoryInfo without ISerializable will stackoverflow
// https://github.com/JamesNK/Newtonsoft.Json/issues/1541
if
(Array.IndexOf(BlacklistedTypeNames, objectType.FullName) != -1)
{
contract.OnSerializingCallbacks.Add(ThrowUnableToSerializeError);
}

Later, another piece of code will execute the serializing callbacks and throw the exception. We can get rid of this functionality, by using a custom contract resolver, like this:
var settings = new JsonSerializerSettings
{
ContractResolver = new FileInfoContractResolver()
};
 
private class FileInfoContractResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
var result = base.CreateContract(objectType);
if (typeof(FileSystemInfo).IsAssignableFrom(objectType))
{
result.OnSerializingCallbacks.Clear();
}
return result;
}
}

Yet now, when trying to serialize, we get the stack overflow exception described in the original Newtonsoft.Json issue. It stems from the difference between the .NET Framework implementation and the .NET Core implementation of ISerializable in FileSystemInfo, which in Core just throws PlatformNotSupportedException. It's still not clear why it goes to a StackOverflowException, probably some conflict with Newtonsoft code, but it's clear Microsoft does not intend to make these classes serializable. If you think about it, those classes suck for so many reasons!

The Solution


So, in order to solve it, we will use a custom JSON converter:
private class FileSystemInfoConverter:JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(FileSystemInfo).IsAssignableFrom(objectType);
}
 
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var jObject = JObject.Load(reader);
var fullPath = jObject["FullPath"].Value<string>();
return Activator.CreateInstance(objectType, fullPath);
}
 
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var info = value as FileSystemInfo;
var obj = info == null
? null
: new
{
FullPath = info.FullName
};
var token = JToken.FromObject(obj);
token.WriteTo(writer);
}
}
And we use it like this:
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new FileSystemInfoConverter()
}
};
var json = JsonConvert.SerializeObject(dir, settings);
var info = JsonConvert.DeserializeObject<DirectoryInfo>(json, settings);

Why FileInfo and DirectoryInfo suck


The answer of a senior developer to any question should be "Why?" or "Why on Earth or anywhere in the Solar System would you want to do a dumb thing like that?!?!". Why would you want to serialize a directory or file info object? The answer is that you should not. The info objects are defined by only one thing: a path, but they have so much baggage: properties that access the file system, unsafe methods, no interfaces or factory methods that can allow them to be mocked in unit tests. They might look like data objects, but they are not!

Imagine a scenario where you have a list of all the files in your drive. You enumerated them all and now you want to serialize them. Should the serializer save Exists or Length, for example? Because that means it will access the file system for each of them in the process of serialization, leading to a lot of work, propensity to access errors and so on.

Best practices say you should either use some model classes to move around data, like an empty FileSystemInfoModel with Type and FullPath and maybe Attributes or Size properties or whatever you want to save, but that you set yourself as a separate responsibility. And if you want to use the functionality of the Info classes, use System.IO.Abstractions or the new Core IFileProvider abstraction to get implementations of interfaces that you can mock in unit tests.

Tell me what you think.
Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The Crown Tower (The Riyria Chronicles #1), by Michael J. Sullivan 17 Jun 2019 1:21 AM (5 years ago)

book cover It seems there is a dedicated fan base for the Riyria series that so enjoy the setup that they ignore the quality (or lack thereof) of the writing. The writing style is amateurish at best, the characters are not fleshed out, yet the little building they get is contradicted with impunity whenever the plot requires it, the point of the story of the book has not been revealed after more than half of it, while the plot doesn't make any sense most of the time.

I am sorry, Michael J. Sullivan, but I could only read 60% of The Crown Tower before deciding I will not continue and I will not try any of the other books in the series. For the readers, imagine a story about implausibly competent youngsters that are forced to work together by a kindly old professor for no good reason other than they have to work together. Imagine a prostitute who decides to fight the world and open her own brothel, right across the street from her former pimp and king of the street, but the only concerns she has is how to bribe city officials to give her a business permit. After half of the book in which the characters have barely begun to do any of the activities listed above, nothing really happened, while hints have been placed to imply this is a world where magic exists, goblins, elves, dwarves, gods, yet none of them made an appearance.

I don't understand how stuff like that gets any awards. Is it just because they sell? Toilet paper sells and doesn't win anything! Just... ugh!

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The Fear Factor: How One Emotion Connects Altruists, Psychopaths, and Everyone In-Between, by Abigail Marsh 16 Jun 2019 12:28 AM (5 years ago)

book cover You remember when you had to write a paper for college and you had the thing that you wanted to say, but then your coordinator told you to make it a chapter, and then add others that are related for context? This book kind of feels like that. In English it is called The Fear Factor, but the Romanian edition calls it "Altruist or being good without reward" (my direct translation, as Good for Nothing didn't feel right, even if it is the title of the book in the UK), showing that even editors didn't really agree with the author on the right way to label it.

Overall, what Abigal Marsh tries to say is simple: our capacity to do good to others without expecting a reward stems from an ancient mammalian mechanism designed to bond mothers to children and it is triggered by our ability to empathize with the fear other feel, while regulated by a network of brain centers, mainly our amygdala and hippocampus using the oxytocin hormone. This takes the book through eight chapters, each kind of separate and which I liked in different measures. The ones describing carefully crafted experiments and their outcomes I liked best, the ones that felt like fillers or the ones affirming that correlation doesn't imply causation then proceeding in describing a lot of correlation less so.

Marsh goes out of her way to portray a positive image of humanity, where most people are generous, empathetic and altruistic. She describes people who aren't capable of it - psychopaths and their amygdala dysfunction, people on the other side of the curve - superaltruists who don't care to whom they do good, they just do it, goes to very interesting experiments and comes with theories about how and why altruism, fear and empathy work. Her conclusion is that our focus on negative things makes us falsely believe things are getting worse, people less trustworthy, when the actual opposite if overwhelmingly true.

Bottom line: I liked the book, but some of the chapters felt forced. I didn't really need the exposition of her beach trip to save the turtles or how much she feared and then appreciated the help of a random guy who looked like a hood thug. Most of the information interesting to me was concentrated in the first chapters, while the last, explaining what to do to become more altruistic and how that improves our well being and filled with international statistical charts on altruism I could have done without entirely. It's not that it wasn't correct or well written, it just felt like an add on that had little to do with the book or, worse, was there just to fill up space.

If you search on TED Talks, you will see the author have a talk there titled Abigail Marsh: Why some people are more altruistic than others.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

How to timeout a task AND make sure it ends 14 Jun 2019 6:03 AM (5 years ago)

This post starts from a simple question: how do I start a task with timeout? You go to StackOverflow, of course, and find this answer: Asynchronously wait for Task<T> to complete with timeout. It's an elegant solution, mainly to also start a Task.Delay and continue when either task completes. However, in order to cancel the initial operation, one needs to pass the cancellation token to the original task and manually handle it, meaning polluting the entire business code with cancellation logic. This might be OK, yet are there alternatives?

But, isn't there the Task.Run(action) method that also accepts a CancellationToken? Yes, there is, and if you thought this runs an action until you cancel it, think again. Here is what Task.Run says it does: "Queues the specified work to run on the thread pool and returns a Task object that represents that work. A cancellation token allows the work to be cancelled." and if you scroll down to Remarks, here is what it actually does: "If cancellation is requested before the task begins execution, the task does not execute. Instead it is set to the Canceled state and throws a TaskCanceledException exception". You read that right: the token is only taken into account when the task starts running, not while it is actually executing.

Surely, then, there must be a way to cancel a running Task. How about Task.Dispose()? Dispose throws a funny exception if you try it: "System.InvalidOperationException: 'A task may only be disposed if it is in a completion state (RanToCompletion, Faulted or Canceled).'". In normal speech, it means "Fuck you!". If you think about it, how would you abort a task execution? What if it does nasty things, leaves resources occupied, has to clean up after it? The .NET team took the safe path and refused to give you an out of the box unsafe cancelling mechanism.

So, what is the solution? The recommended one is that you pass the token to all methods that can be cancelled and then check inside if cancellation was requested. Of course this only works if

  1. you control what the task does
  2. you can split the operation into small chunks that are either executed sequentially or in a loop so you interrupt their flow
. If you have something like an external process that is being executed, or a long running operation, you are almost out of luck. Why almost? Well, CancellationSource or CancellationToken do not have events, but the token exposes a "wait handle" that you can wait for synchronously. And here it gets funky. Check out an example of a method that executes some long running action and can react to token cancelling:
/// <summary>
/// Executes the long running action and cancels it when needed
/// </summary>
/// <param name="token"></param>
private void LongRunningAction(CancellationToken token)
{
// instantiate a container and keep its reference
var container = new IdentificationContainer();
Task.Run(() =>
{
// wait until the token gets cancelled on another thread
token.WaitHandle.WaitOne();
// this will use the information in the container to kill the action
// (presumably by interrupting external processes or sending some kill signal)
KillLongRunningAction();
});
// this executes the action and populates the identification container if needed
RunLongRunningAction();
}
This introduces some other issues, like what happens to the monitoring task if you never cancel the token or dispose of the cancellation source, but that's a bit too deep.

In the code above we get a sort of a solution if we can control the code and we can actually cancel things gracefully inside of it. But what if I can't (or won't)? Can I get something that does what I wanted Task.Run to do: execute something and, when I cancel it, stop it from executing?

And the answer, using what we learned above, is yes, but as explained at the beginning, it may have effects like resource leaks. Here it is:
/// <summary>
/// Run an action and kill it when canceling the token
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="token">The token</param>
/// <param name="waitForGracefulTermination">If set, the task will be killed with delay so as to allow the action to end gracefully</param>
private static Task RunCancellable(Action action, CancellationToken token, TimeSpan? waitForGracefulTermination=null)
{
// we need a thread, because Tasks cannot be forcefully stopped
var thread = new Thread(new ThreadStart(action));
// we hold the reference to the task so we can check its state
Task task = null;
task = Task.Run(() =>
{
// task monitoring the token
Task.Run(() =>
{
// wait for the token to be canceled
token.WaitHandle.WaitOne();
// if we wanted graceful termination we wait
// in this case, action needs to know about the token as well and handle the cancellation itself
if (waitForGracefulTermination != null)
{
Thread.Sleep(waitForGracefulTermination.Value);
}
// if the task has not ended, we kill the thread
if (!task.IsCompleted)
{
thread.Abort();
}
});
// simply start the thread (and the action)
thread.Start();
// and wait for it to end so we return to the current thread
thread.Join();
// throw exception if the token was canceled
// this will not be reached unless the thread completes or is aborted
token.ThrowIfCancellationRequested();
}, token);
return task;
}

As you can see, the solution is to run the action on a thread and then manually kill the thread. This means that any control of where and how the action is executed is wrestled from the default TaskScheduler and given to you. Also, in order to force the stopping of the task, you use Thread.Abort, which may have nasty side effects. Here is what Microsoft says about it:



Bummer! .NET Core doesn't want you to kill threads. However, if you are really determined, there is a way :) Use ThreadEx.Abort(thread);


Bonus code: How do you get the cancellation token if you have the task?
var token = new TaskCanceledException(task).CancellationToken;
It might not help too much, especially if you want to use it inside the task itself, but it might help clean up the code.

Conclusion


Just like async/await, using the provided cancellation token method will only pollute your code with little effect. However, considering you want to use a common interface for the purpose, use RunCancellable instead of Task.Run and handle the token manually whenever you feel resources have been allocated and need to be cleaned up first.
Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The Black Prism (Lightbringer #1), by Brent Weeks 10 Jun 2019 10:58 AM (5 years ago)

book cover If there is something that went wrong with this book, then it has to be the cover on Goodreads: a hipster young man with dark hair, a goatee and a pointlessly fancy dagger, which has almost no connection to the story. Instead, try the one on Amazon, which at least doesn't offend. And that concludes what went wrong with The Black Prism! I actually liked it a lot.

The story feels like so many other young adult fantasy novels, with the young child with important ancestry that had a bad childhood and is suddenly thrown in a world of magic, war and intrigue, but the characters are fresh, their motivations carefully crafted with respectful attention to detail. The world building follow suit, with a novel magic system, a deep history and not all yet revealed. The writing is good, too. After reading this first book in the Lightbringer saga, I immediately felt the need to read the next one in the series. But there is a dark side to all this, too, as The Black Prism isn't a stand alone book. If you like it, you will have to read it all.

Bottom line: I really liked the love Brent Weeks weaved in his book. This is not one of those "give me your money now" kind of work, it's something that has value and beauty. It's not the greatest book ever written, but what book is? For the fantasy genre, it was pretty entertaining (and big!).

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The Rise and Fall of the Dinosaurs: A New History of a Lost World, by Stephen Brusatte 6 Jun 2019 12:31 AM (5 years ago)

book cover When I was a child I was obsessed with dinosaurs. I was going through the pages of the Zoological Atlas again and again, looking at the big lizard like monsters and memorizing all of their names. If I would have had access to a book like Steve Brusatte's, I would have probably become a paleontologist! By that I mean that the book is good... for an eight year old or for somebody who is already giddy with the prospect of reading about their favorite subject. Now, decades later, I really made an effort to enjoy The Rise and Fall of the Dinosaurs, but it had no wow factor anymore. The plethora of names that I haven't known about when I was smaller than a toddler did not bring me joy. Hearing about feathered dinosaurs and what is the most likely reason feathers evolved at all or how they dinosaurs turned into their modern day form - the birds, even the tales about the dwarf dinosaurs found in my own homeland merely made the book bearable. Having a long chapter focused on Tyrannosaurs and having my book reader stop after each T. in T. Rex didn't help either.

My verdict, therefore, is that it is a good history book. It is well written and the passion of the author is palpable and admirable. Yet, unless you either know nothing about dinosaurs or you already love them, you won't read anything really amazing or new. It is, quite literally, a history of how dinosaurs rose and fell and it feels like reading a history book. Somehow, I was expecting more, something that explored in depth a lost world, but in fact it only made clear how little we know and how tiny chances are that this will ever change. Instead of the feel of a lush green world where danger loomed and beauty abounded, I got a dry dusty look at people digging in rocks for small hints of that world. It was like looking at shadows and trying to figure out what made them.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Malice (The Faithful and the Fallen #1), by John Gwynne 31 May 2019 11:37 AM (5 years ago)

book cover Have you ever found a book so bland that you just refused to continue reading it? To me it happens rarely, but it did with Malice, by John Gwynne. And I do feel a sense of loss, since the reviews I've seen are all so overwhelmingly positive. Maybe if I would have just read a few more formulaic chapters I would have gotten to the part when something, anything, happens.

But no, I do have a lot of books to read and I am not going to waste my time reading about another child who wants to be a hero, but he's weak and bullied, another large blacksmith who was once a soldier, another pair of good and evil gods and their minions, noble savages, strong princesses, evil viziers and so on and so on. After several chapters all I got was a bunch of people in different contexts, each with their own names, friends, family, dreams, history and narration. Whenever I thought something would happen, another character with a silly name came along to perform whatever ritual is assigned to its cardboard role. Confusing and boring as hell.

Bottom line, I couldn't even begin to finish it. I probably read about 10-15% and gave up.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Foundryside (Founders #1), by Robert Jackson Bennett 29 May 2019 10:14 PM (5 years ago)

book cover Much like City of Stairs, Foundryside is a steampunk story set in a world where power resides in the hands of a few "houses" who use a magical programming language to alter reality. The lead character is also a girl, the plot also revolves around someone who wants to abuse ancient magic to rule the world and the state of knowledge is yet again recovering from a major catastrophe that veiled the past. Yet with all this, I liked the book less.

Just as the story moved from a more mystical setting to a more rational, scientific one, so did Robert Jackson Bennett's writing turned more formulaic. It's like he took something he had success with and applied the same exact formula, with some improvements related to what people want to read. As a result, the characters are less mysterious and more cardboard, the hints peppered around the story for the reader to glimpse where it is going are way too revealing (something that bothered me a little in City of Stairs, too, but here it was just too obvious). But what bothered me most was that the characterization: some were way too modern, way too educated or philosophical, considering their background, and the divide between good and evil was so obvious, back to the annoying cliché where the good characters are principled and loyal and intelligent and their opponents are insane, frustrated and ugly.

Bottom like, I liked the book, but I feel like Foundryside is a step back for Bennett. It was harder to empathize with the heroes and almost impossible to do so with the antagonists. The story felt recycled from a basic idea scrived with the same recipe as City of Stairs, but more lazily.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Styling Angular Material tooltips 29 May 2019 3:50 AM (5 years ago)

This should be a simple question with a simple answer, but if you google for Angular Material tooltip styling or length or width you get different answers that are not always complete or even correct. The problem: you have something like <a matTooltip="some message" matTooltipClass="myTooltipClass" ... as per the examples easy to find. However, it doesn't seem to be working. The styling for myTooltipClass does not apply. Here are some points to check off while searching for the problem:

  1. Check whether myTooltipClass is defined in the component or the global CSS file. It should either be in the global CSS file (so it applies to everything) or your component should declare encapsulation: ViewEncapsulation.None
  2. Check the declaration of the class is specific enough. DO NOT use !important to fix this, although it would work. Try something like this: mat-tooltip-component .mat-tooltip.myTooltipClass {...}

To see if the class is applied, set the background-color property to red or something. If the class applies, you managed to define it correctly. If it applies partially, it's not specific enough. To change the width, use max-width. To make the tooltip wrap use white-space: wrap; and word-wrap: break-word;

As a reference, this is how the HTML looks for a rendered tooltip:
<div class="cdk-overlay-container">
<div class="cdk-overlay-connected-position-bounding-box" dir="ltr" style="top: 0px; left: 0px; height: 100%; width: 100%;">
<div id="cdk-overlay-1" class="cdk-overlay-pane mat-tooltip-panel" style="pointer-events: auto; top: 8px; left: 417.625px;">
<mat-tooltip-component aria-hidden="true" class="ng-tns-c34-15 ng-star-inserted" style="zoom: 1;">
<div class="mat-tooltip ng-trigger ng-trigger-state" style="transform-origin: left center; transform: scale(1);">Info about the action</div>
</mat-tooltip-component>
</div>
</div>
</div>
Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

City of Stairs (The Divine Cities #1), by Robert Jackson Bennett 25 May 2019 6:42 AM (5 years ago)

book cover What makes a good story? It has to be the telling or writing style, of course, but then there are other factors: believable and sympathetic characters, an interesting idea, a tight plot, good world building, entertaining scenes. I am happy to report that City of Stairs aced everything! I haven't heard of Robert Jackson Bennett before, but I am sure to remember his name now. The first book in a trilogy, City of Stairs wasn't just blessingly self contained, but also made me happy to have following books to continue the story.

The main character is a woman who does everything from conviction, care for others and most of all her own intelligence and effort, not because of her gender. The story is a detective story, set in a fictional preindustrial almost steampunk world where gods recently existed until people killed them. It is a book of mystery, intrigue, politics, detective like investigations, spirituality and magic, but held tight around a solid core of whodunit and great character and world building. It reminded me of the wonder I felt when starting reading Brandon Sanderson's books.

Bottom line: not the greatest work of literary fiction that ever existed, but I couldn't find any fault with it. Per my definition, it was a perfect book.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Microcosm: E. Coli and the New Science of Life, by Carl Zimmer 22 May 2019 9:11 PM (5 years ago)

book cover At first I thought this will rehash the same information I've got from books I've read recently: how microorganisms are everywhere and how they live in symbiosis and cooperation with themselves, plants and animals, how the imbalance in the ecosystem is what we normally get to call disease, maybe some epidemics stories and so on. Instead I've got an ode to E. Coli and how studying it for decades has revealed to us in details the way life works. It's Carl Zimmer's multifaceted portrait of a single species of bacteria (although that's a lot of bacteria, if you get to read the book).

Well written even if more technical than the average popular science book, Microcosm explains how heredity works, DNA, RNA, proteins, amino acids, bacteria, biofilms, archaea, eukaryotes, viruses, plasmids, mutations, evolution, resistance and so on until it gets to creationists, genetic engineering and exobiology, all while following our scientific history built on the study of this one bacteria, the workhorse of microbiology. In fact, it is so focused on E. Coli, that it snubs most other bacteria, it talks little of epidemics or the microbe ecosystem and instead focuses on how things work. It's like an engineer's view on how life works, or a user's manual for Escherichia coli.

I liked the book and I will probably read more from the same author. I mean, if he writes a book per microbe species I could read his books until one of us dies :) I highly recommend it not only for its subject, but also for how it makes clear the inner workings of life and evolution. I would have loved to read this book when I was 12.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The Faded Sun Trilogy (The Faded Sun #1-3), by C.J. Cherryh 18 May 2019 9:05 AM (5 years ago)

audiobook cover To be honest, I've reached the beginning of the third book in The Faded Sun Omnibus and I've decided to stop.

It was 1978. Religious people living in the desert under strict rules and brandishing swords were still cool and not considered terrorists. C.J.Cherryh decides to write a story about a fierce warrior race that works in the employ of others to wage space war, driven by a very exact culture that emerged in the desert. They carry black veils that only let show their eyes and are very partial to rituals and hand to hand combat. No wonder humans kicked their asses, but even they are terribly anachronistic. They have waged 40 years of war with the humans, under the contract of the Regul, fat immobile and amoral beings that care only for their own tribe's well being.

Reminds you of Dune, the Freemen and the Harkonen? Well, this is where the similarity ends. Where Dune was deep, these three books are tediously drudging through all kinds of futile rituals and each character is painfully introspective, to the point that tough warriors bred for battle are recognizing and thinking about their feelings of fear all the time. Worse, nothing really seems to be happening. It takes a book for a ship to get to its destination.

And the book has aged poorly, even when in the whole thing there are maybe a page of technical descriptions, probably less. There is no mention on what makes the ships run, what types of weapons are used, how computers work, etc. A ship just "fires" and it is never even described in what way.

But the ultimate sin is how little sense it makes. I mean, this is the age of Star Wars, where... errr... people on starships wage battles with swords... OK, the author isn't the only one who screwed stories up, but the Mri are presented as this scourge of the battles, yet they don't know technology or can even read or write, they are appalled by mass warfare and prefer hand to hand combat (like real men!) and are strict in what they are allowed to do, know or even think. It's like giving space weaponry to the Flinstones. OK, you get the Jetsons, but how is that supposed to be terrifying or a match to the voracious human penchant for mass destruction? And there is more. After 40 years, we learn that people have never captured Mri alive, never studied them. The Mris themselves are accompanied by huge bear like semitelepathic animals that they never name or even know how they reproduce. Unlike Frank Herbert, who was obsessed with ecology, Cherryh feels no need to explain how a species of huge carnivores exists on harsh desert planets that are almost devoid of life and water or how three completely different species can share air and food, or how the animals and plants on a different planet are the same as from one that lay 120 planets away, or how language and culture stays the same for 80000 years. A lot of things just don't make sense, including the story's main premise, which is the fear that humans and Regul alike carry for the Mri.

Bottom line: if it were nice to read at least, I would have given it a shot, but after two books of people thinking in fear about what others are thinking of them, I gave it up. It was just tediously boring.

Now, Cherryh was at the beginning of her illustrious career and there are books written by her that I liked. I just hated this one.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

The City in the Middle of the Night, by Charlie Jane Anders 11 May 2019 3:54 AM (5 years ago)

book cover The City in the Middle of the Night reminded me of Octavia Butler's Xenogenesis, only way lighter. The same female centric focus, the slight weirdness of descriptions and feelings that comes from a truly different perspective. Charlie Jane Anders describes a planet far away from Earth, a colony that devolved after humans reached the planet until it got to feudal levels of government and technology. The planet is tidally locked, so people live on the narrow edge that separates frigid night and scorching day. There are some aliens there as well. Pretty cool story and concept, so much so that I hated it when the book ended and it was NOT a trilogy or a saga or whatever. Hard to please me, right?

The writing style isn't on par with the richness of the concepts, though, and I was also thrown off often by gaps in the understanding of science, social norms and even sensory descriptions. Yet once I understood the author is a transgender woman with sensory integration disorder, it started to make sense. The main characters are all women. There are no real romantic or familial relationships between them, unless counting the fact that they are always feeling things strongly and lying together in beds without doing anything. The lack of sexuality in the novel is refreshing but going a long way in the other direction until it feels eerie. And they often react physically or mentally in such overblown ways that it's hard to empathize. Stuff like someone saying something and they suddenly go to a corner to heave, or having seen someone smile or being touched in a certain way just short circuits their brain. There are a lot of leftover threads in the book, things that get partially described and you just wait for them to be explained later on and they just don't. Also the mix of first person perspective for Sophie and third person for everybody else is strange and forces one of the characters as the main one, even if maybe a reader would relate better with somebody else.

So I had difficulty in rating this book. I would give an excellent rating to the world building and the concepts presented there, but an average on characterization (even if most of the book is about what characters do and think and feel). I would rate some descriptions of internal struggle and emotion as great, but others really lame, especially when it comes to characters who seem to be designed to be thrown away later on. The writing style is not bad, but not great either. It's a mixture of brilliance and average that is hard to reconcile into a single metric. I mean, I could describe the entire plot of the book in two paragraphs; the rest is just people bumbling around trying to make sense of the world and themselves. No character has a real back story, except a few defining moments that feel pulled out of a hat, and they are understandably confused all the time. Who are their parents? Everybody in the book is an orphan. Why so many descriptions of invented food if does nothing for the plot, yet no sex, only a rare and weird longing sort of platonic love? Why is everybody so casually violent, yet so disgusted with violence in their inner thoughts?

It seems to me that this is a book that only some will be able to connect to (the others will get delirious and murderous). I liked the ideas, I liked the characters, it's just that they are coming from nowhere and ultimately going nowhere.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Good Germs, Bad Germs: Health and Survival in a Bacterial World, by Jessica Snyder Sachs 5 May 2019 7:03 AM (5 years ago)

book cover The book might put you off at the beginning, as it starts with a no bullshit nomenclature chapter. It basically says: "This is how I am going to call things in this book and if you don't like it, talk to people who actually care about semantics". The rest of the book continues with the same directness and I believe it is one of the works' best qualities.

Good Germs, Bad Germs starts like a few other books on the subject I've read recently, with a short history of how people have looked upon disease and its causes: Hippocrates' humors, the (all bad) germ theory, vaccines, antibiotics, the bad antibiotics and the good germs, modern understanding of immunity. And yet this is just the first half of the story. The rest is about new ideas, actual therapies and studies, real life cases and attempts to bring this new knowledge into the public domain.

I really liked the book. It's easy to read, easy to understand. Less of the story-like or anecdotal writing style of some other works and more to the point. I also liked that it doesn't take sides: one therapy has to go through wholly unreasonable FDA hoops to be allowed to even be tested in humans, the author points both positive and negative aspects of being prudent. Is it ridiculous that the lack of communication between American hospitals hides invisible epidemics that then get reported by Canada or Europe and end back into the States' headlines as foreign diseases? Jessica Snyder Sachs just reports on the facts, letting the reader draw their own conclusions.

Bottom line: I thought it would be just a repeat of the same information I've become familiar with lately, yet it was not only a different way of tackling the same subject, but also a lot more information about actual attempts to use it in real situations. I recommend it to anyone trying to understand how we stand in this coevolution with the microbes living inside and outside us.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?

Knights of the Borrowed Dark (Knights of the Borrowed Dark Trilogy #1), by Dave Rudden 30 Apr 2019 1:46 PM (5 years ago)

book cover Knights of the Borrowed Dark is a typical fantasy story filled with tropes like: "the one", "son of..." (or "noble family" or "everybody is related to everybody"), "secret war (for no good reason)", "light versus dark", "evil must be fought with swords", "no one tells you anything, even if it makes no sense", "dark king" and so on. The main character is a Mary Sue, an orphan who doesn't know his parents and has lived his entire life in an orphanage, but somehow is a balanced, well read individual who favors rationality to emotion, yet has no problem using both. Add the trope of trilogy to this and you have a complete picture.

Now, does that mean I was not entertained? Nope. It was all fun and games and I've finished the book in a day, yet I can't but be disappointed in both the formulaic nature of the story and the fact that I liked it anyway. The bottom line is that Dave Rudden writes decently and has enough skill and humor to make the same story you've read or seen a dozen times already feel pleasant. So read it, if you like that kind of thing, but don't expect anything above ordinary.

Content taken from Siderite's blog

Add post to Blinklist Add post to Blogmarks Add post to del.icio.us Digg this! Add post to My Web 2.0 Add post to Newsvine Add post to Reddit Add post to Simpy Who's linking to this post?