rss

DBus Explorer 0.4 Christmas release

4

Category : C#, DBus Explorer, English, Mono, Programming

Finally after months of postponing the 0.4 release of D-Bus Explorer I managed to get it out as a Christmas/New Year present :-) . For the impatient you will find download link at the usual place.

For those who doesn’t know what D-Bus Explorer is, it’s a little tool I wrote up a long time ago which allows to browse D-Bus bus services and services’ API. It’s similar in concept to dbus-viewer or DFeet with extra feature which make it sweet when you work with C# and Managed D-Bus.

For instance when you want to know the signature of a method/event/property it’s both shown with D-Bus own syntax and C# syntax. In this release this mechanism is extensible to other language though only C# is provided at the moment.

2008-12-27-215012_802x625_shot1

Coming to this release is also a C# generator which will create the necessary interface definition for use with Managed D-Bus. Simply right-click on the path / interface you want to use in your program and save it somewhere. Again this is extensible to other language.

2008-12-27-215639_802x625_shot3

In other news, the interface is now fully tabbed to let you browse different API at the same time.

2008-12-28-174241_802x625_shot4

Happy D-Bus hacking !

Parallel goodness

3

Category : C#, English, Google Summer of Code 2008, Mono, Programming

I think I pretty much arrived to the point where my work is starting to get useful. With yesterday basic Tasks implementation and today Parallel.For work I was able to run a parallelized version of Luke’s C# RayTracer. There was already a version using ParallelFx in the CTP samples but I preferred to made my custom, simpler one :

After some micro-benchmarking on my dual-core system the overall speed improvement is around 42%. Deductively it should be 50% but due to the work-stealing algorithm overhead it’s a little less. Still it’s a good improvement over the classic and synchronous version.

Like the folks at the ParallelFx blog did I added some color mask to show which thread was doing the work :

As we can see the work is almost homogeneous between each of the processor. The small delta is explained by the fact that while one of the thread is in the middle of queuing all the work, the other is already processing it.

The code for the parallel ray tracer is here : http://monoport.com/25053. If you want to test it out grab a copy of the source from here in addition (warning : it’s probably full of bugs and won’t work on your system ;) ). Run the program with --thread-mask for the color mask.

Beware of double.Parse()

2

Category : C#, English, Mono, Monodevelop

Some svn up ago, Monodevelop started to throw strange exceptions at my face about Format error occuring when parsing a string with double.Parse(). This was triggered in various places ranging from startup, project opening, file opening or application unloading. At the time I hadn’t bothered tracking down the issue but last Monday I decided to investigate it. Turned out that double.Parse was throwing a FormatException about ‘.’ (like in « 12.68″) which was considered unknown.

After poking and modifying some stuff in Double.cs the problem was remaining. So, I made a really simple test case that I pasted below :

using System;

class DoubleFormatTestCase
{
  public static void Main()
  {
	Console.WriteLine(double.Parse("12.68"));
  }
}

Compiling it and running it on my machine threw the same exception that in Monodevelop. I admit this puzzled me completely as I was thinking that, programming language speaking, floating numbers were always represented like this in their textual form.

After asking in #mono, yakeen suggested replacing the simple double.Parse(string) with double.Parse(string, CultureInfo) like this :

using System;
using System.Globalization;
class DoubleFormatTestCase
{
  public static void Main()
  {
	Console.WriteLine(double.Parse("12.68",
                    CultureInfo.InvariantCulture.NumberFormat));
  }
} 

And if you try this code it should work no matter your platform or your language.

Why that ? Because as you should know (and as I should have remembered :P ) .NET/Mono enforces that things like string comparisons, DateTime handling or long.Parse (in our case) are made according to the user culture. Indeed, here in France, when we write floating numbers, we use ‘,’ and not ‘.’ to separate the integer and floating part. This syntax difference explained why long.Parse(string) was borking on my system.

You can also re-run the first test like this : LANG=en_EN mono DoubleFormatTestCase.exe. Normally it should run without problem.

The moral of the story : always use double.Parse(string, System.Globalization.CultureInfo.InvariantCulture.NumberFormat); instead of double.Parse(string) when doing conversion between string and double in a persistent way (configuration files, intern calculations) and only use the latter when you have to exchange with the user.

Btw, with big kudos to yakeen, I submitted a patch to Monodevelop to correct the problem. It should be available soon.

CoverFlow finalized

2

Category : C#, English, Programming, School

Maybe some folks remember the CoverFlow GTK# widget I talked about a while ago. I had left it in an undetermined state but today I managed to clean it and make it the work the way I intended.

For the little background, I want to use that widget as part of a presentation I will make at school, in two weeks, on creating C# softwares on Linux with Mono. During the presentation, I will make attendees do a simple app which ask, via a GTK# GUI, some informations about an artist, do a query on musicbrainz, parse the reply and, finally, display the cover art of the artist’s albums. That’s why I thought coding a CoverFlow widget would provide a more aesthetic look than a bare Image widget (and, at a same time, allow me to practice graphic programming ;) ).

