Lorenz Cuno Klopfenstein

Posts tagged "Programming"

When trying to build graphical interfaces on Linux with Mono, you have lots of choice. If you want maximum portability you can use Windows Forms (which don't look so great on Mono) or Gtk# (way better for multi-platform stuff). Both have a pretty standard look, even if WinForms look native only on Windows and Gtk does so on Gnome, and both work very well for standard desktop apps.

However, when doing more advanced graphics or targeting embedded systems, both fall short: WinForms runs OK on Windows CE (even if it is very limited), while Gtk looks pretty boring and may not be the ideal choice on resource constrained systems. The next multiplatform GUI choices that come to mind are Nokia's Qt or Intel's Clutter. Clutter is still a young project, but both frameworks unfortunately lack some good .NET bindings in essence.

In my case I'm starting to use Qt, through the Qyoto bindings. The latest Ubuntu distro already includes the package, which makes getting started pretty easy — at last if it weren't for the lack of documentation.

Qyoto provides a quite complete mapping of the Qt interface, but unfortunately mantains a lot of the original C++ “smell”: many enumerations are given as simple integers, events (the signal/slot system in Qt) don't rely on .NET events but require you to bind methods to signals by their untyped name. Less of a problem, but still not very pretty: in many points Qyoto doesn't respect the common .NET naming conventions and some Qt methods should really be mapped to properties.

Anyway, these minor criticisms notwithstanding, Qyoto provides a simple and complete way to use Qt's power from C#. Let's take a look to a simple example application.

More...

Posted on Wednesday, July 07, 2010
203 Views
1 comments posted

Aero in Windows Vista introduced the new glass windows and a nice set of APIs that allow developers to change glass and blur settings. One of the options allows to extend the glass frame from the “non-client” area to the inner parts of the window. This effect is used by many applications of Windows itself (Windows and Internet Explorer for instance, or Media Player — before they dropped the glass in Windows 7).

To understand how this works, firstly let's take a look to how a standard window is structured in Windows:

Windows areas.

A window is composed of many separate areas. The most important one in our case is the non-client area which includes many other parts (for instance the caption, i.e. the title and icon of the window). This area surrounds the central rectangular client area, which is the space where the application draws its own contents.

The whole non-client area is composed of glass in Aero: when extending the glass frame, you are effectively allowing Windows to draw its glass effect inside the client area where you too are drawing the contents of the window. Combining what you and Windows draw together can be tricky (you must draw using GDI and not GDI+ in order to handle alpha transparency and the background of your windows must be black on the glassy area), but it isn't too hard.

However, most applications that extend the glass frame allow you to drag and move the window if you click anywhere on the glass. This makes sense for the users but doesn't work out of the box: after all, even if clicking on glass, the clicks still end in your client area and must be handled by the application. To let Windows handle the clicks and enable dragging, you essentially must not only extend the glass area, but also the whole caption area inside your window (since the caption is the part of window usually in charge of handling mouse dragging). The resulting layout would look like this:

Windows areas.

How do you tell Windows that what was your client area should be considered part of the caption? Windows has a simple way of determining which parts are what: it sends WM_NCHITTEST messages asking your window directly. The message stands for “non-client hit testing” and the result you pass back to the window manager describes the area the mouse pointer is currently hovering on.

protected override void WndProc(ref Message m) {
	base.WndProc(ref m);

	if (m.Msg == WM_NCHITTEST && m.Result.ToInt32() == HTCLIENT) {
		uint lparam = (uint)m.LParam.ToInt32();
		ushort x = (ushort)lparam;
		ushort y = (ushort)(lparam >> 16);

		if(PointerOnGlass(x, y)){
			m.Result = (IntPtr)HTCAPTION;
			return;
		}
	}
}

const int WM_NCHITTEST = 0x84;
const int HTCLIENT = 1;
const int HTCAPTION = 2;

By putting this snippet of code in your WndProc method you'll tell the Window Manager to consider the pixels on glass of your client area as part of the window's caption area instead. This will automatically enable dragging, Aero Snap and so on.

If you use the WindowsFormsAero library, you can simply use the GlassForm helper class and derive from it. The form handles all glass-related stuff automagically (you simply have to set the glass margins you want). It also allows you to hide the window's title and icon in a simple way. Check it out!

Posted on Thursday, July 01, 2010
152 Views
3 comments posted

I have been tinkering around my "home brewed" dependency injection library, as I mentioned in my last post. Since most of the code revolves around instantiating objects (well, and keeping them orderly registered), I figured it couldn't hurt to check out which is the best (i.e. fastest) way to dynamically instantiate objects in .NET.

There are essentially two ways you can register objects to my IoC container: using a delegate or using the type. The delegate is a really nice method, also used by Autofac (any comparison between my library and Autofac is probably an insult to Autofac  :)). It works like this:

container.Register(c => new Implementor());

In this case the delegate simply instantiates an instance of a class that implements the IInterface interface. Pretty slick and also very fast: calling the delegate is exactly one method call slower than calling the new operator, so that shouldn't be a problem at all.

Problem is, sometimes you can't register a delegate (for instance when you're registering dynamically loaded plug-ins to the container). In that case you need to manually instantiate the objects: .NET provides a lot of different ways to do that, and some methods can be compiled to dynamic methods or to delegates which probably should improve their performance.

There's a pretty complete blog post by Haibo Luo, but it's 5 years old and might not be accurate (it also misses the methods that use System.Linq.Expressions).

More...

Posted on Monday, January 11, 2010
582 Views
3 comments posted

I have been implementing a simple and easy to use IoC library: I need a simple solution and big frameworks like Spring.net offer way too much stuff (even Autofac is getting huge). My implementation is composed of some basic container, some simple instantiation logic and some stuff to do automatic property injection. Nothing more.

In order to keep a collection of all singleton instances registered in the IoC container, I needed a thread safe dictionary implementation. There are a lot of discussions about how to do it right: the agreed point is that it isn't simple, mainly because you're working at the wrong level of abstraction.

Either you get a lock on each single IDictonary method, that would result in tons of locking with potentially incoherent results between one call and the other. Or you expose a more complex interface, like they did with ASP.NET MVC's RouteTable collection, and leave locking to the user.

I decided to do something in between, using ReaderWriterLockSlim from .NET 3.5 instead of a simple lock{} and writing a fine grained IDictionary implementation while also exposing some high level methods to obtain coherent and really thread safe results.

More...

Posted on Friday, December 18, 2009
Tagged as
3531 Views
554 comments posted

While working on OnTopReplica I needed a way to constrain the aspect ratio of the "cloned" window. Since the live thumbnails created using the DWM API cannot be manipulated and always maintain the aspect of the original window, it makes sense to limit the user's choices in resizing the window, in order to fit the window to the cloned thumbnail automatically.

