Friday, December 11, 2009

WCF errors translation



If you get a message from server:

The exception message is 'The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.'. See server logs for more details


this may mean that your ajax client did not set up ContentType such as "application/json; charset=utf-8"

Thursday, October 22, 2009

Menus in Gtk# (and Monodevelop)



Unfortunately there is surprisingly little information about Gtk# and gtk itself in Internet. So when I started my first UI project in Monodevelop, I had to spend a lot of time looking for information and experimenting.

My environment: gtk# version: 2.12, Monodevelop: 2.0, OS: Ubuntu-9.04

When you create new Gtk project, everything is very intuitive.
First little surprise is that in Gtk you can not create any element on your window but instead you have to put there a placeholder, usually a Vbox, and only than you can use familiar controls like menu.

Menu editing is intuitive and cause no problems. But I wanted to generate one of the menus programmaticaly: list of last files open. Here is a surprise.
Monodevelop has its own UI builder and most of the controls have appropriate object instances auto-generated. For example:

// Container child MainWindow.Gtk.Container+ContainerChild
this.vbox1 = new Gtk.VBox();
this.vbox1.Name = "vbox1";
this.vbox1.Spacing = 6;


But menu is an exception. Menu items do not have appropriate variables generated. There are two ways you can get your menu item: you can digg through "Children" properties until you find the menu item you want. Not too elegant, if you are looking several levels down.
The other way is to use UIManager:

var menu = (Menu)((ImageMenuItem)this.UIManager.GetWidget("/menubar2/FileAction/LastProjectsAction")).Submenu;

But how do I know what the path to the menu is? You need to open your auto-generated window class and find there a line like this:

this.UIManager.AddUiFromString("<ui><menubar name='menubar2'><menu name='FileAction' action='FileAction'><menuitem name='SaveAction' action='SaveAction'/><menu name='LastProjectsAction' action='LastProjectsAction'/><menuitem name='ManageProjectsAction' action='ManageProjectsAction'/><separator/><menuitem name='ExitAction' action='ExitAction'/></menu></menubar></ui>");

If you traverse nodes, following their "name" attribute, that would be the path you are looking for.

Using "Menu.Append()" you can add new MenuItem to the menu. You run your program, and... there is no result. There is no exception, but no new menu item either. Why is it missing? Gtk again: by default any widget's visibility property is off. Don't ask me why. Just call Gtk.Widget.Show() on newly added menu item. As alternative, you can add menu items and than call "Widget.ShowAll()" on the parent menu.

When those problems were sorted out I got functioning basic UI application which loads last used files as a menu.

Wednesday, July 29, 2009

Pattern: resource management using callbacks



In C# in order to manage resources, IDisposable interface is used. But what if resource creating is complicated and requires a dedicated function? Lets say we have a system with multiple databases and complicated logic deciding which database should be used. We want to encapsulate this knowledge into a function:

class ConnectionWrapper {
IDbConnection NewConnection() {
string connectionString
... // whatever application specific logic
... // constructing connection string
return new SqlConnection(connectionString);
}
}


There is something bothering me in this code. We return new Connection object without guarantee that it will be disposed. We assume that the caller will utilize "using" statement. So we create resource but we do not have control over it correct usage.

Now, do you remember that when creating Data Reader by calling IDbCommand.ExecuteReader, we can provide a parameter "CommandBehavior" and one of the options is "CommandBehavior.CloseConnection". Why is that? It is exactly for the reason I've just described: sometimes we create connection in one place but we create a reader in another place. So we can not coordinate their life time. We can not wrap Connection into "using" because most likely we will close connection before data reader will have chance to finish reading. That's where "CommandBehavior.CloseConnection" helps. We create connection without worrying (or shall I say "with a hope") and we always create reader with "CommandBehavior.CloseConnection" and wrap reader into "using".

Needless to say, it is fragile. May be not really terrible, but you have to be careful and remember about all those little agreements you have in your application. Of course, you never forget things but when you write a framework to be used by others 10 programmers, it is just matter of time, when somebody will start leaking half-committed transactions... you will have a lot of fun trying to figure it out.

So, what new and shiny C#-2.0 (or even better 3.0) gives us? Callbacks. Or should I say simple way to write callbacks.
Lets see, what we want is a guarantee that resource allocated is not leaked. So we need to use "using" statement.

class ConnectionWrapper {
IDbConnection NewConnection() {
string connectionString
... // whatever application specific logic
... // constructing connection string
using(var connection = new SqlConnection(connectionString))
return connection;
}
}
}


This is what we want. But it will not work, because connection will be disposed before returning it to the caller and caller will get disposed connection. So here is the trick:


class ConnectionWrapper {
void NewConnection(Action<IDbConnection> callback) {
string connectionString
... // whatever application specific logic
... // constructing connection string
using(var connection = new SqlConnection(connectionString))
callback(connection);
}
}
}