Anyway, for the technical side the code doesn’t do too fancy things. For a start it’s not even accelerated or OpenGL-enabled (would be fun to do a Clutter port), it’s just good-old-gdk and System.Drawing operations on bitmaps with a DrawingArea. There is no animation too, it would probably flicker too much and eat CPU which isn’t the purpose. Finally I used the traditional way of manipulating pixel, no pointer black magic in the code.

I will post the code somewhere tomorrow or later but, in the meantime, here is a screenshot showing Nightwish (\o/) discography :

C# vs. Python

2

Category : C#, Design, English

That post isn’t a in-depth comparison of the two languages because it would require lot of time and, in the end, I don’t find that sort of thing particularly pertinent. It’s just a side-by-side presentation of the same script, written in both languages, assorted with my « it’s just my opinion »-type of comments.

Without further introduction, here is the Python version :

#!/usr/bin/env python

import dbus, gobject, dbus.glib

NICK = "Kiri"
CHAN = "#riverotte"

bus = dbus.SessionBus()

obj = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface")

obj = bus.get_object ("org.xchat.service", "/org/xchat/Remote")
xchat = dbus.Interface(obj, "org.xchat.plugin")

away = False

def statuschangementCallback(acctID, old, new):
	global away
	cur_status = purple.PurpleSavedstatusGetCurrent()
	message = purple.PurpleSavedstatusGetMessage(cur_status)

	if (purple.PurpleSavedstatusIsIdleaway() == 1):
		message = "aw"

	message = message.replace(" ", "_")
	if (len(message) > 8):
		return
	serv_id = xchat.FindContext("", CHAN)
	xchat.SetContext(serv_id)
	xchat.Command("nick "+NICK+"`"+message)
	if (purple.PurpleSavedstatusGetType(cur_status) == 5):
		xchat.Command("away")
		away = True
	elif (away):
		xchat.Command("back")
		away = False

bus.add_signal_receiver(statuschangementCallback, dbus_interface="im.pidgin.purple.PurpleInterface", signal_name="AccountStatusChanged")

gobject.MainLoop().run()

And here is the C# version :

using System;
using GLib;
using NDesk.DBus;

[Interface("im.pidgin.purple.PurpleInterface")]
public interface PurpleInterface
{
int PurpleSavedstatusIsIdleaway();
int PurpleSavedstatusGetCurrent();
string PurpleSavedstatusGetMessage(int status);
int PurpleSavedstatusGetType(int status);
event StatusChangedEventHandler AccountStatusChanged;
}

[Interface("org.xchat.plugin")]
public interface XChatInterface
{
uint FindContext(string serv, string channel);
void SetContext(uint cont);
void Command(string cmd);
}

public delegate void StatusChangedEventHandler();

