Monday, December 28, 2009

Deadhouse Gates by Steven Erikson

book coverThe second book in Steven Erikson's Malazan Book of the Fallen series, Deadhouse Gates starts from where Gardens of the Moon left, using some of the characters, but in a completely different storyline. Thus, it can be read as a separate book.

I found Deadhouse Gates to be both better in the good parts as well as worse in the bad parts than Gardens of the Moon. The characters are more complex, the storyline more interesting, the battles more epic, but the magic is even stronger, its power never truly explained or detailed so that it fits in the background. What use is an army, if a single mage can obliterate whole realms? How does a human empire span so much land unchallenged, while creatures that can crush it singlehandedly exist in the world?

As expected, the characters more their separate ways, occasionally meeting for brief periods of time, but essentially having their own story arches. There is the Coltaine arch, with the moving story of a brilliant commander protecting thousands of ungrateful whiny rich refugees; the Felisin arch, which describes the life of the younger Paran sister, driven by the hate towards her older sibling and adjunct to empress Laseen; the story of Kalam, the assassin, in his quest to kill Laseen; the tale of Crokus and Apsalar and Fiddler, travelling the magical desert Raraku; finally, the story of Icarium the Jaghut and Mappo Runt, the Trell, both insanely old and searching for Icarium's lost memories.

Great book, I started reading the third in the series and I don't see me stop until I finish the entire Malazan saga. I found an interesting link that can serve as an encyclopedia of the Malazan universe. Here it is: Malazan universe.

Wednesday, December 23, 2009

Joy of Thinking, lectured by Ed Burger and Michael Starbird

Joy of Thinking: The Beauty and Power of Classical Mathematical Ideas is an earlier math course, staring a long haired Ed Burger and his Texas U colleague Michael Starbird.

Many of the ideas in Introduction to Number Theory have obviously originated here, however I didn't find this course so interesting, maybe because it was not so well thought trough or maybe because it was clearly targeted at a lower level of understanding and the many repetitions of basic ideas kind of turned me off.

The content of the course is structured into three parts: Numbers, Geometry and Probability. The first part contains very little that has not been covered in Introduction to Number Theory. The geometry section is a bit interesting as Michael Starbird takes us through some topology, talking about the Möbius strip and the Klein bottle. The last part is basic probabilities, although there are some interesting problems studied there.

Overall, a fun course, better suited for people that are really not into maths, but more into interesting ways of thinking. The last lecture summarises the life and thought "lessons" learned from this trip into mathematics.

Monday, December 21, 2009

EasyReplace - replace files in a folder hierarchy with newer versions

Yay! New Github project: EasyReplace.

What it does is replace all files in a folder hierarchy with the files you drag&drop on the app info box. It is very helpful when you want to replace old library files or some other versions of your files with newer ones without having to manually navigate through solution folders.

Life on Mars revisited

...and no, I am not talking about the Ashes to Ashes spinoff of the British series, I am talking about actual life on Mars.
Microscopic picture of the meteorite
Remember in 1996 when everybody was talking about finding signs of life in a meteorite that came from Mars? At the time the theory was dismissed because other causes for the structures in the meteorite were thought to be valid. Here comes a new study from december 2009 that invalidates the proposed non-organic processes in which the features on the martian rock could have been formed.

Yay! Merry Christmas, green guys!

Sunday, December 20, 2009

Large Hadron Collider TV

Here is a small funny video combining music and science in a geeky mix. I know, the music could have been less 80's rap and the dancing... well, could have been dancing. I mean, if even I noticed a lack thereof, it must really have been awful. But then it wouldn't have been geeky enough, right ;)

Friday, December 18, 2009

Introduction to Number Theory, lectured by Ed Burger

What a fun course this was. The lecturer of Introduction to Number Theory, Ed Burger, a math PhD, looks like what one would expect a mathematician to look like: thin, tall, geeky looking, wearing a rather bland costume, but with a colorful tie, curly hair and large glasses, with a sincere smile that seems a bit sad. The thing is, he is also a lot of fun and his enthusiasm regarding mathematics is not only obvious, but catchy as well.

The course itself requires very little if any mathematical education to understand, being mostly about ideas, rather than formulas. It is a Teaching Company course, and each lecture builds upon the understanding from the previous ones, making surprising and really fun connections.

I was very sad when the course ended, I wanted more! Happily, I've got "The Joy of Thinking" and "Zero to Infinity - a History of Numbers" that are also lectured by Ed Burger and I can't wait to watch them all. I highly recommend the course, even if one is not interested in math. It opens the mind on a way of thinking, useful in any situation, rather than anything specific.

Wednesday, December 16, 2009

Ruruoni Kenshin aka Samurai X

Every time I've heard about this anime I refused to watch it for the very simple reason that the American "brand name" was Samurai X, which pretty much sucked tremendously. But, while reading a list of Shōnen anime series, I've decided to give it a try. And it, real name Ruruoni Kenshin, was a decent anime.

Staged in the beginning of the Japanese Meiji era (the reconstruction, as they call it, after American battleships forced the country to open its borders to the outside world) it features the adventures of former samurai assassin Himura Kenshin Battousai, fighting for the imperialists in the Tokugawa era, now reformed as a wandering samurai and having vowed not to kill anyone anymore. He manages this feat by using a "reverse blade" sword, which has the cutting adge on the inside. He thus manages to beat the crap out of people without actually killing them.

The series reminded me of Twilight Samurai, the movie that I liked so much, because it shows the feelings of people in the middle of great social and political change. Featuring 95 episodes, it is split in three main parts.

The first is how Kenshin moves into a sword dojo ran by a beautiful and single girl (heh!) and how they save a little boy from thugs and thus they become sort of an unofficial family. His "man slaying" past is slowly eroded by the contact with this pure hearted people. During this period he gets to fight several enemies, each stronger than the others, but keeping his vow not to kill anyone.

The second part is a large story arch in which he fights against a plot to overthrow the Meiji government and bring Japan to another period of chaos and war. The story culminates with the battle against a former "manslayer", the mastermind of the said plot.

The third part is mostly a mix of different stories that pretty much breaks the spirit of the first two parts. Instead of getting better, it grinds to a stop and then even gets worse. In this section he gets to fight "Feng Shui" masters and participate in all kind of filler episodes.

I felt that the series had a very nice feel to it, so I would recommend anime fans to watch it, but with the third part optional. There are also several OVAs that I am yet to watch. Happy viewing!

Update: I have watched the 6 OVAs and I was blown away. There are 4 episodes that make up an "origin story" for Kenshin, then a fifth episode which kind of summarises the series (badly) and then an ending that is both positive and extremely sad (in that typical Japanese suicidal way :) ). The animation is way more mature, the plots more complex, the characters have real feelings and there is no comedy whatsoever, getting back to that good feeling I had when I started to watch the series. Also the audience is different: the battles are realistic, with wounds and lots of blood, no magical mambo-jambo, while the characters behave more traditionally, with the women being more passive and the men more closed up.

All in all, the origin story makes the series seem childish at best, however I would recommend it being watched after seeing the series, just as I did.

Friday, December 11, 2009

Gardens of the Moon by Steven Erikson

I got this book as a recommendation and at first, I thought it wouldn't work. The scope was large, the characters many and the OCR was really bad so I had to guess some of the words from my text file. So I started reading other books. Left with only this on the PDA, I decided to attempt one more read. I don't regret that decision.
Book cover
After a while I thought I've started another series of books from the middle or something. A lot of characters, with deep histories, placed in a vast historical context with lots of cool stuff like magic and wars and empires and gods and undead creatures and all that. But no, Gardens of the Moon is actually the first of ten books in the Malazan Book of the Fallen series by Steven Erikson. Wikipedia says: The Malazan world was co-created by Steven Erikson and Ian Cameron Esslemont in the early 1980s as a backdrop to their GURPS roleplaying campaign. In 2005 Esslemont began publishing his own series of five novels set in the same world, beginning with Night of Knives. Although Esslemont's books are published under a different series title - Novels of the Malazan Empire - Esslemont and Erikson collaborated on the storyline for the entire fifteen-book project and Esslemont's novels are considered as canonical and integral to the series as Erikson's own.