We do not return connection object now. Instead caller must provide a callback code.
And notice important detail: connection object is wrapped into "using" statement, so we achieved our goal: we have guarantee that it will not leak.
Here is how caller will look like:

ConnectionWrapper.NewConnection(connection=>{
IDbCommand cmd = connection.CreateCommand();
cmd.CommandText = "select ...";
using(IDataReader reader = cmd.ExecuteReader()) {
while(reader.Read())
...
}
});


Notice, that caller does not have to use "using" on connection object. We simplified caller and improved reliability the same time.
But now we look suspiciously at the remaining "using" statement: if we managed to get rid of one, can we do the same thing to the another? What if callback will return reader instead of connection string?


class ConnectionWrapper {
void NewConnection(string sql, Action<IDataReader> callback) {
string connectionString
... // whatever application specific logic
... // constructing connection string
using(var connection = new SqlConnection(connectionString))
IDbCommand cmd = connection.CreateCommand();
cmd.CommandText = sql;
using(IDataReader reader = cmd.ExecuteReader()) {
while(reader.Read())
callback(reader);
}
}
}
}

// Caller:
var names = new List<string>();
ConnectionWrapper.NewConnection("select ...", reader=>{
names.Add((string)reader["Name"]);
});


Wow! Caller is now just two lines of code. And at the same time we keep Connection and Reader object inside "using".

But what if I want some parameters into my Command? Or you want to set command timeout? By now you should get used that the answer is going to be... right, callback :)


class ConnectionWrapper {
void NewConnection(Action<IDbCommand> cmdCallback, Action<IDataReader> callback) {
string connectionString
... // whatever application specific logic
... // constructing connection string
using(var connection = new SqlConnection(connectionString))
IDbCommand cmd = connection.CreateCommand();
cmdCallback(cmd);
using(IDataReader reader = cmd.ExecuteReader()) {
while(reader.Read())
callback(reader);
}
}
}
}

// Caller:
var names = new List<string>();
ConnectionWrapper.NewConnection(
cmd => {cmd.CommandText = "select ..."; cmd.Parameters.Add(...)},
reader=>{names.Add((string)reader["Name"]);
});


Now the framework call two callbacks: one to give the caller opportunity to set up Command properties, and another callback for Reader which will be called for each row in Reader.

Conclusion.
This article demonstrates how to use callback to keep resources life time under control without burdening callers.

Tuesday, June 09, 2009

Console in Windows application



Sometimes it is convenient to have a text console in windows non-console application. For example it is much more convenient to debug windows service in console than as a real service.
If you try to do Console.WriteLine() from our service, it will produce nothing, because there is no console window at all. You can go to project settings and change project type from windows application to console application, but it is inconvenient, because your will have to remember to undo it.

Initialize console in windows application is easy calling API function:

[System.Runtime.InteropServices.DllImport("kernel32")]
static extern bool AllocConsole();


Now you can add some parameter parsing and programmatically switch into console mode without tweaking your project.

Another nice trick is to switch into console mode instead of windows service mode whenever you run your project under Visual Studio debugger.

static class Program
{
static void Main()
{
if (AppDomain.CurrentDomain.DomainManager.GetType().Name !=
"VSHostAppDomainManager")
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new Service1() };
ServiceBase.Run(ServicesToRun);
}
else
{
AllocConsole();
var srv = new Service1();
srv.Start();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
srv.Stop();
}
}

[System.Runtime.InteropServices.DllImport("kernel32")]
static extern bool AllocConsole();
}

Thursday, February 05, 2009

C# paradigm shift



Everybody knows that c# had introduced lambdas in version 3.0, but it takes some time to change the way you program before.


It helps a lot if you are familiar with some modern dynamic languages like Ruby.
I realized that things changes when I found this library, NDesk.Options. I recognized right away familiar pattern of heavy callback usage which is expected in Ruby code. But not in C#. At least not until now. C# team admits that they are looking at dynamic languages and trying to provides dynamic benefits without losing static type check safety. And I must admit that they are doing remarkable job in balancing past and future. Unlike Java which seems stuck in the past. Java didn't manage to implement even descent generics functionality.


Here is an example of handling command line options in callback style:


new NDesk.Options.OptionSet().
Add("file=", o => {_walker.AddFile(o);}).
Add("dump:", o=> { Dump(o); }).
Parse(args);


You add processing option as a pair of option string and a callback action. When option parser will parse parameters, it will call your code back.

Traditional way would be perhaps inheriting from some BaseParserOption calss, overriding some method like "OnOptionMatch", writing a constructor with option to be matched, etc. Creating a class is too much hassle if you want just call a function or modify property for later usage. Often callback style helps reducing code size and make it more readable.


Don't overuse it though, always compare, which code will be more elegant, with callback or inheritance/interface.