class Plugin
{
const string Nick = « Kiri »;
const string Chan = « #riverotte »;

static bool away;

public static void Main()
{
MainLoop ml = new MainLoop();
BusG.Init();

XChatInterface xchat = Bus.Session.GetObject(« org.xchat.service », new ObjectPath(« /org/xchat/Remote »));
PurpleInterface purple = Bus.Session.GetObject (« im.pidgin.purple.PurpleService », new ObjectPath(« /im/pidgin/purple/PurpleObject »));

purple.AccountStatusChanged += delegate {
int cur_status = purple.PurpleSavedstatusGetCurrent();
string message = purple.PurpleSavedstatusGetMessage(cur_status);

if (purple.PurpleSavedstatusIsIdleaway() == 1) {
message = « aw »;
}

message = message.Replace( » « , « _ »);
if (message.Length > 8) return;

xchat.SetContext(xchat.FindContext(«  », Chan));
xchat.Command(« nick  » + Nick + « ` » + message);

if (purple.PurpleSavedstatusGetType(cur_status) == 5) {
xchat.Command(« away »);
away = true;
} else if (away) {
xchat.Command(« back »);
away = false;
}
};

ml.Run();
}
}

Preliminary

First of all, one may find that the Python code is shorter. But if you remove the boilerplate code (the interfaces and delegate), which could be both autogenerated with a future release of D-Bus Explorer anyway (ad inside ;) ), the overhead is about 3-4 lines ({ } included). So no real advantage there.

Readability != Conciseness

Now for readability. Python has always been praised for being concise and all. Why do I say ‘concise’ there ? Because IMHO conciseness and readability aren’t the same things at all.

When friends show me a OCaml sexy hack, the first thing I reply is « and what does it do ? ». Don’t mistake me, I don’t use OCaml that much and sure these things come with habit, but nonetheless, I’m not completely alien to the programming style and, even with that knowledge, I can’t tell what a « concise » 20 lines OCaml program do. You can call me dumbass but I’m pretty sure I’m not the only one in this case. Anyway, all of this to illustrate that, at least for some people (which I’m part of), these two concepts of readability and conciseness are not equivalent.

Returning to our matter, I think the previous story illustrate the case of the C# example. Indeed, it may not be shorter at first sight but (and I’m convinced about that) even if you never programmed in C#, you know, with a quick glance, what it does. Verbosity is not a bad thing if it’s not extreme (read, VB). Complain about that in comments, with arguments, if you disagree.

Of course, it can hold true for the Python snippet too. This first part was just to clear the idea that conciseness ⇔ readability.

Tackling the binding problems

Now there is another important aspect to take care (in my sense) : language integration. I won’t talk about the ‘global away’ line and the inherent block semantic which I find strange in a « Python is the C programmer best friend » context as it’s more a personal preference. However, since we are talking about C, I just can’t see the design difference between the Python snippet and an equivalent C one coded with libdbus so what’s the advantage to use Python over C for D-Bus ? In fact, what I want to point out is that having binding is good and all, but, IMHO, having integrated binding is better. What do I mean by integrated ? Well, look at the C# code and you will see several things which make Managed D-Bus « integrated » compared to dbus-python :

  • Real polymorphism with interface and genericity (What GetObject is doing ? I don’t care, I have my interface definition for reference purpose).
  • No dbus.Interface, everything is handled thanks to attribute and reflection.
  • Integrated events, not a silly bus.add_signal_receiver() C-ism.

All of that allow D-Bus specific calls to blend more nicely in the rest of the application. To the contrary, I often see Python scripts which look more like a patchwork of different paradigm and convention style.

Having an interface-based way to access DBus’ methods also provides type safety (provided that you don’t fight with your keyboard or that you use the kind of autogenerating tool I described before) and I’m pretty sure your computer who-doesn’t-like-runtime-error will also be happier. And with a tool like D-Bus Explorer you don’t have to search tons of docs for type informations (still ad inside).

This last point is more debatable since it touches the more general philosophy of dynamic typing against static typing. My general stance on that is that, even if dynamic typing simplifies the process of writing the first code, it’s very damageable at the end for several points (which are also valid in our test case) :

  • Type information is « volatile » meaning that, even if you know what that function of yours is supposed to return when you write it down, chances are that you will have to re-read the whole thing (or check the doc, or take a look at the unit testsn or something else time-consuming) later to remember what it does because, well, time and coffee do their job. Whereas in static typing langage, if the API is well made and if you have some sort of auto-completion, you can pretty most always deduce things from the full prototype.
  • Continuing from point 1, it’s even worse for those guys who have to understand what you did before writing their own code.
  • It’s not robust by default : you have to write unit tests to make sure no one is going to screw that part of the code with type mismatch (who said shortness ?).

Conclusion

So, to conclude, even if this post looks like a monologue against Python, it’s not. I understand Python advantages over traditional typed language and, as the first script shows, I even use it to test my ideas. What I wanted to highlight is that I consider Python *not* suited to large applications where several people have to collaborate (especially if there are no strong policy or rigor inside the team). Python as a powerful Bash replacement, yes. Python as a nice framework for testing and prototyping ideas, good, why not. Python as en embeddable scripting language, sure, it’s made for that in a sense. But Python for a large and maintainable application ? No, not for me.

NB: this post is what some might call a (badly hidden) troll. Instead of that, I would like to present this post as an invitation to discuss in comments, so feel free to drop your thoughts.

Could C++ have at least a good point ?

4

Category : C#

(I’m taking risks with such a title :P )

During yesterday computer science practical session (just think of the most hellish thing you have ever done), I was wandering lazily in the program list of the computer where I was supposed to do Excel stuff (actually I had pretty most finished and I wasn’t really in the mood to do extra work), when I found an antique DevC++ installation in one of the menu. Launching the thing I started to do a calculator (yes, after VBA almost anything else to program sounds interesting) when I remembered the use of the const keyword applied to functions and methods which (C++ purists correct me if I’m wrong) compiler-check that the code inside the function/method doesn’t modify both the parameters or the internal class state.

After thinking about it I thought : « Hey actually that’s a nice idea » and indeed it somehow lessens what the functional enthusiasts may call one of the ‘imperative nightmare’, namely, the imperative’s side-effects :

« Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast with the imperative programming style that emphasizes changes in state.« .
Wikipédia, Functional programming

This feature is particularly important in the today context where search for performance leads to parallel programming, a field where functional language excels by using this feature that imply that every function calls are independent from the execution context of the program.

IMHO this could proves to be a good feature in C# : a compiler-enforced mean to behave in a (mimicked) functional way with readonly access to fields and parameters and, thus, both no pollution of the others class’ methods call and the absence of locks which would allow, for example, auto-parallelism by the runtime. Especially when C# tends to get more and more functional concepts integrated both in the core language and in the class library.