and has 0 comments
Villains by Necessity is not a masterpiece of literature, but it is a fun fantasy book that doesn't feel the need to be part of a trilogy or take itself too seriously. Perfect for when you want to pick up a book because you are tired, not because you want to work your brain to dust. First work of Eve Forward, it is rather inconsistent, moving from silly to dead serious and back and making the heroes of the story oscillate between pointlessly evil and uncharacteristically good.

The best part of the book, though, is the concept. The world enjoys an age of light and good after a bitter war that saw all the forces of darkness and evil be defeated. The world is filled with happy people, no conflict, beautiful weather, lush vegetation. In a word, it is fucking boring. An unlikely party of evildoers gets together to save the world by bringing darkness back!

Alas, it was a concept that was not really well used. The characters, borrowed from classical fantasy, are "evil" by their professions only, but not by behaviour. Sam is an assassin, but he doesn't enjoy the suffering of his victims and is proud of his prowess. Archie is a mischievous thief, but other than that he is an OK fellow. Even Valerie, the dark sorceress, eats sentient beings just because it is her race's culture and her evil is more often artificial. Not to mention Blackmail, who acts as the classic stoic hero. Similarly, the forces of good are blood thirsty thugs that want to either kill everything dark or brainwash them, as a humane solution. This basically makes our heroes... err... heroes, not villains, and viceversa.

Now, the book wasn't bad. The style was amateurish, but it is Eve Forward's first book, after all. I could read it and I got caught by the story. I was more attracted to the original concept, though, and I was very curious how it would go. It is so difficult to present bad people as the protagonists, I know, because many people, including writers as they write, want them to be redeemed somehow. In the end, the moral of the story - excruciatingly laid out in a few paragraphs that shouldn't have existed - felt really heavy handed and simplistic. Ok, good people can do bad things and bad people can do good things, but it is important to explore what makes them good and bad, not just lazily assign them dark fantasy classes and be done with it.

Bottom line: fun read, but nothing special.

and has 0 comments
This is how reality stands right now: even if the danger of an asteroid hit is great, the risk of one hitting is small. That means that they hit (very) far apart and cause a lot of damage. Now, all governments in the world are run by politicians, who are by their very nature bureaucrats. They are reactive, not proactive, and they have insulated themselves from responsibility by manipulating laws and creating committees and departments that they can behead at any time, as they keep their fat asses on their chairs of power. This is not a rant, it's just the ugly truth, evolving, but never really changing since we were barely smarter than monkeys.

The logical conclusion of these facts is that politicians will not do anything about asteroids until we are hit by one. Even worse, since the probability that a really big one will hit without us knowing in advance has been reduced by space advances, the asteroid that will hit us will probably be small. The Tunguska and the Chelyabinsk events, real things that happened, changed nothing. The one that is going to change anything will be when something similar happens on top of a city.

This is not a doomsday prophecy, either. The probability that this will happen is extremely small. First of all the asteroid has to be small enough and/or fast enough so that we don't detect it in time. Then it has to hit at a certain angle to not be deflected by the atmosphere. Then it has to reach a populated area, which one would think is simple, since we can't seem to be able to fart without someone smelling it, but in truth, with the oceans and the human propensity of congregating for no good reason, it is less probable. However, with enough time, even a small probability becomes certainty.

So, the scenario goes like this: we all pretend to care, but we don't. We want less taxes, not asteroid protection. Politicians use our shortsightedness and our greed to enhance their own and do nothing. Then an asteroid hits, causing massive damage, death and loss of property. This is the moment when something happens. They implement new laws, launch asteroid defense programs, create new departments and committees. But, since the probability that an asteroid hits is small, the hype will fade, the budgets with it, politicians will rotate, people will forget. By the time the next asteroid hits, no one will be prepared for it any more than for the previous one.

In the end, the only things that ever made a dent in the probability that something will hurt us as a species or even as a larger group were technological. Not technology per se, just its price. Just more scientists with cheaper tech getting more done. When space launches become cheaper, satellites smaller, we can do more with them at the same relative price. That is why now we are discovering millions of asteroids in the Solar System, not because of some sort of scientific awakening. It's cheaper, probably as cheap as it was for amateur astronomers to buy telescopes in 1801, when Giuseppe Piazzi discovered the first asteroid, Ceres. I just hope this all gets cheap enough fast enough so we can do something by the time the big asteroid is coming. Well, if we don't destroy ourselves in some other way by then.

I know I'm a month late, but Happy Asteroid Day!