The plot is very complex, revolving around the Malazan empire, ruled by empress Laseen, who has just recently staged a coup d'etat and has overthrown and killed the emperor. The empire itself has only one goal, to bring all free cities under its rule, therefore a thick weave of scheming in order to juggle the armies that are partially still loyal to the fallen emperor, the many enemies of the empire, including vary powerful mages and the various high ranking officers who don't see with good eyes what is happening with the empire. And on top of this, Ascendants or Gods are meddling in every important aspect of life. The result is a soup of personal stories, epic battles, shrewd politics and lots of cloak and dagger stuff.

I have to say that I liked the effort a lot, including all the small details that are quite different from books with similar subjects. For example the magic comes from warrens, each a different flavour with influences that diminish and grow like tidal waves and which feed powerful beings whose purposes are never clear or directly expressed. Gods are equally likely to fight amongst themselves, meddle in the human affairs or purely possess some unlucky sod in order to manifest in the real world.

I will now end this entry in order to get the rest of the books in the saga. I highly recommend the book for all fans of fantasy and sci-fi alike.

Tuesday, December 08, 2009

Romanian Zombie Elections

A while ago, before the election craze began to grip Romania, someone asked me what I think will happen. At the time (as now) I knew more about the plot of the TV series I am watching and the insides of .NET than what was going on politically in my country. Of course, I answered anyway, as the truth is often found in the mouths of children and crazy people. Being both, I said Basescu, the current president, would win the elections, due to populace inertia, and the coalition of parties that wanted to replace him will see each of the inner parties split into people that don't want Basescu and people that want power, making the Democratic Party even larger, even meaner, even worse.

A month after my prediction, month spent in the hope that I was just a fool and didn't know anything about anything, it came true.

And, as if things couldn't get worse, I get to see how the difference between candidates has mostly been provided by the Romanian diaspora, rather than the poor bastards that have to live with the decision. And I know these guys, people that left the country in search of better payment, better conditions, maybe some respect. Knowing nothing about Romania anymore, they just vote as they see from afar, smug in their belief that they do one good thing or the other. Like fighting communism. Maybe it would have worked 20 years ago when you left! That, my friends, pisses me off. If you left, dear diasporans, leave us the fuck alone! Choose a president where you live, not where we do. I can't believe that the same people shouting the country is shit, that they want to go live in a "real" country, that they want to be treated with decency and so on and so on, gather en mass outside the borders to vote with the same idiot that ruled us so far.

And you know what is the funny thing here? People that see how this went and are just as disappointed and disgusted as I am... they say this could have happened only in Romania and they want to leave! It's like a zombie infection, isn't it? And we all got bitten.

Friday, December 04, 2009

Infragistics XamDataGrid binding to hierarchical DataSet

The WPF Infragistics controls 9.2 feature a grid called the XamDataGrid, which has a lot of options and is better designed than the horrible web grid from the same company. I wanted to bind the grid to a DataSet, one that has two tables (Data and Details) that are connected through a data relation (named keyRelation). Also, the fields are not auto generated, but defined in the FieldLayouts block.

First step: define the field layouts. Then bind to the DataSet. No go. The only way I could see anything was if I bound to the first table in the dataset (Data). Even so, the fields that were shown were those from the second FieldLayout definition, not the first. After googling a while I finally found the answer: you need to have a Visible field that has the name of the data relation.

So, the final solution for binding a DataSet hierarchically to a XamDataGrid when AutoGenerateFields is set to false:
  1. Bind the XamDataGrid DataSource to the parent table (or its DataView)
  2. Define two FieldLayout sections in the FieldLayouts block for each of the tables
  3. Add a Field with the same name as the data relation between the two tables to the parent table FieldLayout block


Example:

<DataPresenter:Field Name="keyRelation" Visibility="Visible"/>

Thursday, December 03, 2009

DuteVino - lansare album "0.1 Prototype"

A while ago I was blogging about a Romanian jazzy band called DuteVino. They didn't have an album, just leaked songs over the web, and they sounded rather nice with their female singer having a wide voice range.
band photo
After quite a while, they are releasing their first album, "0.1 Prototype", maybe a subtle irony to their lack of activity these past three years, or something to do with all the 2.0s clogging the names of new media. The album itself is formed of their songs so far and, hopefully, it means they plan another soon enough. Nice enough, it is freely downloadable from their site.

The release is due on Friday, December 4th, at 21:30, at Control Club. More information on their official site. If you have difficulties seeing the site, look for a popup poll (which is actually not a popup, but on the edge of the screen) and close it.

Wednesday, November 25, 2009

Infragistics Intermezzo

Ok, I know I promised you some cool posts and I really was going to write them. However, I am in my own personal crisis and all because of Infragistics controls. Ok, I know that some people like to complain and blame others for their mistakes. I am tempted to do that all the time and I am not always succeeding in abstaining, but this time it is not a pointless blame shift, this is totally real.

Let me put it in no uncertain terms: Infragistics controls suck shitty balls! They are poorly made, badly documented, there is no architecture that one can talk about (except in funny anecdotes at parties) and they are a complete pain in the ass. After giving some time estimates of how long it would take me to finish up some tasks I ended up repeatedly doubling that time because of the stupidity of Infragistics controls. Have I mentioned enough the shitty balls? And the sucking? Because I don't feel completely satisfied.

A small example: class A is inherited by class B. The functionality of class B is implemented in class A as "if I am B, then...". Then other classes using the A class sometimes have checks to see if it is not B, so that they would behave in a completely different way. I am not a brilliant software architect or something, but this is simply insane!

What about the grid columns and rows that are NOT web controls, nor do they implement some events or overridable methods that control their rendering. Instead, the grid is asking questions like "is this a template column? Then add this to the rendered string" (so not even a Controls collection that one can manipulate). And if this weren't enough, I get to have to fix errors in the javascript from Infragistics by replacing whole functions, because there is no other way to get through. One step forward and two back, just like bloody Sisyphus!

I had expected this to take 5 days and it took 3 weeks and I am still not done. My self esteem is plummeting, I am losing my will to live, I feel like the only satisfaction I could have is to go to the Infragistics team and tear them limb by limb, laughing all the way. I sincerely wish all of their managers, sales people, developers and remote assholes that finished tasks without consideration for the other developers they were working for a slow and painful death.

The fixes and solutions I have found are so unavoidably ugly that I don't dare to publish them on the blog, so my advice for you if you use Infragistics controls is to throw them all away and start from scratch. It will take you longer, but in the end you get a good thing, satisfaction for a job well done and a maintainable code. Don't worry, you can be a completely useless developer and you will still do a better job.

On a brighter note, I may start some attempts to code in Mono or at least create stuff in a different domain that what I have worked so far, so good things will happen on the blog, only not in the immediate future.

Monday, November 23, 2009

All Tomorrow's Parties by William Gibson

book coverAll Tomorrow's Parties is part of the Bridge trilogy, together with Virtual Light and Idoru. Placed in a world that is not too distant from our own, but changed brutally and irreversibly by the advent of new technology, it features some of the same characters as the previous books and tells the story of nodal points, as viewed through the eyes of Laney, the quantitative analyst, and of the people that are inadvertently in the middle of profound change. Laney is a guy that can sense accretions of data intuitively, because he was subjected to trials of some weird drug, and he notices a large nodal point, a place where data points to a change in the way the world works.

I will let you read it and see what this is all going towards. I must say that it felt like an easier book than Idoru, maybe because it has more action sequences and (a bit) less descriptive prose. It is a strange thing to understand the world of Gibson's imagination and feel so strongly about it, yet in the same time see that the world is not really going there. The details that the author infuses in his stories make all of his books seem part of reality and, having finished some story, I feel that the world around me is a bit fake. I believe that is a mark of a great writer.

Idoru by William Gibson

