Monday 26 October 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 17 October 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 15 October 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 12 October 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.

Sunday 11 October 2009

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.

Wednesday 7 October 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.

Tuesday 6 October 2009

Friday 2 October 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.