Much like in the case of media players, where video files have a certain aspect ratio (let's ignore that this ratio can usually be changed by the user). If the video doesn't fit inside the player window, black bars are added on top and bottom or on the sides. Limiting the user's resizing options in this case actually improves the interface experience because a tedious task is handled directly (like searching the right size of the window to reduce the black bars).

In Windows Forms you have two options to react to resize events of the window: the OnResize event and the couple OnResizeBegin and OnResizeEnd. The problem of those two methods is that they both run after the window has been resized. That is, after the window received the WM_SIZE message (in Win32 terms). You can force the window to adopt a correct size after receiving one of those events.

This would work, if it weren't for the option "Show window contents while resizing" (added a long way back in Windows 98, more or less). That option (which is usually on by default) causes the window to generate a lot of WM_SIZE messages while it is being resized. If you react by changing the size on each event, the result is an extremely jerky window that jumps back and forth while the users tries to resize it. And the contents of the window flicker awfully as a result.

More...

Posted on Sunday, November 08, 2009
Tagged as
600 Views
4 comments posted
Last.fm logo

I've had an account on Last.fm for more than 3 years and liked it on the spot. I love to explore new music, discover new artists, listen to streaming radio (that is, until it was free) and especially scrobbling the music I listen!

The geek in me simply freaks out seeing the amount of stats you can get from your Last.fm "scrobbled" data: the music I listened the most this week? Last month? What is my favorite Porcupine Tree song? In fact there's also lot of external services that offer awesome visualizations of your data.

This was great up to the day when I decided to put my whole music collection on the Windows Home Server and listen to it via the built in UPnP media sharing in Windows Media Player. That day I discovered that the Windows Media Player plug-in doesn't scrobble songs on network shares! It doesn't work, neither from an SMB shared folder, nor directly through UPnP sharing (which in fact is HTTP streaming).

More...

Posted on Wednesday, November 04, 2009
53550 Views
16 comments posted

I have started to work on WPF GUI programming again, and finally found out how to use nested styles in an application (pretty basic, I know, but I'm slowly getting to know the framework on my own  :)).

So, starting from the basics, to embed some global styles in the application, you can define an external ResourceDictionary (much like an external CSS stylesheet):

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <!-- Colors -->
    <Color x:Key="WhiteDark" A="255" R="238" G="240" B="245" />
    <Color x:Key="WhiteBright" A="255" R="254" G="254" B="254" />
    <!-- ... -->
	
    <RadialGradientBrush x:Key="PaleBackgroundRadial" Center="0.8,0.8" GradientOrigin="0.8,0.8"
                         RadiusX="0.8" RadiusY="0.7">
        <GradientStop Offset="0" Color="{StaticResource WhiteBright}" />
        <GradientStop Offset="1" Color="{StaticResource WhiteDark}" />
    </RadialGradientBrush>
    <!-- ... -->
	
</ResourceDictionary>

In order to reference those resources in your code (using their x:Key name), you must embed the dictionary where it is needed. The simplest solution is to embed all styles at an application level:

<Application x:Class="Application"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="MyResourceDictionary.xaml" />
                <!-- other dictionaries -->
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
    
</Application>

Now, everywhere in your XAML code you'll be able to reference one of your styles, for instance:

<Rectangle Background="{StaticResource PaleBackgroundRadial}" />

Now, if you - like me - are used to web programming using CSS and HTML, you'll expect to be able to define a "class" with a custom style and then specify additional styles for all nested tags in an element of that class. You could for instance define a class for a menu and then define another (nested) style for all <b> bold tags inside it:

.menu {
    width: 200px;
    font-size: 0.8em;
    background: red;
}

.menu b {
    font-size: 1.2em;
    color: blue;
}

The definition for the bold tag will only be applied to <b> elements inside the element with the "menu" class. The same can be done in XAML, albeit in a somewhat different way:

<Style TargetType="{x:Type Window}" x:Key="GlossyWindow">
    <Setter Property="Background" Value="{StaticResource GlossyBackground}" />
    <Setter Property="TextElement.FontFamily" Value="Segoe UI" />
    <Setter Property="TextElement.Foreground" Value="White" />
    <!-- Other setters, trigger, etc... -->

    <!-- NESTED STYLES -->
    <Style.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Margin" Value="3.0" />
            <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Grid>
                            <Rectangle />

                            <ContentPresenter />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        
        <Style TargetType="{x:Type Menu}">
            <!-- Setters, triggers, etc... -->
        </Style>
    </Style.Resources>
</Style>

The effect of the XAML code above is that if you define a Window's style as "GlossyWindow", automatically all buttons and menus contained in that same window will have the nested styles applied (in addition to other styles you might have explicitly set on each button or on each menu).

This allows you to efficiently mark only a root element as being styled and apply a custom appearance to all nested elements in the XML structure. However, using nested styles can get you some quite... nested XAML code: the code above is still readable, but obviously if you start using more nested levels you'll end with a huge XML hierarchy.

To clean the code up, define each single style individually and then declare the nested styles hierarchy by "basing" them on the previously defined templates (this is done by using the BasedOn attribute on your styles and referencing the styles above by their dictionary key):

<Style TargetType="{x:Type Button}" x:Key="GlossyButton">
    <Setter Property="Margin" Value="3.0" />
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid>
                    <Rectangle />

                    <ContentPresenter />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style TargetType="{x:Type Menu}" x:Key="GlossyMenu">
    <!-- Setters, triggers, etc... -->
</Style>

<Style TargetType="{x:Type Window}" x:Key="GlossyWindow">
    <Setter Property="Background" Value="{StaticResource GlossyBackground}" />
    <Setter Property="TextElement.FontFamily" Value="Segoe UI" />
    <Setter Property="TextElement.Foreground" Value="White" />
    <!-- Other setters, trigger, etc... -->

    <!-- NESTED STYLES -->
    <Style.Resources>
        <Style TargetType="{x:Type Button}" BasedOn="{StaticResource GlossyButton}" />
        
        <Style TargetType="{x:Type Menu}" BasedOn="{StaticResource GlossyMenu}" />
    </Style.Resources>
</Style>
Posted on Tuesday, May 19, 2009
Tagged as
1849 Views
0 comments posted

UTF I already posted about the problems I ran into using UTF-8 encoding on MySQL and PHP. Unfortunately, MySQL still seems to not be completely happy about Unicode characters, even if you work with ASP.NET and NHibernate (which both have complete Unicode support by default).

Therefore, in order to get your UTF strings stored in the database and get them back correctly in .NET, you'll first have to specify the charset you're using for the database connection in your connection string. For instance:

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
	<reflection-optimizer use="false"/>
	<session-factory>
		<property name="dialect">NHibernate.Dialect.MySQL5Dialect</property>
		<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
		<property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
		<property name="connection.connection_string">
		Server=localhost;Database=db_name;User ID=user_id;Password=pwd;charset=utf8
		</property>
		<!-- other properties -->
	</session-factory>
</hibernate-configuration>

As far as I know, this should be equal to sending the "SET NAMES utf8;" command I used to send in PHP.

Then, you must ensure that your database tables actually use the Unicode encoding to store strings. This is especially true if your table creation SQL is automatically generated by NHibernate, through the GenerateSchemaCreationScript() method, because NHibernate will just use the default encoding (not Unicode). On Microsoft SQL Server it will instead use the Unicode column types like "nvarchar" and "ntext", preventing any problem.

Hence, when you create a new database, explicitly define the charset to use or MySQL will default to latin1:

CREATE DATABASE db_name
    DEFAULT CHARACTER SET utf8
    DEFAULT COLLATE utf8_unicode_ci;

Then you can normally create all your tables and start using them. Test the database using some uncommon characters, like the "famous" dotless turkish ı, and try to do some upper/lowercase conversion on the database.

Posted on Tuesday, May 12, 2009
338 Views
0 comments posted

Yesterday I posted about genetic algorithms. Now it's time to put a GA to use and solve a very simple problem: in this case, generating boolean logic gates until one of them behaves exactly like a logic XOR gate.

XOR truth table Boolean logic gates take one or more boolean values as input (in our case, value A and B) and return a single boolean response value. Their behavior can be expressed by a so called truth table: in XOR's case, the gate will return True if the two input values are different, while it will return False if both are true or both are false.

More...

Posted on Saturday, May 09, 2009
934 Views
0 comments posted

Double helix by ?mrhappy? I decided to write a couple of posts about a topic I have been working on a couple of years ago and I still find very interesting: Genetic Algorithms.

Genetic Algorithms are very general methods, based on the same mechanisms the biological theory of evolution is built upon, that can be successfully applied to solve optimization or search problems, without having to resort to a well known solution or a fully described algorithm.

Very generally speaking, genetic algorithms can be seen as a form of heuristic that approximates a possible solution for a problem by improving it step by step. Evolution in biology depicts how a population of simple organisms eventually can evolve in functioning complex life forms, whereas genetic algorithms apply the same incremental approach to the solution of mathematically defined problems.

Genetic Algorithms can also be made to mimic intelligent behavior and can be seen as a form of Artificial Intelligence. Even if the algorithm's process is basically "dumb" (and blind), its emergent behavior in response to changes in input can be easily mistaken as "awareness" by a human user.

More...

Posted on Friday, May 08, 2009
1491 Views
71 comments posted
Back to Klopfenstein.net
Clemens Klopfenstein Serena Kiefer Lukas Tiberio Klopfenstein Lorenz Cuno Klopfenstein
English German