Book cover It seems that I started William Gibson's the Bridge trilogy in reverse order. I finished reading All Tomorrow's Parties and, before I could blog it, I started reading Idoru and realized that it was set in the same universe and had some of the same characters. And this only to find out by Wiki'ing that there is a third (and first) book in the series.

Well, I can't possibly hold up until I start and finish that one, and I may even not read it. Not because Gibson is not brilliant, but because the level of attention necessary to enter the atmosphere of his books is not appropriate for my daily subway trips to work. Because of this I recommend reading William Gibson books somewhere alone, in bed, well rested, ready to virtually go somewhere else and abandon reality for a while.

Back to Idoru, a book about a Japanese popular idol (hence the name of the book) who is entirely virtual, a programatic entity made for the sole purpose of entertaining. However, this inadvertently turns into a proper AI, becoming more human as the data from her fans becomes part of her being. Of course, a lot of characters are doing their thing in a typical for Gibson very detailed world that mixes the increasingly neglected realilty with emerging virtual worlds and concepts.

It is a good book, but I recommend you start with Virtual Light, go through Idoru and finish the proper way, by reading All Tomorrow's Parties.

Thursday, November 12, 2009

Your Silverlight developer components are out of date

For a few weeks I have been having problems running Silverlight on my machine, especially since I had SL3 installed and also Expression Blend, version 3. I didn't mind much, because I don't need Silverlight most of the time. But since sometimes I do, here is the solution for the "Your Silverlight developer components are out of date" error when trying to install Silverlight.

Go to http://go.microsoft.com/?linkid=9394666 and install the Silverlight tools. Yes, they are version 2. No, I don't know why Silverlight 3 would have problems because of version 2 Silverlight tools. However, installing the tools solved my problem.

Thursday, November 05, 2009

Use CSS expression to initialize html elements

Internet Explorer added something called expression to CSS, something purists have booed at for mingling javascript and CSS. Well, boo back! I happen to like stuff that can solve problems. If I were at Microsoft I would create an entire subset of javascript and css functionality. But hey, that's just me.

Anyway, I have decided to use expression to run an initialize function on newly created elements. It would work like this:
initialize:expression(window.initializeElement?initializeElement(this):null);
This CSS bit tells Internet Explorer (and none of the other browsers) that the initialize style property should get the value of the initializeElement function every time the browser refreshes the layout of the element. In the function itself I would do something like this:
function initializeElement(elem) {
if (!elem.style.initialize) {
doSomethingWith(elem);
}
return true;
}
This basically executes doSomethingWith on each element matched by the CSS rule and only once.

Good theory, but in practice it was terribly slow and, after a while, it managed to kill Internet Explorer with a strange System.AccessViolationException: Attempted to read or write protected memory error.

What happened? The slowness, I gathered after a while, was caused by the function doSomethingWith because it changed the style of the element. That meant that the css rule was being applied again before the function ended and returned true. Changing things to:
function initializeElement(elem) {
if (!elem.style.initialize) {
elem.style.initialize=true;
doSomethingWith(elem);
}
return true;
}
fixed it.

The error that killed Internet Explorer was even stranger. After a while I narrowed it down to using jQuery. I have no idea what it did, probably trying to access computedStyle or something like that. The thing is that changing an $(elem).height() with elem.offsetHeight solved it.

Wednesday, November 04, 2009

Get Visual Studio to use (better) more than 2GB of memory

I actually didn't know that a 32bit program could not use more than 2Gb of virtual memory by default. It makes sense, now that I think of it, but I just didn't make the connection. My office computer has 3Gb of memory and there is also the swap file, so having a program using more than 2GB of memory would be beneficial. And I am talking about Visual Studio here, especially since today I got an error I've never seen before: "Not enough storage is available to complete this operation".

So I've stumbled upon this article: Hacking Visual Studio to Use More Than 2Gigabytes of Memory which told me how to convince Visual Studio to use more than 2GB of memory. Also, since I am a ReSharper user, I found this little wrapper for Visual Studio that makes it use a different memory allocation method that reduces memory fragmentation: OutOfMemoryException Fix.


