Lorenz Cuno Klopfenstein

Posts tagged "Programming"

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
159 Views
1 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
573 Views
91 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
195 Views
2 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
3211 Views
11 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
1135 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
240 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
606 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
947 Views
12 comments posted

While working on the XNA Contest I wanted to use a standard Windows Forms dialog for credits at the end of the game, instead of doing it all inside XNA (mostly because it would have been much easier and faster to do). At the moment, when the game is over, this dialog appears:

My game's credits

The problem is that, as soon as the XNA window closes and the game terminates, the XNA framework tears down the entire thread on which it was running. If you try to open a Windows Forms dialog at that point, you will see a glimpse of it for some millisecond if you're lucky.  :)

The solution is a pretty simple workaround, but since I tried a lot of different things before and wasted some time, I thought this might by interesting to share: essentially, you run the whole XNA game in a different thread than your main thread. When XNA closes its window, it will tear down the other thread you created, leaving you with the main thread still running.

static void Main(string[] args) {

	Application.EnableVisualStyles();

	//Separate thread on which the game will run
	Thread backThread = new Thread(new ThreadStart(delegate() {
		using (Main game = new Main()) {
			game.Run();
		}
	}));

	backThread.Start();

	//Wait for the game to end
	backThread.Join();

	//Credits dialog
	using (Credits c = new Credits()) {
		c.ShowDialog();
	}
}
Posted on Wednesday, February 11, 2009
719 Views
50 comments posted

Yesterday I passed the exam in Logic Programming: a very interesting declarative programming style based on the foundations of mathematical logic.

Take this as a short, very vague, introduction: logic programming works by defining some logic clauses in your program and then applying a resolution algorithm on a particular query (the logical clause you are trying to "prove" according to logic inference rules). The logic interpret will then determine whether your query is a logical consequence of the program or not, i. e. the query is satisfied and a valid result was found.

More...

Posted on Thursday, February 05, 2009
233 Views
2 comments posted
Back to Klopfenstein.net
Clemens Klopfenstein Serena Kiefer Lukas Tiberio Klopfenstein Lorenz Cuno Klopfenstein
English German