and has 0 comments
I needed to get all IP addresses in a range, so I applied the mask to my current IP and started to work through the minimum and maximum values of bytes to get the result. I had a code that looked like this:
for (var b = min; b <= max; b++) { //do stuff }
where min was 0 and max was 255.

The expected result: all values from 0 to 255. The result: infinitely running code. Can you spot why?

Yes, when min and max are bytes, b is also a byte, so when it gets to 255 and does b++ the value becomes 0 again. Fun, eh?

and has 2 comments
There are several stories happening at the same time in The White Luck Warrior, with almost no direct connection between them. There is the Great Ordeal, advancing slowly towards Golgoterath while being besieged by hordes of Sranc, also containing the story of this kid prince forced to march with it; then there is the palace life, with Esmenet left to rule the empire while Kellhus is away, while various factions are ready to take advantage of the lack of man power of the leadership and her half Dunyain children prove to be either insane or really insane; there is the trek of Achamian in search of the origin place of Kellhus. Among these there is a vague and a few paragraphs long subplot of The White Luck Warrior, a mysterious figure that seems to know all of its future, making him an automaton, I guess and some bits about the Fanim.

Why the smallest and insignificant portion of the book gave its title I do not know, but remember that the first book in the Aspect-Emperor series was called The Judging Eye, which is most prominently used or described in this volume. By far the most interesting and captivating storyline is that of Achamian, although I have to say that the logistics of long duration travel within enemy territory and the psychological factors involved seemed to me poorly described by Bakker.

What I knew will happen happened. I finished the book before the third volume in the series was released and now I am in withdrawal pains. That proves that the book captivated me. At very few moments I felt the need to "fast forward" and, considering the amount of distraction and that I had resolved to draw this book out a little bit in the hope that the third volume would be released, I finished it rather quickly.

Even if enjoyable, to me it felt more like a filler. I couldn't empathize with Esmenet or any of her demented children, nor could I care less what happened to Maithanet, who is one of the less fleshed out characters in the book. Similarly, the Sorweel story arch described a confused and frustrated teen, which was relatable, but uninteresting as a character. Unlike in the first four books, Kellhus sounds less godly and dominating and is mostly relegated to a minor role in the overall story. No, the most interesting characters and storyline revolve around Achamian, Mimara, The Captain and the mysterious Cleric, plus any of other members of the crazy bunch of mercenaries known as The Skin Eaters. And they just walk and walk and walk, only to end the book in a cliffhanger. While I await eagerly the sixth book, I have my misgivings and fears that it will not be as good as this one, just as this one felt a little bit short of the first.

and has 1 comment
This post will discuss the possibility of creating an SQL injection using the name of a parameter.

We have known about SQL injection since forever: a programmer is constructing an SQL command using user provided information and some malicious hacker inserts a specially crafted string that transforms the intended query into something that returns the content of a user table or deletes some data on the server. The solution for this, in the .NET world, is to use parameterized queries. Even if someone dynamically creates an SQL query, they should use parameter names and then provide the parameters to the SQL command. The idea behind this is that any value provided by the users will be escaped correctly using parameters. Today I found that this solution works perfectly for parameter values, but less perfectly for parameter names. Try to use a parameter with a name containing a single quote and you will get an error. Let's analyse this.

Here is a piece of code that just executes some random SQL text command, but it also adds a parameter containing a single quote in the name:
using (var conn = new SqlConnection("Server=localhost;Database=Test;UID=sa;Trusted_Connection=True;"))
{
conn.Open();
using (var comm = new SqlCommand())
{
var paramName = "a'";

comm.Connection = conn;

comm.CommandText = "SELECT 1";
comm.Parameters.Add(new SqlParameter(paramName, SqlDbType.NVarChar, 100)
{
Value="text"
});

comm.ExecuteNonQuery();
}
conn.Close();
}

As you can see, the text content of the SQL command is irrelevant. the name of the parameter is important and for this I just used a single quote in the name. Running SQL Profiler, we get this query string that is actually executed:
exec sp_executesql N'SELECT 1',N'@a'' nvarchar(100)',@a'=N'text'
In this example the name of the parameter is properly handled in the string defining the name and type of the parameters, but it is NOT escaped during the parameter value declaration. A small change of the code with paramName="a='';DELETE * FROM SomeTable --" results in an interesting query string in the SQL Profiler:
exec sp_executesql N'SELECT 1',N'@a='''';DELETE FROM SomeTable -- nvarchar(100)',@a='';DELETE FROM SomeTable --=N'text'
Strangely enough, when inspecting the SomeTable table, the values are still there, even if copying the text into SQL Management Studio actually deletes the values. A similar construction using stored procedures leads to a completely legal SQL that is recorded by SQL Profiler, but it doesn't really do anything:
using (var conn = new SqlConnection("Server=localhost;Database=Test;UID=sa;Trusted_Connection=True;"))
{
conn.Open();
using (var comm = new SqlCommand())
{
var paramName = "a='';DELETE FROM SomeTable --";

comm.Connection = conn;
comm.CommandText = "DoTest";
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter(paramName, SqlDbType.NVarChar, 100)
{
Value="text"
});

int k = 0;
using (var reader = comm.ExecuteReader())
{
while (reader.Read()) k++;
}
Console.WriteLine(k);
}
conn.Close();
}
... with the resulting SQL:
exec DoTest @a='';DELETE FROM SomeTable --=N'text'

I have demonstrated a method of sending a maliciously crafted parameter name to the SqlCommand class and managing to send to the SQL Server a query that should achieve a destructive result. So why doesn't it actually do anything?

The explanation is in the EventClass column of the SQL Profiler. While a normally executed SQL command (let's say from SQL Management Studio) has event classes of SQL:BatchStarting and SQL:BatchCompleted, the query resulting from my attempts have an EventClass of RPC:Completed. It appears that the RPC method of sending queries to the SQL Server doesn't allow for several commands separated by a semicolon. The result is that the first command is executed and the rest are apparently being ignored. The TDS protocol documentation shows that the RPC method is a system of executing stored procedures by sending a binary structure that contains stuff like the name of the procedure, the parameters and so on. Since an SQL text is actually translated into a call to the sp_executesql stored procedure, RPC is used for both types of SqlCommand: Text and StoredProcedure.

I don't have the time to explore this further, but I wonder if this can be used for any type of SQL injection. To make sure, try to check the names of the parameters, if they come from user input.

and has 0 comments
As you know from the previous post, I am working on a network monitor application that displays information about the devices in my local network. For that I need to ping them to see if they are available. The simplest solution is to use the out-of-the-box solution of System.Net.NetworkInformation.Ping. It was no little shock to stop debugging my application and find myself facing a Blue Screen of Death, you know, the blue thing with white text that means everything is fucked, with the error message PROCESS_HAS_LOCKED_PAGES.

Googling around I found that the problem is, indeed, coming from the Ping class. Since the application is full with BackgroundWorkers and threads and stuff like that, Ping was actually the furthest from my mind. I even suspected that my laptop is dying. Microsoft, blessed be their hearts, not only did they ignore the bug, which is logged on their Connect site, but they eventually closed it with no resolution. Therefore I resolved to find a solution by myself.

I tried to see if there are any alternatives to the Ping class. I downloaded two implementations: PingWin and Pinger, both seemingly functional. PingWin, was using the Windows IcmpSendEcho function, via Pinvoking icmp.dll. Pinger was using raw sockets. After replacing the Ping class with a class with the same members and properties I was using, but wrapping PingWin, I checked to see if the application was behaving as expected, then stopped debugging. Again I got the BSOD, suggesting what I had read from other people with the same problem, that it is not a .NET managed code issue, but instead it is a problem stemming from the lower level code in the Windows operating system.

As noted in the IcmpSendEcho documentation, there are two implementations, one included in Icmp.dll, which comes from Windows 2000, and one included in Iphlpapi.dll, which comes included in Windows XP and later. Replacing the target of the DllImport attribute to Iphlpapi.dll resulted in an application that works exactly the same, crashing just the same. Looking at the source code of the Ping class, I see that it is using the same mechanism, calling the functions exported by Iphlpapi.dll.

Using the raw socket implementation did not cause a crash, though, so I can recommend you use it, if you can, since everything using Iphlpapi.dll or Icmp.dll seems to be affected by this. There are some limitations to using raw sockets in Windows, but I think ICMP may be exempt. You should research some more if you want to use it in an application that must work in all kind of security environments.

In this post I will discuss the following:
First, let's discuss the project that I was working on which led to this work. I wanted to do a program that manages the devices on my network. There is a router and several Wi-fi extenders, all of them with an HTTP interface. I wanted to know when they are reachable through the network, connect to the HTTP interface and gather data or perform actions like resetting the device and so on. In order to see if they were reachable, I was pinging them every second, so I thought I would like to see the evolution of the ping roundtrip time in a visual way, therefore the chart.

All of the values that I was displaying and all the commands that were available on the interface were using MVVM, the pattern developed by Microsoft for a better separation of presentation and data model. MVVM presents some difficulties, though, since most of the time directly getting the data and displaying it is more efficient and easier to do. It does allow for fantastic flexibility and good maintenance of the project. So, since I am a fan, I wanted to draw this chart via MVVM as well.

The MVVM chart


In order to do that I needed a viewmodel that abstracted the chart. Since I had several devices, each of them with a collection of pings containing the time of the ping and a nullable rountrip value, it would have been way too annoying to try to chart the values directly, so on the main viewmodel I created a specific chart model. This model contained a BindingList of items of various custom types: GraphLines, GraphStarts and GraphEnds. When the ping failed I added an "end" to the model. When the ping succeeded after a fail, I would add a "start". And when the ping was continuously successful, I would add a "line" connecting the previous ping to the current one.

So, in order to draw anything, I used a Canvas. The Canvas is a very simple container that can position stuff at absolute values. The first thing you need to realize is that it is not a vectorial type of container, so when you draw something on a small canvas and you resize the window, everything remains at the same position and size. The other thing that quickly becomes apparent is that there are various ways of positioning objects on the Canvas. The attached properties Canvas.Top, Canvas.Left, Canvas.Bottom and Canvas.Right can define the position of TextBlocks or other elements, including Rectangles and Ellipses. Lines, on the other hand, whether simple Line objects or something more complex, like Paths, are positioned using Points and X,Y coordinates. This would come to bite me on the ass later on.

WPF is very flexible. In order to add things to a Canvas, all one needs to do is to declare an ItemsControl and then redefine the ItemsPanel property to be a Canvas. The way objects are represented on the Canvas can be defined via DataTemplates, in my case one for each type of item. So I created a template that contains a Line for the GraphLine type, another for GraphStart, containing a Rectangle, and one for GraphEnd, containing an Ellipse. Forget the syntax right now, first I had to solve the problem of the different ways to position something on a Canvas and the ItemsControl. You see, in order to position a Line, all you have to do is set the X1,Y1,X2,Y2 properties, but for Ellipses and Rectangles you need to set Canvas.Left and Canvas.Top. The problem with the ItemsControl is that for each of these not primitive objects it creates a ContentPresenter to encapsulate them, therefore setting Canvas properties to the inner shape did nothing. The solution is to set a style for the ContentPresenter and set the Canvas properties on it. Surprise! Then the Lines stop working! The solution was to add several Canvases, one for the lines and one for the rectangles and ellipses, as ItemsControls, and one for static text and stuff like that, all in the same Container so that they overlap. But it worked. Then I started the program and watched the chart being displayed.

<ItemsControl ItemsSource="{Binding GraphItems}" Name="GraphLines">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type local:GraphLine}">
...
</DataTemplate>
<DataTemplate DataType="{x:Type local:GraphSpline}">
...
</DataTemplate>
<DataTemplate DataType="{x:Type local:GraphStart}">
...
</DataTemplate>
<DataTemplate DataType="{x:Type local:GraphEnd}">
...
</DataTemplate>
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>

But how did I calculate the coordinates of all of these items? As I said, the Canvas is a pretty static thing. If I resized the window, the items would remain in the same position and with the same size. Also, the viewmodel didn't have (and shouldn't have had) an idea of the actual size of the drawing Canvas. My solution was to use a MultiBinding with a custom converter. It would get two values, one would be a computed double value, from 0 to 1, that represented either vertical or horizontal position, the second would be the value of the dimension, the height or the width. The result would be, of course, the product of the two values. Luckily WPF has a very flexible Binding syntax, so it was no problem two define a value from the viewmodel and a value of the ActualWidth or ActualHeight properties of the Canvas object. This resulted in a very nice graph that adapted to my resizing of the window in real time without me having to do anything.

<Line Stroke="{Binding Ip, Converter={StaticResource TextToBrushConverter}}" StrokeThickness="2" >
<Line.X1>
<MultiBinding Converter="{StaticResource ResizeConverter}">
<Binding Path="X"/>
<Binding Path="ActualWidth" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type Canvas}}"/>
</MultiBinding>
</Line.X1>
<Line.Y1>
<MultiBinding Converter="{StaticResource ResizeConverter}">
<Binding Path="Y"/>
<Binding Path="ActualHeight" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type Canvas}}"/>
</MultiBinding>
</Line.Y1>
<Line.X2>
<MultiBinding Converter="{StaticResource ResizeConverter}">
<Binding Path="X2"/>
<Binding Path="ActualWidth" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type Canvas}}"/>
</MultiBinding>
</Line.X2>
<Line.Y2>
<MultiBinding Converter="{StaticResource ResizeConverter}">
<Binding Path="Y2"/>
<Binding Path="ActualHeight" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type Canvas}}"/>
</MultiBinding>
</Line.Y2>
</Line>

Performance


The next issue in the pipeline was performance. Clearing the GraphItems collection and adding new items to it was very slow and presented some ugly visual artifacts. For this I used the inner mechanisms of the BindingList object. First I set the RaiseListChangedEvents property to false, so that the list would not fire any events to the WPF mechanism. Then I cleared the list,added every newly calculated GraphItem to the list, set RaiseListChangedEvents back to true and fired a ListChanged event forcefully using the (badly named) ResetBindings method.

GraphItems.RaiseListChangedEvents = false;
GraphItems.Clear();
foreach (var item in items)
{
GraphItems.Add(item);
}
GraphItems.RaiseListChangedEvents = true;
this.Dispatcher.Invoke(GraphItems.ResetBindings, DispatcherPriority.Normal);

All good, but then the overall performance of the application was abysmal. I would move to another program, then switch back to it and it wouldn't show up, or I would press a button and it wouldn't show up pressed, or the values of the data from the devices were not displayed sometimes. It wasn't that it used too much CPU or memory or anything like that, it was just a very sluggish user experience.

First idea was that the binding to the parent Canvas object to get the ActualWidth and the ActualHeight values was slow. I was right. In order to test this I removed any bindings to the Canvas and instead set the values directly to the converter, via the SizeChanged event of the Canvas object. This made things slightly faster, but also made them look weird, since I would resize the window and only see a difference after SizeChanged fired. The performance gain was significant, but not that large. The UI was still sluggish.

void Canvas_SizeChanged(object sender, SizeChangedEventArgs e)
{
var resizeConverter = (ResizeConverter)this.Resources["ResizeConverter"];
resizeConverter.Size = e.NewSize;
}

Now, you would ask yourself, what is the purpose of my using this ItemsControl and Canvas combination? It is in order to use the MVVM pattern. Just drawing directly on the Canvas would violate that, wouldn't it? Or would it? In this case the binding of the values in the viewmodel to the chart is one way. I only need to display stuff and nothing that happens on the chart UI changes the viewmodel. Also, since I chose to recreate all the chart items at every turn, it just means I am delegating clearing the Canvas and drawing everything to the WPF mechanism, nothing more. In fact, if I would just subscribe to the GraphItems ListChanged event I would be able to draw everything and not really have any strong link between data model and presentation. So I did that. The side effect of this was that I didn't need two ItemsControl/Canvas instances. I only needed one Canvas and I would add items to it as I saw fit.

Of course, the smart reader that you are, you realized that I need to know the type of the viewmodel in order to subscribe to the items list. The very correct way to do it would have been to encapsulate the Canvas into a control that would have received a list of items as a model and it would have handled all the drawing itself. It makes sense: you don't want a Canvas, what you really want is a Chart component that handles everything for you. I leave that to the enterprising reader, since it is outside the scope of this post.

Another thing that I did not do and it probably made sense in terms of performance, was to add items to the chart, somehow translate the position of the chart and remove the items that were outside the visible portion of the chart. That sounds like a good feature of the Chart control :) Again, I leave it to the reader to try to do something like that.

Bezier curves instead of lines


The last thing that I want to cover is making the chart less jagged. The roundtrip ping values were all over the place resulting in a jagged line kind of chart. I wanted something smoother, like a continuous curvy line. So I decided to replace the Line representation with a Bezier curve one. I am not a graphical person, neither a math geek. I had no idea what a Bezier curve is, only that it helps in creating these nice looking curves that blend into each other. Each Bezier curve is defined by four points so, in my ignorance, I thought that I just have to pass four points from the list instead of the two required to form a Line. The result was hilarious, but not what I wanted.

Reading the theory we learn that... what the hell is that on Wikipedia? How can anyone understand that?!... Ugh!

So let's start with some experiments. Let's use the wonderful XamlPadX application to see some examples of that using WPF. First, let's draw a jagged three line graphic and try to use the four points to define a Bezier curve and see what happens.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<Canvas>
<Line X1="100" Y1="100" X2="200" Y2="300" Stroke="Gray" StrokeThickness="2"/>
<Line X1="200" Y1="300" X2="300" Y2="150" Stroke="Gray" StrokeThickness="2"/>
<Line X1="300" Y1="150" X2="400" Y2="200" Stroke="Gray" StrokeThickness="2"/>
<Path Stroke="Red" StrokeThickness="2">
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigureCollection>
<PathFigure StartPoint="100,100">
<PathFigure.Segments>
<PathSegmentCollection>
<BezierSegment Point1="200,300" Point2="300,150" Point3="400,200" />
</PathSegmentCollection>
</PathFigure.Segments>
</PathFigure>
</PathFigureCollection>
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
</Canvas>
</Page>



As we can see, the curve does touch the first and the fourth points and sort of approximates the line, but not very clearly. The problem becomes even more obvious when we add another point and we create two Bezier curves, from the first and last four points. The two curves intersect, they are not continuous. Even if you take points four by four, the resulting curves, even if they continue each other, they do it with straight corners, the opposite of what I wanted.




Let's try the opposite, let's draw one Bezier curve and then lines that connect the first and second and then the third and fourth points. We see that the lines define tangents to the two arcs comprising the Bezier curve. That intuitively tells us something: if two Bezier curves would to seamlessly blend into each other, then the straight lines that define them would also have to be continuous. We try that in XamlPadX and yes! It works.




So, from this we learn something. First of all, the first and last points of the Bezier have to be the points used in a normal Line. Then the last two points need to be part of the same line for the first two points of the next curve. So what about the second and third points? How do I choose those? Can I choose any lines to define my curves? Thinking of the chart that I am looking for, I just want that the jagged edges turn into nice little curves. I also don't want to think of other points than the points that would normally define a single line, that means I shouldn't use future data in defining the middle points of the curve that defines current data. So I just made the decision to use only horizontal lines to define curves. That means for any pair of coordinates X1,Y1, X2,Y2 I would create four pairs like this: X1,Y1 X1+something,Y1 X2-something,Y2 X2,Y2. That value could be anything, but I've decided it would be a percentage of the horizontal distance between two points.

Final result: using a percentage, let's say 20%, I would turn the pair of coordinates into X1,Y1 X1+(X2-X1)*0.2 X1+(X2-X1)*(1-0.2) X2,Y2. Let's see how that looks on the original jagged line. Let's use 50% instead. And for some fun, let's put it to 80%, 100% and even 200%.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<Canvas>
<Line X1="100" Y1="100" X2="200" Y2="300" Stroke="Gray" StrokeThickness="2"/>
<Line X1="200" Y1="300" X2="300" Y2="150" Stroke="Gray" StrokeThickness="2"/>
<Line X1="300" Y1="150" X2="400" Y2="200" Stroke="Gray" StrokeThickness="2"/>
<Path Stroke="Red" StrokeThickness="2">
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigureCollection>
<PathFigure StartPoint="100,100">
<PathFigure.Segments>
<PathSegmentCollection>
<BezierSegment Point1="150,100" Point2="150,300" Point3="200,300" />
</PathSegmentCollection>
</PathFigure.Segments>
</PathFigure>
<PathFigure StartPoint="200,300">
<PathFigure.Segments>
<PathSegmentCollection>
<BezierSegment Point1="250,300" Point2="250,150" Point3="300,150" />
</PathSegmentCollection>
</PathFigure.Segments>
</PathFigure>
<PathFigure StartPoint="300,150">
<PathFigure.Segments>
<PathSegmentCollection>
<BezierSegment Point1="350,150" Point2="350,200" Point3="400,200" />
</PathSegmentCollection>
</PathFigure.Segments>
</PathFigure>
</PathFigureCollection>
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
</Canvas>
</Page>







That's it, folks. I hope you enjoyed this as much as I did and it helps you in future projects.

Whenever you want to test a REST API, Postman is a great tool. It allows configuring all aspects of a request: Method (GET, POST, etc), Headers, keeps previous attempts in history, manages collections of requests and saves them and it is installed as a Chrome extension, bringing it only two clicks away. It does everything! ... or does it? Short story long: no!

Reported as a problem here: Referer header is not sent when set in Postman, the issue appears to be that some headers are "protected" by Chrome, therefore unusable. Well, it is a bug in the sense that Postman should tell you that when you write something there it is completely ignored! There is a solution, that can be found as a link in the bug report, but it involves installing other crap and running Python scripts. Ugh!

Here is a list of the Chrome protected headers:
  • Accept-Charset
  • Accept-Encoding
  • Access-Control-Request-Headers
  • Access-Control-Request-Method
  • Connection
  • Content-Length
  • Cookie
  • Cookie 2
  • Content-Transfer-Encoding
  • Date
  • Expect
  • Host
  • Keep-Alive
  • Origin
  • Referer
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade
  • User-Agent
  • Via

So whenever you believe that some web site has used a magical solution to detect your sneaky attempts to access their web API or site and you are wondering what, just remember that it is most likely a Referer header that Postman (via Chrome) silently ignored.

and has 0 comments
The Prince of Nothing trilogy was a total masterpiece, full of harrowing experiences of flawed men and women and characters so deep and original that they defied belief. You get the godlike Kellhus, not only freezingly rational and intelligent, but also mastering the Gnosis, the art of magic, while being a textbook example of a charismatic psychopath. You get Akkamian, a worldly sorcerer and spy, a teacher and a hopeless romantic. You get Cnaiür, a monstrous barbarian driven by revenge, but trapped by love. Esmenet, the whore empress mother, being heartbreakingly and treacherously a woman. And all these complex characters get to live in an epic world of different cultures, with politics, and military campaigns and evil creatures serving the No-god, shape shifting assassins and magic schools. In fact, it was so great that I found myself feeling dread of reading more, so terrifying the deep and personal pain of the characters that it was becoming mine.

Now I have finished The Judging Eye, the first book of the Aspect-Emperor trilogy, itself no more than a direct continuation of Prince of Nothing. R. Scott Bakker kind of cheats by using the same basic scaffolding for this story: a military campaign where an innocent and sympathetic character is being eroded by Kellhus' influence, a dark character driven by revenge on a lonely and dangerous quest, against himself slowly warming himself to the presence of a woman, court machinations driven by self serving creatures and the general backdrop of a clash between religions. He does it masterfully, though, switching the characters around and adding new ones to fill the roles left empty. In The Judging Eye one gets something as similar to The Darkness That Comes Before as needed to please the crowds that enjoyed Prince of Nothing, but as different to make it a completely different story. You get more of the same, so to speak, with an emphasis on 'more'. But also a little bit less.

Not everything is perfect. I feel that the inner dialogues of the characters have become more opaque, more strained. The metaphors flow just as in the previous books, but they communicate less, one makes more of an effort to get them and feel what the author meant, giving it a slight air of pompousness. I mean even a little kid philosophizes more than all the adults I know. The book has slightly more action scenes than I remember in Prince of Nothing, but they also feel more confusing. For all of Bakker's talent, I think he doesn't really understand combat and physical violence. He more than compensates with emotional and visceral violence, I agree, but I can't stop myself thinking of all the tactical applications that were never explored in battles purportedly fought by hardened veteran mercenaries.

His biggest sin, I believe, is that he doesn't follow through with the revelations that he awards the reader. I remember he was doing something similar in Prince of Nothing as well. He takes one through the labyrinthine mental processes of a character that marches uneventfully, but he fails to explain what exactly is happening - or at least what the characters are thinking - when something extraordinary happens. For example, in one scene, they discover a crazed individual with an eye on his heart, driven mad by the darkness that his heart is plunged into. A very powerful image. Yet Bakker doesn't explain anything. How was that possible? How did Akka know to look at his heart? What the hell were hordes of Sranc doing in a sterile dead mountain tunnel? No, instead we get to read about every single internal thought that the characters have about themselves and their lives. To quote from the book: "the work of a race that has gone insane for staring inward".

Bottom line: there is so much introspection in this book that barely anything happens. Falling into his own trap, Bakker gets seduced by his characters to the point of ignoring the universe in which they live. The book remains incredibly good and so I will venture to read the next one in the series. I already lament the fact that the third book of the Aspect-Emperor is not yet published and dread the moment when I will finish the second.

and has 0 comments
There is a nice web site called Chess Pastebin that allows one to publish a chess game as a PGN, comment on it using a Disqus form and share it with whomever you wish. However when I tried to use it, it refused to accept my PGN (extracted from Chess Arena). After many trials I realized that it considered invalid a move written as 10. .. some move instead accepting only 10... some move (no spaces between the dot of the move number and the dots representing a black move after a variation). So just replace ". .." with "..." to get a PGN acceptable by Chess Pastebin.

and has 0 comments
I've always heard this when I was young, as a Latin proverb - and therefore old and wise: in vino veritas. I've always interpreted it as "alcohol loosens the tongue", but today I had a revelation. Yeah, alcohol does remove some inhibitions, but usually the things we say to other people while inebriated are really dumb things that only a drunken man would say. They are not truth, they are wishful thinking, fears, pains. Instead, I propose that the real truth of the wine is you cannot so easily lie to yourself!

Indeed, I've noticed this in several situations, highly emotional ones or normal ones - it doesn't matter, when I have drunk alcohol and I am thinking to myself I always reach the conclusion that lying to myself, no matter how comforting, is not worth it, and I often expose and dispel things like hypocrisy, pettiness, delusion and so on. My best psychotherapy was always alone, drunk or comfortably inebriated, having the opportunity and courage to confront myself.

Now, that might seem boisterous or even something a drunken man would write. And that is true. However, it doesn't invalidate the argument. I have recently counseled a good friend who just lost his mother (he didn't lose her, he knows where she is, but she just died) to drink - alone - and speak to himself. I only wanted to help using my own experience, but that prompted me to think a little about it and that materialized into this blog entry. Drink a little with your friends, relax, chill, do whatever social thing you want to do, perform whatever ritual your tribe is comfortable with, but that only removes the stress. It does little else. At worst, it makes a fool out of you. True drunkenness is lonely and revealing and bitter. It is not pleasant, it is, at best - when done right, or when lucky - therapeutic.

That's my two cents about the subject, but I feel I need to explain a passage above: "comfortably inebriated". Sometimes, especially if confronted with strong emotions (or even boredom or gluttony, why not?), we drink too much. We don't consider the "alcoholemy", the amount of alcohol in the blood, the rates of absorption and so on. If there is a "sweet spot" a place where the quantity of alcohol in our blood is good for us, the only way to maintain it is to compute the ingested quantity compared to the quantity of blood one has and maybe some empirical factors like tiredness, personal resistance to intoxication, body mass, what you ate and so on. More simply: find the number of minutes that you can afford to drink a beer and then continue to drink beers every such interval so that you not get completely wasted. Of course, the equations are slightly more complicated, but you get the gist of it. I submit that you probably don't need to get completely drunk to reach that sweet spot, instead just research and find the perfect combination for you. More than a few times I got wasted after I had stopped drinking, as the alcohol in my guts was getting absorbed.

I may be wrong. There is always the dark specter of acquired resistance to any intoxicant, so that while the experiment may be perfectly scientific and true, one would need increasing quantities of the drug to get to the same result. However, empirical evidence of people who started drinking a little bit, then more and more, shows that there is a point where they stop and get the same result with similar quantities of alcohol. There is the sad case of alcoholics, but I believe that to be a small percentage of people experimenting with alcohol.

Anyway, the thing to remember: a few (more) beers could be as good as a year of therapy, if you are willing to drop the veil and be honest... to yourself. Anyone else wouldn't understand anyway.

and has 0 comments
Another really nice book I am glad I readlistened to. In 2001 Neil Gaiman published this book, American Gods, and then,ten years later, a special tenth anniversary edition, with the "author's preferred text" and including an additional 12,000 words, was published by William Morrow in June 2011. Both versions of the book were adapted to audiobooks, the first just narrated, the second with a full (and talented) cast. This second version I listened to, on YouTube no less. Long story short, I liked the book a lot, even if it was a bit too long winding.

The story is not only interesting in concept - gods being created and fed by people's beliefs, then being forgotten and dying as belief wanes, but also in its many details borrowed from the world's superstitions and religions. We start with a man in prison, a calm, cerebral man, but also big and muscular. He is about to be freed from prison and return to his wife and his best friend to start his life anew. From then he is just thrown into this crazy world of supernatural beings, but not like all these lazy TV shows where there are vampires and werewolves at war, but slowly and subtly. Gods are at the same time what we remember them to be: big spiders, thunderbirds, gods of war, but also men and women that can be killed. They can be pitiful beings, old creatures that resent the newness of the world and of its people. I also liked that there was not a lot of the major religions, just a few hints at the end. No Christian or Muslim stuff, I mean. At the end of the audio book there is an appendix, Shadow meeting Jesus, that the author wrote but decided to keep out of the book because it didn't feel like it was part of it. I agree with him.

There is also a kind of Lord of the Rings ending to the book. Even if the main story arches ended, there are still several chapters after that. I could have lived without them, I guess. This verbosity is also the problem with the book. Laden with details and side stories and keeping the pace slow can be slightly boring. I never read the version published in 2001, but it was shorter, which was probably for the better. I liked that Gaiman left a lot of hints in his writing and even I was able to see through them. That was maybe another reason why the pace felt too slow, since I've glimpsed a little of the whole story and then just waited for it to reach that point. However, that is the exact reaction of the protagonist, when he figures stuff out. He feels like he already knew, but refused to actually bring it into consciousness.

The adaptation of the book was top notch, the protagonist, but more than this the man called Wednesday, were interpreted by talented actors and I found myself drawn into the story like a man slowly being pulled down in quicksand. Give it a try.

It was announced by Starz in July 2014 that they are preparing an adaptation of the book into a TV series. Also, while there are other Gaiman books and stories in the same universe (like Anansi Boys, from 2005, which some call American Gods #2), the author announced he is working on a direct sequel of the book only in 2011.

Shinsekai Yori, translated as From the New World in English, is the anime adaptation of the homonymous book from 2008, written by Yusuke Kishi. It shows, too, as the subjects touched are deep, the characters are complex and the story is wonderful. It is a true sci-fi, not only set into the far future, but also using serious concepts such as what it means to be human, what is the price of peace and questioning if we can ever change as a species and as a culture.

It is a complete plot told in 25 episodes, well animated, but I wouldn't call the animation special, yet the story is certainly worth it. If you want to compare it with something, try a combination between The Village and some fantasy kid school movie. While it begins like a post apocalyptic version of Harry Potter, it quickly turns into a discussion about the sacrifices required to preserve peace. It doesn't just stop at the young adult audience, but continues with new and new twists until it feels like you have a collection of stories that just happen to follow one another, yet they are very connected. The film is filled with Japanese ways of seeing the world, from the absolute obedience towards authority to the horror they instinctively feel when talking about mass destruction, but also random cruelty based on a class system, or that sense of duty that permeates everything everybody does, or girls always stumbling or being interrupted by men when they talk and told what to do. However, it doesn't stop there and it explains, in a way, why things are like that and what are their consequences.

In the end, you feel like humanity has been deconstructed and its ways of functioning laid bare and put to trial. I liked the characters and the emotional rollercoaster the anime has put me through. Really nice, Hollywood should take heed on how to do a good story and put it into motion. I highly recommend it.

Update: This post discusses shrinking the data file of a Microsoft SQL database, caused in this case by misconfiguring the initial size of the database. For shrinking the log file one must at least use type 1, not 0, in the query. Also, a very pertinent comment from NULLable warns of the performance issues related to shrinking database files resulting from the fragmentation of the file.

I had this situation when the available space on the SQL database disk was less than the size of the database, in this case the temp database. Someone had wrongly configured the database to have an initial size of 64GB. Changing the size of the file in Microsoft SQL Management Studio doesn't work because it tries to create a different file, fill it with the data and then replace the file. No space for that. Also, it is damn slow, even if you have the space (I have no idea why). Shrink doesn't work either, because the database will not go smaller than the configured initial size. Time to do it command line style. Well, with sql queries, but you know what I mean.

The code for it goes like this:
USE [master];
GO

CHECKPOINT;
DBCC DROPCLEANBUFFERS;
DBCC FREEPROCCACHE;
DBCC FREESYSTEMCACHE ('ALL');
DBCC FREESESSIONCACHE;
GO

USE [tempdb]
GO

DBCC SHRINKFILE (tempdev, 3000); --- New file size in MB
As you can see, you need to know not only the name of the database, but also the logical name of the database file that you want to shrink. It is not even a string, it is like a keyword in the DBCC SHRINKFILE command. Even if it does work, one would benefit from encapsulating it into a stored procedure. Here is the final code:
CREATE PROC ShrinkDatabase(@DbName NVARCHAR(100),@SizeMB INT)
AS
BEGIN


DECLARE @filename NVARCHAR(255)

DECLARE @sql NVARCHAR(Max) = 'SELECT @filename = dbf.name FROM ['+REPLACE(@DbName,'''','''''')+'].sys.database_files dbf WHERE dbf.[type]=0'
EXEC sp_executesql @sql,N'@filename NVARCHAR(255) OUTPUT',@filename OUTPUT

SET @sql='USE [master];
CHECKPOINT;
DBCC DROPCLEANBUFFERS;
DBCC FREEPROCCACHE;
DBCC FREESYSTEMCACHE ('
'ALL'');
DBCC FREESESSIONCACHE;'

EXEC sp_executesql @sql

SET @sql='USE ['+REPLACE(@DbName,'''','''''')+'];
DBCC SHRINKFILE ('
+REPLACE(@filename,'''','''''')+', '+CONVERT(NVARCHAR(100),@SizeMb)+');'
EXEC sp_executesql @sql

END

Create it in the master database and use it like this:
EXEC master.dbo.ShrinkDatabase 'tempdb',3000
Take note that you cannot use this to "shrink up" the database. If the value you set is larger than the current size, the file will remain the same size as well as the setting for the initial size. Also take note of the fact that this stored procedure only shrinks the data file, not the log file (dbf.[type]=0).

and has 0 comments
Just a quick reminder that there are a lot of Star Trek productions out there, some really terrible, some really good. I am going to talk about three(ish) of them today.


First one is Star Trek: Federation One. It is with a lot of actors you have seen in other Hidden Frontier and Studio Areakt productions and focuses on the chief security of the presidential office of the Federation. While the plot is kind of a mess, the acting was decent and I was actually very sad to see that after the first "season" of two episodes they continued the story in an audio format. Even if the main character looked like he was on speed all the time, I had fun with it.


Another one is Star Trek: The Infinite Chain. Even if it is split into "episodes" it is actually a feature film. The acting is a bit amateurish, but decent. No obese teens in this one. It uses the now tired plot of a Federation starship thrown into unknown space by "an anomaly". The worst part of it was the "doctor" that was assigned to the mission. His character was believable: the guy in charge of the project creating the sensors used to study the anomaly, but in truth not a good manager or having any merit in the team. He just explodes randomly in childish emotional outbursts, threatening everybody with his artificial authority, and everybody hates him. I totally know people like that. However the actor was just goddamn awful and his script lines ridiculous! The makeup was ingenious, but really cheesy.


The last, but certainly not least, is something made by the Hidden Frontier team, but not set in the Star Trek universe. I am talking about Frontier Guard. The casting is made with the better actors of previous productions and, while the universe seems very similar to the Star Trek one, it is actually a different thing altogether. They use another type of space propulsion, it involves a FederationFrontier Guard academy and it concerns The Arc, a huge alien artifact that may have seeded the galaxy with intelligent life. Unfortunately, after some great episodes, they completely lost it. They began (some) episodes with "My name is..." evoking feelings of remembrance towards all the bad DC superhero series and movies, they started pointless subplots like the gay relationship thing - which always pisses me off, not because of the gayness, but because of the relationship that doesn't further the plot in any meaningful way - and threw in the towel after the 12th episode (which was an elevator show, basically).

From these three Frontier Guard was the best. My guess is that they wanted to do a Star Trek Academy series - which makes total sense and it should be the direction of the next Star Trek series - but they didn't get the approval. Since this sounds like a really good idea and one that might attract a lot of fans, I believe studios are keeping the story in reserve. However, not being Star Trek allowed them to evolve both stories and characters and I was really excited to see this done. In a world where everybody is remaking remakes, we need and deserve original content. Just look at David Feintuch's Seafort Saga series of books. That would make a fantastic TV series and has enough material to allow for several companion feature films.

For people just considering starting to watch these, do not expect Star Trek Next Generation. The actors are amateurs, I mean real amateurs not professionals who just started acting, most of them are American Trekkies and - even if I don't want to insult - some of them are just humongous pieces of fat with big glasses, which kind of explains the whole geek high school thing that is kind of difficult to understand in Europe. The stories, the lines, the makeup, the uniforms, the special effects, they are all done by enthusiasts. Sometimes they feel cheesy, sometimes they look completely and horribly fake. But once you realize that they are people like you, enjoying the wonderful universe of Star Trek, you can begin enjoying these productions.

I've watched other things as well, including Machinima style animations like Borg War - which I wouldn't recommend, but wasn't bad, and I will continue to look for these things. Just by looking at people like Hidden Frontier, who start doing something for the fun of it and end up doing original stuff with veteran amateur actors, I get filled with hope for the whole fan made universe, not just the Star Trek one. Keep up the good work guys (and if you can't do it good, keep working and it will get there eventually :) )

The best thing about it is that most of these series are online, on YouTube, free to watch. Here are some links to the shows above and others:
Star Trek Federation One - 1.01 Unity
Star Trek Federation One - 1.02 Institutions

Star Trek: The Infinite Chain

Frontier Guard

Star Trek: Digital Ghost

Special mention: Star Trip - a humorous parody of Star Trek.