Short story shorter (for XP users with Visual Studio 2008 only - read the full articles for other configuration):
  1. Edit boot.ini to have the /3GB option
  2. Use editbin /LARGEADDRESSAWARE devenv.exe to change Visual Studio to have IMAGE_FILE_LARGE_ADDRESS_AWARE in the process header (editbin can be found in \Program Files\Microsoft Visual Studio 9.0\VC\bin\
  3. Download the Jetbrains devenv wrappers and change the signature of the Visual Studio shortcut to point to devenv2008_wrap.exe instead of devenv.exe
  4. (of course) Restart the computer


Update:
Thanks to the warnings from Lex Li, I went to study the /3G switch some more. The most important thing seems to be to also use the /USERVA switch to tune the /3G functionality.

More details here:
Memory Management - Demystifying /3GB
Summary of the recent spate of /3GB articles.

Monday, November 02, 2009

Things I've learned from HotBabe.NET

Rebecca Romijn as the icon of HotBabe
Today I've released version 1.2 of the HotBabe.NET application. It is a program that stays in the traybar, showing a transparent picture, originally of a woman, sitting on top of your other applications. Clicks go through the image and the opacity of the picture is set so that it doesn't bother the use of the computer. When the CPU use or the memory use or other custom measurements change, the image changes as well. The original would show a girl getting naked as the use of CPU went up. Since I couldn't use what images it should use, I did my own program in .NET. This blog post is about what I have learned about Windows Forms while creating this application.

Step 1: Making the form transparent



Making a Windows Form transparent is not as simple as setting the background transparent. It needs to have:
  • FormBorderStyle = FormBorderStyle.None
  • AllowTransparency = true
  • TransparencyKey = BackColor
However, when changing the Opacity of the form, I noticed that the background color would start showing! The solution for this is to set the BackColor to Color.White, as White is not affected by opacity when set as TransparencyKey, for some reason.

Step 2: Making the form stay on top all other windows



That is relatively easy. Set TopMost = true. You have to set it to true the first time, during load, otherwise you won't be able to set it later on. I don't know why, it just happened.

Update: I noticed that, even when TopMost was set, the image would vanish beneath other windows. I've doubled the property with setting WS_EX_TopMost on the params ExStyle (see step 4).

Step 3: Show the application icon in the traybar and hide the taskbar



Hiding the taskbar is as easy as ShowInTaskbar = false and putting a notification icon in the traybar is simple as well:
_icon = new NotifyIcon(new Container())
{
Visible = true
};
Set the ContextMenu to _icon and you have a tray icon with a menu. There is a catch, though. A NotifyIcon control needs an Icon, an image of a certain format. My solution was, instead of bundling an icon especially for this, to convert the main girl image into an icon, so I used this code.

Step 4: Hide the application from Alt-Tab, make it not get focus and make it so that the mouse clicks through



In order to do that, something must be done at the PInvoke level, in other words, using unsafe system libraries. At first I found out that I need to change a flag value which can be read and written to using GetWindowLong and SetWindowLong from user32.dll. I needed to set the window style with the following attributes:
WS_EX_Layered (Windows Xp/2000+ layered window)
WS_EX_Transparent (Allows the windows to be transparent to the mouse)
WS_EX_ToolWindow (declares the window as a tool window, therefore it does not appear in the Alt-Tab application list)
WS_EX_NoActivate (Windows 2000/XP: A top-level window created with this style does not become the foreground window when the user clicks it).

Then I found out that Form has a virtual method called CreateParams giving me access to the style flag value. Here is the complete code:
protected override CreateParams CreateParams
{
get
{
CreateParams ws = base.CreateParams;

if (ClickThrough)
{
ws.ExStyle |= UnsafeNativeMethods.WS_EX_Layered;
ws.ExStyle |= UnsafeNativeMethods.WS_EX_Transparent;
}
// do not show in Alt-tab
ws.ExStyle |= UnsafeNativeMethods.WS_EX_ToolWindow;
// do not make foreground window
ws.ExStyle |= UnsafeNativeMethods.WS_EX_NoActivate;
return ws;
}
}


However, the problem was that if I changed ClickThrough, it didn't seem to do anything. It was set once and that was it. I noticed that changing Opacity would also set the click through style, so I Reflector-ed the System.Windows.Forms.dll and looked in the source of Opacity. Something called UpdateStyles was used (This method calls the CreateParams method to get the styles to apply) so I used it.

Update: Apparently, the no activate behaviour can also be set by overriding ShowWithoutActivation and returning true. I've set it, too, just to be sure.

Step 5: Now that the form is transparent and has no border or control box, I can't move the window around. I need to make it draggable from anywhere



There is no escape from native methods this time:
private void mainMouseDown(object sender, MouseEventArgs e)
{
// Draggable from anywhere
if (e.Button == MouseButtons.Left)
{
UnsafeNativeMethods.ReleaseCapture();
UnsafeNativeMethods.SendMessage(Handle, 
UnsafeNativeMethods.WM_NCLBUTTONDOWN,
UnsafeNativeMethods.HT_CAPTION, 0);
}
}
Both ReleaseCapture and SendMessage are user32.dll functions. What this mouse down event handler does is say to the Window that no matter where it was clicked, it actually clicked the draggable area.

Step 6: Remove flicker



Well, I am getting a bit ahead of myself, here, the flickering becomes annoying only when I implement the blending of an image into another, but since it is also a style setting, I am putting it here:
SetStyle(ControlStyles.AllPaintingInWmPaint 
| ControlStyles.UserPaint
| ControlStyles.OptimizedDoubleBuffer, true);
This piece of code, placed in the Form constructor, tells the form to use a double buffer for drawing and to not clear the form before drawing something else.

Update: It seems the same thing can be achieved by setting the Control property DoubleBuffer to true as it seems to be setting ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint and ControlStyles.UserPaint seems to be set by default.

Step 7: Blend the images one into the other



Well, in order to make an image blend nicely into the next, I used a Timer. 10 times a second I would decrease the opacity of the first, increase the opacity of the second and draw them one over the other.

A small detour: if you think about it, this is not absolutely correct. A 70% opacity pixel blocks 70% of the light and lets 30% of the image behind show. If the image underneath has 30% opacity, then it shows 30% left from 30% of the image and it doesn't get opaque. But if I just set the opacity of the bakground image to 100%, it shows really strong on the parts of the images that are not overlapping, where image1 is transparent and image2 is not.

Unfortunately there is no resource friendly way to read write/pixels. It's either GetPixel/SetPixel in a Bitmap class (which are very slow) or using pinvoke again. I prefered to use the opacity hack which looks ok.

I was already using an extension method to invoke any change on the form on its own thread (as the Timer ran on its own thread and I would have gotten the "Cross-thread operation not valid: Control [...] accessed from a thread other than the thread it was created on" exception or "Invoke or BeginInvoke cannot be called on a control until the window handle has been created"):
public static void SafeInvoke(this Control control, Action action)
{
if (control.IsDisposed)
{
return;
}
if (!control.IsHandleCreated)
{
try
{
action();
}
catch (InvalidOperationException ex)
{
}
return;
}
if (control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action();
}
}

This is where I got the "Object is currently in use elsewhere" InvalidOperationException. Apparently the Image class is not thread-safe, so both the timer and the form were trying to access it. I tried locking the setter and getter of the Image property on the class responsible with the image blending effect, with no real effect. Strangely enough, the only solution was to Clone the image when I move it around. I am still looking for a solution that makes sense!

Step 8: Showing the window while dragging it



Using WS_EX_NOACTIVATE was great, but there is a minor inconvenience when trying to move the form around. Not only that the image is not shown while moving the form (On my computer it is set to not show the window contents while dragging it), but the rectangular hint that normally shows is not displayed either. The only way to know where your image ended up was to release the mouse button.

It appears that fixing this is not so easy as it seems. One needs to override WndProc and handle the WM_MOVING message. While handling it, a manual redraw of the form must be initiated via the user32.dll SetWindowPos method.

The nice part is that in this method you can actually specify how you want the form draw. I have chosen SWP_NoActivate, SWP_ShowWindow and SWP_NoSendChanging as flags, where NoActivate is similar with the exstyle flag, ShowWindow shows the entire form (not only the rectangle hint) and NoSendChanging seems to improve the movement smoothness.

Quirky enough, if I start the application without Click through set, then the rectangle hint DOES appear while dragging the window. And with my fix, both the image and the rectangle are shown, but not at the same time. It is a funny effect I don't know how to fix and I thought it was strange enough to not bother me: the rectangle is trying to keep up with the hot babe and never catches on :)

Step 9: Dragging custom images



I am a programmer, that means that it is likely to add too many features in my creations and never make any money out of them. That's why I've decided to add a new feature to HotBabe.NET: droppping your own images on it to display over your applications.

At first I have solved this via ExStyle, where a flag tells Windows the form accepts files dragged over it. A WndProc override handling the WM_DROPFILES message would do the rest. But then I've learned that Windows Forms have their own mechanism for handling file drops.

Here are the steps. First set AllowDrop to true. Then handle the DragEnter and DragDrop events. In my implementation I am checking that only one file is being dropped and that the file itself can be converted into an image BEFORE I display the mouse cursor hint telling the user a drop is allowed. That pretty much makes the ugly MessageBox that I was showing in the previous implementation unnecessary.

Step 10: Reading files from web, FTP, network, zip files, everywhere, with a single API



Reading and writing files is easy when working with local files, using System.IO classes, but when you want to expand to other sources, like web images or files bundles in archives, you get stuck. Luckily there is a general API for reading files using URI syntax in the System.Net.WebRequest class. Here is a sample code for reading any file that can be represented as an URI:
WebRequest req = WebRequest.Create(uriString);
using (var resp = req.GetResponse())
{
using(var stream= resp.GetResponseStream())
{
// do something with stream
}
}


WebRequest can also register your own classes for specific schemas, others than http, ftp, file, etc. I created my own handler for "zip:" URIs and now I can use the same code to read files, web resources of zipped files.

One point that needs clarification is that at first I wanted an URI of the format "zip://archive/file" and I got stuck when the host part of the URI, mainly the archive name, would not accept spaces in it. Instead use this format "schema:///whatever" (three slashes). This is a valid URI in any situation, as the host is empty and does not need to be validated in any way.

The rest are details and you can download the source of HotBabe.NET and see the exact implementation. Please let me know what you think and of any improvement you can imagine.

Monday, October 26, 2009

HotBabe.NET a new project at Github

I've stumbled upon this Windows port of a Linux application called HotBabe. What it does is show a transparent image of a girl over your applications that looks more naked as the CPU is used more. I wanted to use my own pictures and explore some of the concepts of desktop programming that are still a bit new to me, so I rewrote it from scratch.

The project is now up on Github and is functional. Please report any bugs or write any feature requests here or on the project page in order to make this even cooler.

Features:
  • Custom images responding to custom measurements
  • Custom measures (included are Cpu, Memory and Random, but an abstract class for custom monitor classes is included)
  • AutoRun, ClickThrough, Opacity control
  • Interface for custom images and custom monitors
  • XML config file


Update: After adding a lot of new features, I've also written a blog entry about the highlights from HotBabe.NET's development, a "making of", if you will. You can find it here: Things I've learned from HotBabe.NET.

Enjoy!

Dexter by Design by Jeff Lindsay

Book Cover After the horrible dissappointment with the third book from the Dexter series by Jeff Lindsay, I even forgot there was a fourth book coming. Thanks to my friend Meaflux, who kindly remembered me to not miss on my education as a serial killer, I found out the fourth book, Dexter by Design, was out and, (thank you, Jeff!), without any of the fantasy monster crap that made Dexter in the Dark so bad.

Dexter by Design was a really nice book. It captured the dark humour only a geeky psychopath would have, caught in a world of emotional people, it added a lot of tension, it went cursively from start to end. The only problem I could possibly have with it is that it made Dexter look bad, easily surclasses by not one but three people on three separate ocasions.

The conclusion is that it was one of the best, if not THE best in the series. Not a lot of killing is done, though, not by Dexter in any case. And if you are wondering, it has no connection with the third season of the Dexter TV series, except for the ending :).

Saturday, October 17, 2009

Exploring the Model-View-ViewModel pattern

This will be a long article, one that I intend to add on while understanding more about the MVVM pattern and patterns in general. Also, while I am sure I will add some code during the development of the post, this is intended mostly as a theoretical understanding of the said pattern.

For an easy and short explanation of the concepts, read this article: WPF Apps With The Model-View-ViewModel Design Pattern.

The start of every concept research these days seems to start with Wikipedia. The wiki article about Model View ViewModel says that MVVM is a specialization of the PresentationModel design pattern introduced by Martin Fowler specific for the Windows Presentation Foundation (WPF). Largely based on the Model-view-controller pattern (MVC).
Further reading from Martin Fowler's site on the MVC pattern, which seems to stand at the core of all this specialization, revealed this: Probably the widest quoted pattern in UI development is Model View Controller (MVC) - it's also the most misquoted. [...] In MVC, the domain element is referred to as the model. Model objects are completely ignorant of the UI. [...] The presentation part of MVC is made of the two remaining elements: view and controller. The controller's job is to take the user's input and figure out what to do with it. There is a lot more there, about how in the early MVC concept there were no events or binding of any sort. Instead the controller would get the input from the UI, update the model, then the View would change as the model changes using some sort of Observer pattern. Even from these few quotes, one can see that in this "holy trinity" there are actually two basic actors: the Model (which, to make it easier to differentiate later on from other models, I will call Data Model) and the Presentation (controller+view in MVC).
Let's see what the PresentationModel pattern is all about: Presentation Model pulls the state and behavior of the view out into a model class that is part of the presentation. The Presentation Model coordinates with the domain layer and provides an interface to the view that minimizes decision making in the view. The view either stores all its state in the Presentation Model or synchonizes its state with Presentation Model frequently. As I see it, it introduces a new model, one specific to the Presentation side but independent of the UI controls. Martin Fowler specifically says about the PresentationModel pattern: Probably the most annoying part of Presentation Model is the synchronization between Presentation Model and view. It's simple code to write, but I always like to minimize this kind of boring repetitive code. Ideally some kind of framework could handle this, which I'm hoping will happen some day with technologies like .NET's data binding. and Presentation Model allows you to write logic that is completely independent of the views used for display. You also do not need to rely on the view to store state. The downside is that you need a synchronization mechanism between the presentation model and the view. This synchronization can be very simple, but it is required.

I also find this article about different Model View Presenter patterns very informative and the diagrams easier to understand than Fowlers UML or whatever that horrible diagraming he uses is :)

This brings us to MVVM. It is basically the PresentationModel pattern, where WPF/Silverlight types of complex binding take care of the synchronization of View and ViewModel. For me, one of the most important aspects of this approach is that the complex interactions between UI components (and that don't involve the data in the DataModel) can be left in the View and completely ignored further down. That makes interchanging Views something very easy to do, as the entire "UI logic" can be separated from the more general presentation logic. In this, I see that the UI becomes a third layer by the introduction of the ViewModel/PresentationModel in between the Data Model and the Presentation.
I have imagined doing this in a Web or stricly Windows Forms environment. As Fowler said, the plumbing required for synchronization between the view and the viewmodel makes it not worth the effort. That is where the WPF Data Binding comes in.

Let's start the MVVM chapter with a simple example. There is a need to search people by using different filters, display the list of found people and give the ability to click a person and see the details in a separate detail pane. The filters can be simple (Google like textbox) or complex (specific role, age, etc searches). The complex filters of the search are hidden in a separate panel that can be shown or not.
An ASP.Net or Windows Forms application would probably create a form containing the searchbox, the additional filters in a panel with a checkbox or button to show/hide it, the details panel with textual information and a grid where the list of people would be displayed. Events would provide all the needed plumbing, with the code executed on them placed in the code behind of the form, changing what was needed. See, the code behind was already an attempt to separate the presentation from code, although the separation was mostly symbolic. One might have employed a flavour of the MVC pattern, creating a separate controller class that would have worked with the data model and the form (as a view) through interfaces. That means a lot of plumbing, anyway.
In WPF, one creates the form, as in the Windows Forms approach above, but then it binds no events (or very few, I will talk about that later). Instead, it uses data binding to link UI components to properties that it expects to find on the object that will be provided to the view as a DataContext, that is the ViewModel. It doesn't know what the format of this object is and, indeed, the properties are found using reflection, which makes this slightly slower than other methods.
What this means is that any code that reacts to a change of a UI component would be placed on an event handler of the property to which it is bound. When the property changes, stuff happens, not when someone clicks a checkbox. This makes the architecture a lot more testable from code, as all a test needs to do is change a property, not perform a click. It also means that a lot of extra plumbing must be done on those properties, for example the ViewModels could implement INotifyPropertyChanged and then notify on any property being changed. Also lists must not only inform on the get/set operations on them, but also on their items, which implies using ObservableCollection, ObservableDictionary, BindingList and other objects that observer their items and notify on change. On the Views, Dependency and Attached properties come into play , and I will link to some explanatory posts later on. They are extremely important in WPF, because they compute the value, rather than store it, but that's another story altogether.
What this also means is that events, in the way there are used in Windows Forms scenarios, are almost a hinderance. Events cannot be bound. If they are handled in bits of code that change properties in the ViewModel, then the code must either have a reference to a specific type of ViewModel, which defeats the whole purpose of MVVM, or to read/write properties using reflection, which means extra plumbing in the View code. Not that this cannot be done, and there are several solutions to that. However, it would be ugly to write a view completely in XAML, binding everything you need to properties that are to be found on the ViewModel, then starting writing code just for a few events. Here is where commands come in.
The Command pattern is an Gang of Four pattern, useful in WPF by providing objects that can be bound and that encapsulate a behaviour that will be executed. Read more about Commanding on MSDN. Many WPF controls exposes events as well as commands for common actions, for example the Button class exposes the OnClick event, but also the Command property (which will be executed on click) and the Clicked property (which will be set on click).
Commands in WPF implement the ICommand interface which exposes the Execute method as well as the CanExecute method. A default WPF button that has a command bound to its Command member will appear as disabled if the CanExecute method returns false, that because the ButtonBae class implements ICommandSource. More about commands when I present the RelayCommand class, which has become quite commonplace in the MVVM world.
A problem is that not all controls have a command for every concievable event. A solution is, of course, to inherit from the control and create your own command for a specific event. It only requires that you handle the event internally, expose a property that implements ICommand and execute that command inside the event handler. This brings the advantage that the control can be reused with minimal changes in the XAML. There are other solutions, one of them is to use Attached Properties. If you don't want an attached property for every event that you use, read this article. A very comprehensive article about the application of Commanding in WPF can be found here: WPF Command-Pattern Applied.

So far so good. Using the concepts above we can separate the UI from the data completely, as the View only uses binding on the Data Model and can be replaced with any other View that binds to existing properties. This pattern can be used on any level, be it the window or the user control level. Controls that are strictly UI, of course, don't need to implement MVVM. There are other aspects that were not covered here, more specific to WPF, like Routed Commands and Events and concepts like global messaging. But since they are not really part of the MVVM idea, I will leave them for other posts.
There is also the question of code. I will not be doing any in the post for now. However, I will be ending this with a few links that seem relevant.

Extra links:
Adventures in MVVM -- Ball of Mud vs MVVM
Hands-On Model-View-ViewModel (MVVM) for Silverlight and WPF
Exploring a Model-View-ViewModel Application; WPF Password Manager, Cipher Text

Another important thing to consider is the myriad MVVM frameworks out there, all of them implementing some helper classes and prewiring of applications. I was talking earlier about the RelayCommand. Imagine you want to create a ViewModel that exposes a Command. That command would need to implement ICommand, therefore being an object that has two methods: one to execute and the other to determine if it is possible. Creating a class for each such command would be tedious. The RelayCommand is a generic class of T (where T is the type of the command parameter) with a constructor that accepts an Action of T and a Func of T. You instantiate it with the methods in your class that are to be used and that is it.

I will update this material with more information as it becomes available and if I have enough time for it.

Thursday, October 15, 2009

Script elements with height (and scrollbar issues)

I've encountered this situations a couple of times, what happends is that, at the end of the body of the document or of a major element like a form or a page wide div, sometimes (I haven't really been able to reproduce it at will) hidden elements start having height. This includes hidden divs and spans and even script elements. It seems to be happening mostly on Internet Explorer, but the behaviour has reportedly also been found on Opera and even Chrome.

For a specific example, I had this page with a lot of script tags at the end of the form element. Curiously, only when some spans with display:none were added at the end of the body element the problem would become evident as the height of the page would increase by 12px and a vertical scrollbar would appear. I also encountered the issue when I moved, via script, the calendar popup div for a datetime editor at the end of the body element to solve a positioning issue. Both were happening in "quirks mode" because I am forced to use a HTML 4.01 Transitional doctype.

To me it seems that the browser considers that script tags have no layout, so there is no problem to put them all one above the other in that extra 12px bit, but it does consider it needs to reserve that 12px space. Well, does it have layout or doesn't it?

I looked on the web for people with similar problems and I have encountered very few that actually tackled it. Here is one example of a solution from the Perishable Press blog: Prevent JavaScript Elements from Breaking Page Layout when Following Yahoo Performance Tip #6: Place Scripts at the Bottom.

For short, the solution in the above link is to place all the scripts at the end of the page, but inside a hidden div element. If you have access to all the layout, that is a great solution. However, I found that I could not use it, since the scripts were not added by me and I had no control over their placements. So I found an alternative solution, after noticing that the extra size would dissappear if the popup div of a control was shown.

Well, my solution is quite obvious: if there are issues with hidden and script elements placed at the end of the page, then why not try to add an element at the end of the page and thus make hidden elements NOT be at the end? :)

A short jQuery script did it for me:
$('script').each(function() { 
if ($(this).height()>0 && !$('form').children(':last').is('div.scrollFix'))
$(this).parent().append('<div style=\'position:absolute;background:transparent;width:0px;height:0px;line-height:0px;font-size:1px;\' class=\'scrollFix\' />');
});
or, in normal Javascript:
var scripts=document.getElementsByTagName('script');
for (var i=0; i<scripts.length; i++) {
var script=scripts[i];
var parent=script.parentNode;
var lastChild;
if (parent&&parent.childNodes.length>0)
lastChild=parent.childNodes[parent.childNodes.length-1];
var isFixed=(lastChild&&lastChild.tagName&&lastChild.tagName.toLowerCase()=='div'&&lastChild.className=='scrollFix');
if (script.offsetHeight>0&&!isFixed) {
var div=document.createElement('<div style=\'position:absolute;background:transparent;width:0px;height:0px;line-height:0px;font-size:1px;\' class=\'scrollFix\' />');
parent.appendChild(div);
}
}


The script is improved by actually scanning the last element of the parent element for the hidden div so that it doesn't add a zillion divs, one for each script tag. However, it doesn't cover the situation where other elements, rather than the script elements, cause the problem. However, the principle remains sound.

Monday, October 12, 2009

The God of Clocks by Alan Campbell

Book coverThe last book (in story time) in the Deepgate Codex series, God of Clocks was a huge disappointment. It started nicely enough, preparing us for epic battles of wit and weirdness. Reading it, I was about to forget all about the slight drop in quality in the second book, Iron Angel, and was preparing for something grand. Then Mr. Campbell did what he never should have done: he altered the time space continuum. Before I knew it I was thinking at that old sci-fi movie where a ship boards another ship while in hyperspace and because of chaotical relativistic effects they all end up getting old, then young, then meeting themselves, fighting along their older grandsons, fighting the enemy with sticks and so on. For the love of God, I don't remember the name and I did Google it, but got only crap pages.

Anyway, Mr. Campbell, haven't you watched sci fi movies until now? Haven't you read a lot of SF books that make the same mistake, drowning in their own pool of possibilities. Time travel, unless it is the main subject, always messes up a story. And I was already confused with all the gods that were nothing more than angels with over inflated egos that anyone could capture and kill, the assassin that turned into mother-do-good, the boy demon who thought John Anchor was his father and that little child that is older and more powerful than him... so all this became very jumbled. No wonder a lot of the threads just remained hanging. What happened to Devon? Who the hell was the little girl? What did Carnival do? Everything just got negated by a race towards the beginning of time, when Ayen blocked the gates of Heaven. And then poof! A lot of fast scan scenes and the book ended. The fight never took place, or if it did, it was never described. And don't worry, if you preferred any other ending, there must be a broken timeline floating like a disolving icecube in a water glass that you can climb on and enjoy whatever reality you desire.

This book must be one of the most (if not THE most) WTF book I have ever read. In the end I was pacing, swearing and regretting my lost time. If the Deepgate Codex series would have been a video game, it would have never been released, with all the lack of documentation and obvious bugs.

My conclusion: what a nice beginning with Scar Night, but what a faltering fiasco up to and through God of Clocks. It did manage to make me think of a book where the main character would be Carnival, and all the rest would be just detail. I just loved her character and I feel so unfulfilled because it was never properly developed.

Resource not found when using Merged Dictionaries in WPF themes

I was creating this XAML to hold the design of all the controls in a library as a theme (generic.xaml). After a while it just got too big and so I had to use merged dictionaries to split the file into smaller parts.

First problem is that you can't just use the name of the file as the source of a ResourceDictionary, you need to specify the assembly name kind of like this:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Library.Namespace;component/Themes/OneOfMyControls.xaml" />
Notice the keyword component, which is NOT part of the folder or namespace structure.

The second problem is when you want to use merged dictionaries and then reuse a style key, for example, that you would expect to just place directly in generic.xaml or in the first merged dictionary. You will soon get a "Resource not found" error. Googling, one notices a lot of people having the same problem, but only in the generic.xaml/themes scenario. The solution is to add the common style file as a merged dictionary in each of the dictionaries merged in generic.xaml. That means that if you have 5 controls that use the same style and you have a xaml file for each control and one for the style, you need to add a MergedDictionaries entry in each of the 5 control files and merge the style xaml there.

Iron Angel by Alan Campbell

Book coverIron Angel starts where Scar Night left us. Even if the scope of the story now expands tremendously, doing credit to the author's imagination, I didn't feel so good reading it as I did Scar Night. Frankly, I don't know exactly why. It may have to do with the several character groups in the plot, which we follow separately for quite some time and that I know are bound to encounter each other or influence each others destinies. When that fails to happen for a long time, I get nervous. Also, while the description of hell was very nice, I found it difficult to swallow.

That doesn't mean it is not still a brilliant story, just that it seemed to falter a little in the middle. Now, almost close to the end of God of Clocks, I can say that the quality will improve, at least as measured from my own level of pleasure, although it doesn't get close to Scar Night yet.

I love that Alan Campbell really worked on his characters, making them very different to the formulas we are used to see in the field. Heroes are cowardly and impotent, women are strong, gods are flawed and some characters are simply likeable even if they don't see reason and exist for the sole purpose of physical revenge.

I can say that God of Clocks is at least intriguing, although I have to ask myself if the author didn't bite more than he can chew with the new concepts involved. Anyway, that is another post, coming soon on a blog near you.

Sunday, October 11, 2009

Inuyasha anime continues story

A while ago I was writing of the ending of the anime series, well before the story in the manga, leaving me wanting more. Well, a new series has been started that continues the plot. The English translated first episode of Inuyasha Kanketsu-hen has been released on the 4th of October 2009.

Wednesday, October 07, 2009

Select and change collation of T-SQL tables and databases

I could have sworn I wrote a collation article a while ago. Anyway, here are some links:
  • an article about getting and setting the collation for Transact SQL databases and tables:TSQL to change collation of database
  • A list of available collations
  • if you get a collation conflict error, you need to collate every join or where like in this example:select * from profile, userinfo
    where profile.custid collate database_default = userinfo.custid collate database_default

Attached properties in Windows Presentation Foundation

Attached properties allow you to add new properties and functionality without changing one bit of the code of the affected classes. Attached properties are quite similar to Dependency properties, but they don't need an actual property in the affected object. You have probably worked with one when setting the Grid.Column property of controls inside a WPF Grid.

How does one implement it? Well, any class can have the static declaration of an Attached property for any other class. There are decorative attributes that indicate to which specific classes the property should appear in the Visual Studio property window. The caveat here is that if the namespace of the class has not been loaded by VS, the property will not appear, so it is better to place the class containining the property in the same namespace as the classes that the property is attached to.

Well, enough with the theory. Here is an example:

public static readonly DependencyProperty SizeModeProperty
= DependencyProperty.RegisterAttached(
"SizeMode",
typeof (ControlSize), typeof (MyEditor),
new FrameworkPropertyMetadata(
ControlSize.Custom,
FrameworkPropertyMetadataOptions.OverridesInheritanceBehavior,
sizeModeChanged)
);

[AttachedPropertyBrowsableForType(typeof (TextBox))]
public static ControlSize GetSizeMode(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (ControlSize) element.GetValue(SizeModeProperty);
}

[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public static void SetSizeMode(DependencyObject element, ControlSize value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(SizeModeProperty, value);
}

In this piece of code I have just defined a SizeMode property for a class called MyEditor, the default value being ControlSize.Custom. To use it, I would write in the XAML something like MyEditor.SizeMode="Large" and it would attach to any DependencyObject. The FrameworkPropertyMetadataOptions flags are important, I will review them later on. This also declares a sizeModeChanged method that will be executed when the SizeMode changes.

The GetSizeMode and SetSizeMode methods are needed for the attached property to work. You might also notice this line: [AttachedPropertyBrowsableForType(typeof (TextBox))], decorating the getter, which tells Visual Studio to display SizeMode in the properties window of TextBox objects. Another possible attribute is [AttachedPropertyBrowsableForChildren(IncludeDescendants = true)] which tells Visual Studio to display the property for all the children of the control as well.

Now, how can this be useful? There are more ways it can.
One of them is to bind stuff to the property in Triggers or Templates like this: Binding="{Binding Path=(Controls:MyEditor.SizeMode), RelativeSource={RelativeSource Self}}". This is interesting because one can use in the visual UI properties that are not part of the actual code or ViewModel.
Another solution is to use the change method, but be careful that the method must consider all possible uses for the property and also it will not work for when you explicitly set the default value (as it doesn't actually change)! Let me detail with a piece of code:

private static void sizeModeChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
FrameworkElement elem = d as FrameworkElement;
if (elem == null)
{
throw new ArgumentException(
"Size mode only works on FrameworkElement objects");
}
switch ((ControlSize) e.NewValue)
{
case ControlSize.Small:
elem.Width = 110;
break;
case ControlSize.Medium:
elem.Width = 200;
break;
case ControlSize.Large:
elem.Width = 290;
break;
case ControlSize.Custom:
break;
default:
throw new ArgumentOutOfRangeException("e",
" ControlSize not supported");
}
}


Here I am setting the Width of a control (provided it is a FrameworkElement) based on the change in SizeMode.

Ok, that is almost it. I wanted to shaed some extra light to the FrameworkPropertyMetadataOptions flags. One that is very important is Inherits. If set, the property will apply to all the children of the control that has the property defined. In the example above I first set FrameworkPropertyMetadataOptions.Inherits as a flag and I got an error, because it would try to set the Width to children controls that were not FrameworkElements like Border.

Another interesting page that is closely related to this is I’ve created an Attached Property, now how do I use it? where an Attached property is used in a Behavior, which is actually implemented by the Blend team and, as such it is still in the Expression assembly. Here are two other pages about this:
Using a Behavior to magnify your WPF applications
The Attached Behavior pattern.

Scar Night by Alan Campbell

Book coverI was reading this interview of the guy from The Wertzone blog, a Sci-fi and fantasy blog that I enjoy reading, and he recommended some movies and some games and some books. So, on his recommendation, I started reading Scar Night, by Alan Campbell, and I have no reason to regret my decision (other than the one I will not be able to read another technical book until I finish the saga).

The writing style is nice, although I wouldn't say it rocked my world, however the world the author has envisioned is really great. Imagine a large city built upon great chains of alien metal, suspended over hell itself, inhabited by people worshiping a version of the devil, their church defended by angels called archons and armies of assassins. There is more, but you just have to read the book. What I also enjoyed tremendously is that the characters are very different from one another, ranging from mad scientists to priests corrupted by their desire for the greater good, from good hearted assassins to undead gods and inept cowardly angels.

I can only recommend you read this book, the first from the Deepgate Codex trilogy. Funny enough, the writer, Alan Campbell, was one of the authors of the Grand Theft Auto game, so he is also a software developer. I am hooked.

Friday, October 02, 2009

Major changes to the blog

As you may have noticed, I am now working on a new interface for communicating with my blog reader. It features the old Plugoo chat, a whiteboard like interface and a public chat along with administrative news. In the future I will probably also Google Wave.

That allows for the main blog to get simpler and more information friendly, while the other would serve for interaction with my friends and people that need my help.

Please leave a comment on any improvements you might want. It is important to me to get this right.

Tuesday, September 29, 2009

How to list the items in a Resource class

When you want to enumerate through the items in a Resource class, you find that its ResourceManager class doesn't have a method for it, only GetString or GetObject for when you know the key. The solution to get all of the items in a Resource class comes with the GetResourceSet method of the ResourceManager, which returns an IEnumerable class, but not a collection. The enumerator can be of different types, but by default it is a HashTable, therefore the items the enumerator returns are of the type of DictionaryEntry.

So the code is as follows:
var resourceSet = ResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, false, true);
foreach (DictionaryEntry resource in resourceSet)
{
DoSomethingWith(resource.Key, resource.Value);
}

Monday, September 28, 2009

There are 19 extra pixels in my scrollHeight and the scroll bar is showing!

I had this situation where in Internet Explorer, in quirks mode, I would open a dropdown calendar (so showing an absolutely positioned element that was until then hidden) and the scrollHeight of the entire page would increase by a magical 19px.

This was caused by a fix for another problem, where the displayed calendar would not position itself under the text input element where it should have positioned, so I made it so that the displayed calendar would be the last child of the body element. This way it would always show in the correct position, but displaying this situation when elements were trying to fit in the height of the page.

I could not find the cause other than a problem in the Internet Explorer render engine, but I did find a fix. Instead of placing it at the end of the body element, place it at the beginning. With jQuery that simply translates into:
if (!elem.parent().is('body')) $('body').prepend(elem);
Notice my use of prepend instead of append.

Tuesday, September 22, 2009

The Internet as an utopian tool

It has been a while since I've posted an entry about TED. In case you don't know what it is, go to ted.com and marvel of the interesting things one can find there. Well, in this post I am going to post two talks about the Internet. One talks about how concepts that would never have worked in real life have caught on in cyberspace (see Wikipedia, where people add information voluntarily, without any remuneration) and the second is about how the Internet can be used by totalitarian(?) states to oppress, rather than being a magic tool that spwens democracy. My comments are at the end of the post.





I have to say that Jonathan Zittrain's talk made me immediately think of Fidonet. Long before there was the ubiquitous Internet, amateurs would host Bulletin Board Systems where people could connect and send/read mail, download files and engage in social activities. Actually, one could think even further back, to pirate radio stations, that people would run on their own money (and seldom their own risk) without any chance of a profit.

So yes, given a method of reducing the cost of help significantly, I think a vast majority of people would help others without considering it a bother. However, to adapt the theory that any altruistic person is helping others because of personal reasons, therefore it is a form of egotism, I think a better way of putting it is: given a method of reducing the cost of coagulating in a group, people will enlarge their concept of clan and start doing stuff they would do for themselves for a lot more people.

That brings me to the second talk, Evgeni Morozov's,that would have been a lot more powerful if the guy would have stopped a few times to take a breath, right? :) He talks about the ease of using the Internet to determine the network structure of groups of people (clans again) and then striking where it is most effective with minimal cost to the establishment. There are mathematical algorithms that can do this automatically, just give them a graph of people and they will determine the leaders of opinion, the hubs of information. Then you can either persuade or remove them, giving you the power to control their entire "flock", just like pruning a bonsai tree to make it look like you want it to. And I think this system is a lot more used in democracies, rather than in totalitarian regimes, for the simple reason that despots have other options.

Both ideas seem to have a point in common, in my view, that in any strongly connected group of people leaders will naturally emerge , without any other reason than that they feel good about it, and stear a lot of passive people, whether in opinion or action. In an ideal situation, where all connections between people would be transparent (and I imagine Google is not far from having this kind of information), the entire humanity could be reduced to an active minority and an inertial mass of people.

This is interesting as a case study, because I am talking of an elite group of people, and not one that is organized, but one that is emerging naturally from chaotic personal behaviour. Something like Asimov's psychohistory could use that, with the axioms slightly modified to talk about "active population" as opposed to total population.

OutOfMemoryException in System.Drawing.Graphics.DrawImage

I was using these GIF images stored as embedded resources and suddenly I got an Out of memory exception from a component that I had no control over. All images were icon size, 16x16 or a little more, so a lot of the explanations for the error based on "you don't have enough memory!" (duh!) were not helpful. The images did have transparent pixels, and my gut feeling is that it all came from there.

I still don't know what caused it, but I did find a solution. Where I get the image I add an additional
image = image.GetThumbnailImage(image.Width, image.Height, null, IntPtr.Zero);
I know it's not something very intuitive, but it solved the problem.

The only significant difference between the image before and after the thumbnailization is the PixelFormat property that changed from PixelFormat.Format8bppIndexed to PixelFormat.Format32bppArgb.

The stack looks like this:
   at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
at System.Drawing.Graphics.DrawImage(Image image, Rectangle destRect, Int32 srcX, Int32 srcY, Int32 srcWidth, Int32 srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttrs, DrawImageAbort callback, IntPtr callbackData)
at System.Drawing.Graphics.DrawImage(Image image, Rectangle destRect, Int32 srcX, Int32 srcY, Int32 srcWidth, Int32 srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttr, DrawImageAbort callback)
at System.Drawing.Graphics.DrawImage(Image image, Rectangle destRect, Int32 srcX, Int32 srcY, Int32 srcWidth, Int32 srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttr)


And, using Reflector, I could go as far as pinpointing the error to the method System.Drawing.SafeNativeMethods.Gdip.GdipDrawImageRectRectI which wraps the gdiplus.dll GdipDrawImageRectRectI function. It returns error status 3, which is Out of memory, and that is that. I couldn't find a C++ code for the GdiPlus library and even if I had, who I am kidding? :)

Saturday, September 19, 2009

The Teaching Company. Realy nice courses on just about anything

My world view is limited by the data that comes to me. I have my tiny slice of reality, a few friends, my work, then there are movies, news, documentaries, the Internet and so on. You will notice that I placed them in a certain order, it is the order that to me seems to go from more bullshit and less information to more information. I never believed the expression "Truth is stranger than fiction", so lets set the slice of reality aside. And, being first on my list... full of bullshit :)

Movies teach me a lot, but there is just as much untruth and deceit in them as there is stuff worth knowing. News are focused on a part of life that normally doesn't interest me, but they still have a higher percent of useful information. Then there are the documentaries, stuff from Discovery Channel and the likes. Well, I have mixed feelings about those. There are things that they teach me and they do it in a pleasant manner, yet, by the time they end, I feel like there is so much more that I wanted to know and that it all just stopped when it got interesting. On further analysis, it seems the quantum of information in an hour of film was something I could blog in two or three paragraphs.

And then there is the Internet. It is bursting with information, if only I knew where to look and only if I had the discipline of researching, summarising and storing that information. I am working on that, even this blog is used to store what I find, but I am still only an amateur. There is something that attracted me a while ago, something called Open Courseware. There were courses from the largest universities, freely available on the net. However, they left me feeling disappointed as they were mostly text, the few that were in media format were mostly audio and, in the end, they were only poor recordings of classroom courses, sounds of scribling on the blackboard included.

Enter The Teaching Company, a company that produces recordings of lectures by nationally top-ranked university professors as well as high-school teachers. The lectures are well done, they feature some guy or gal that present the information without having to write stuff on blackboards. If anything is to be shown, it will be a computer slide or animation, while the details on spoken information are added to the screen (for example the names of people). Wonderful stuff, only it is not free.

If you go to the official site you will find courses on just about anything, priced at around 35$ per download and 70$ per DVD if they are "on sale" and the rest of them going to about 250$, with a range of 20-40 lectures per course. Of course, there is the option of looking for "TTC torrent" on Google and see what you find there. For the people in Africa that just got an Internet cable installed, I mean.

I had the luck to start with linguistics (Understanding Linguistics: The Science of Language by John McWhorter), lucky not because linguistics is so interesting, but because John McWhorter was really charismatic and had a very well constructed set of lectures. And because linguistics is an interesting topic, at least at the introductory level of this course. It was funny, too, the guy is what I imagine a typical New Yorker to be. He is black with a Scottish name, he talks a lot of Broadway plays and old movies, he is socially astute; very cosmopolitan.

Then I went for astronomy (New Frontiers: Modern Perspectives on Our Solar System by Frank Summers). If you like those National Geographic documentaries about the solar system, you will love this. Towards the end it got detailed in a bad way, but only compared with the beginning of the course, which was really well done. The lectures are about the Solar System, from the standpoint of a modern astronomer, in light of all the recent discoveries. Also, a very well made point about why the structure of the solar system was revised and Pluto got demoted. At the end it talks of other star systems and what are the methods to detect and study them.

Not all the courses are so good, though. I had the misfortune of trying out Superstring Theory: The DNA of Reality by Sylvester James Gates, Jr. The guy is a black man in his late fifties who tries to explain Superstring theory without using any mathematics. He starts by repeating a lot of what he said in previous lectures and, indeed, in the same one earlier on, then goes asking these stupid questions that repeat what he said again. Something like "As I said in a previous lecture this and this and this happened. But why did this and this and this happen?". Ugh. If it was only about that, I would have finished watching the course, but it was something completely unstructured, boring and dragging. After 12 lectures out of 24 I knew nothing about string theory, except vague things like "if I imagine a ball that goes towards another ball and they shout at each other and the waves make other balls while the previous balls disappear but wait they appear again...". What I knew is that I had to stop watching. Sorry, Mr. Gates, lecturing... just not your thing. Stick to short appearances on Nova PBS shows.

Right now I am on Building Great Sentences: Exploring the Writer's Craft by Brooks Landon. It talks about constructing good sentences in order to improve one's writing. I have the feeling that the guy uses more detail than necessary. Like when he explains a concept he has to give at least 5 examples, when 2 or 3 would have been enough. But then again, maybe I am wrong. I will have to finish the course to give you a definite opinion.

Next on my list:
Quantum Mechanics: The Physics of the Microscopic World by Benjamin Schumacher
Understanding Genetics: DNA, Genes, and Their Real-World Applications by David Sadava
Introduction to Number Theory by Edward B. Burger
Understanding the Brain by Jeanette Norden

Does all this make me a very smart person? Not really. Remember that most of these are introductory courses. They do not contain exercises or books that you need to read, nor do they require a very high level of previous knowledge in order to understand them. They are, pure and simple, like those Discovery Channel shows, only they don't end when they get interesting and they are not so full of bullshit. After watching one of these courses (or, indeed, listening to them as podcasts while you are going to work) you will have an idea on where to go digging deeper for the topics that interest you.

Good learning!