Archive for 'coding'

python interop: using jython and ironruby

in a project with java and .net komponents we needed to share some validation-code. this code should be executable on both platforms and act against pocos (plain old clr objects) and pojos (plain old java objects). we tested python as a language that can be executed on both sides using jython for java and ironpython for c#. i want to show you how simple an integration of python is here.

for c# and ironpython:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;
using IronPython.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
 
namespace IronPythonValidationTest {
  internal class Program {
    private static void Main(string[] args) {
      string code = @"
if this.Von > this.Bis:
    result = 'von soll kleiner sein als bis'
elif this.Child.Name != '':
    result = 'name soll gefüllt sein'";
 
      ScriptEngine engine = Python.CreateEngine();
      ScriptScope scope = engine.CreateScope();
      scope.SetVariable("this", new TestType {Von = DateTime.Now.AddDays(1), Bis = DateTime.Now, Child = new TestTypeNested()});
      ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.SingleStatement);
      source.Execute(scope);
      string validationResult = scope.GetVariable("result");
      Console.WriteLine(validationResult);
      Console.ReadKey();
    }
  }
 
  public class TestType {
    public string Name { get; set; }
    public DateTime Von { get; set; }
    public DateTime Bis { get; set; }
    public TestTypeNested Child { get; set; }
  }
 
  public class TestTypeNested {
    public string NochName { get; set; }
  }
}

and almost the same for java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import org.python.util.PythonInterpreter;
import org.python.core.*;
 
public class JythonValidationTest {
 
	public static void main(String[] args) {
		PythonInterpreter python = new PythonInterpreter();
		String code = "if this.Von > this.Bis:\n    result = \"von soll kleiner sein als bis\"\nelif this.Child.Name != \"\":\n    result = \"name soll gefüllt sein\"";
		PyCode pc = python.compile(code);
		TestType l = new TestType();
		l.setVon(2);
        l.setBis(1);
		python.set("this", l);
	}	
}
 
// this has to be a public class, so one could not put it in one classfile
public class TestType {
    public int von;
    public String name;
    public int bis;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getVon() {
        return von;
    }
 
    public void setVon(int von) {
        this.von = von;
    }
 
    public int getBis() {
        return bis;
    }
 
    public void setBis(int bis) {
        this.bis = bis;
    }
}

remaining problems:

  • because of naming-convention ifferences you have to wrap python code so that you can intersept calls to get*() methods. as in c# getters and setters look like Name instead of getName()
  • if there are user visible strings involved, you have to think about translating them
  • checking the python code before deployment

java-bits #1: filedragdrop handler

drop a file from the explorer to a textbox and make the path the text of that textbox:

// imports omitted, dont know why...
public class Foo extends TransferHandler {
 
//...
 
/*
DRAG & DROP
*/
@Override
public boolean importData(JComponent comp, Transferable t) {
// Make sure we have the right starting points
if (!(comp instanceof JTextField)) {
return false;
}
if (!t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}
 
// Grab the tree, its model and the root node
JTextField textField = (JTextField) comp;
try {
List data = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
for (Object object : data) {
File f = (File) object;
textField.setText(f.getAbsolutePath());
}
return true;
} catch (UnsupportedFlavorException ufe) {
System.err.println("Ack! we should not be here.\nBad Flavor.");
} catch (IOException ioe) {
System.out.println("Something failed during import:\n" + ioe);
}
return false;
}
 
@Override
public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
if (comp instanceof JTextField) {
for (DataFlavor transferFlavor : transferFlavors) {
if (transferFlavor.equals(DataFlavor.javaFileListFlavor)) {
return true;
}
}
return false;
}
return false;
}
}

walk in the park: installing mod_rails aka phusion passenger

man that was easy. after my problems with getting ruby, gem and rails to run installing mod_rails aka phusion passenger was really easy:

  • gem install passenger
  • passenger-install-apache2-module

i followed the steps that the installer told me and go. just needed to apt-get some apache dev packages and was ready to run.

cant tell you how happy i am.

now the rails fun can start.

getting ruby on rails to run on my debian 4 vps

man…always fighting to get a recent version of anything to run on the debian 4 (etch) vps i have. this time: ruby on rails. ruby v1.9.1, gems 1.3.5 and ror 2.3.4 is what i had i mind.

first step: download ruby. execute the usual ./configure && make && make install triplet. worked fine. then download ruby gems. but when i tried to run anything with gem i got:


/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- zlib (LoadError)
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/spec_fetcher.rb:1
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/commands/update_command.rb:5
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/command_manager.rb:167:in `load_and_instantiate'
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/command_manager.rb:88:in `[]'
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/command_manager.rb:144:in `find_command'
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/command_manager.rb:131:in `process_args'
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/command_manager.rb:102:in `run'
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/gem_runner.rb:58:in `run'
from /usr/local/bin/gem:21

after googleing and trying some stuff i solved it this way:

  • edit ruby-1.9.1-p0/ext/Setup
  • uncomment the line zlib
  • make && make install again

next step. successfully let gem install rails. but then ruby script/server stopped with:


=> Booting WEBrick
=> Rails 2.3.4 application starting on http://0.0.0.0:3000
/usr/local/lib/ruby/gems/1.9.1/gems/rails-2.3.4/lib/initializer.rb:271:in `rescue in require_frameworks': no such file to load -- openssl (RuntimeError)
from /usr/local/lib/ruby/gems/1.9.1/gems/rails-2.3.4/lib/initializer.rb:268:in `require_frameworks'
from /usr/local/lib/ruby/gems/1.9.1/gems/rails-2.3.4/lib/initializer.rb:134:in `process'
from /usr/local/lib/ruby/gems/1.9.1/gems/rails-2.3.4/lib/initializer.rb:113:in `run'
from /var/www/rails/ukk/config/environment.rb:9:in `'
from /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-2.3.4/lib/active_support/dependencies.rb:156:in `require'
from /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-2.3.4/lib/active_support/dependencies.rb:156:in `block in require'
from /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-2.3.4/lib/active_support/dependencies.rb:521:in `new_constants_in'
from /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-2.3.4/lib/active_support/dependencies.rb:156:in `require'
from /usr/local/lib/ruby/gems/1.9.1/gems/rails-2.3.4/lib/commands/server.rb:84:in `'
from script/server:3:in `require'
from script/server:3:in `

'

after a another round i found this site with help:

  • apt-get install openssl libssl-dev
  • apt-get install ruby1.9-dev
  • cd ruby-1.9.1-p129/ext/openssl
  • ruby extconf.rb
  • make && make install

that worked. nice. so now i am waiting for the next fail

itemtemplate selection by type in xaml only

some days ago i found my self in need to change the itemtemplate in a listbox according to their type. and if with less code as possible. i had done this in a treeview but i couldnt find the code again. so i needed to figure it out again and with some help from a collegue we ended with this:

[source language='xml']














[/source]

remark: you arent allowed to give a key to that resources. i suppose the type is kind of key here.

prio conf 28.-29.10. in munich

i am existed about a conference i am attending end of oktober in munich, germany: prio conference. its totally ui centric and that why its so hot. never saw such an interesting conference all about ui in germany before.

what is wrong with focus in wpf

lately we wanted to set the initial focus on a window in wpf to improve the keyboard experience in our app. what we want to achieve is just the initial focus. so when one opens the window he can type or push the most meaningful button instantly. unfortunately we encountered several problems. at first lets see what wpf offers to set the focus. there are at least 4 possibilities:

  • FocusManager
  • Keyboard.Focus
  • InputElement.Focus
  • InputElement.MoveFocus

what i understand from msdn is that the best way to set the initial focus is the focusmanager. but we encountered two problems where that wont work:

  • set initial focus to a button with a commandbinding
  • set initial focus to an element defined through a contenttemplate

i did not understand why that is. but i found two strange things: when setting a breakpoint in the ContentRendered-Event you can see the button is visible, but it is disabled. so i understand that i doesnt make sense to set the focus to a disabled element. this seems like a bug to me. another thing i could not understand is when the content of the control is set through a ContentTemplate the Method FrameworkElement.FindName(string elementName) wouldnt find the element. isnt that a bug too? when you inspect the window on screen with scoop u can see all the elements of course.
i tried to use the other focus-methods in various events but none worked. funny thing: if you set the focus and have a breakpoint in the Loaded-Event and just go on after stopping there the focus is correct. Racecondition?

so is there someone who had similar problems? am i wrong with my feeling that these are bugs?

i added an example solution where you can see the sourcecode.

skillsmatter, london: day 3

man, again a hour too early. but needed to pack my stuff so i arrived at the old sessions house on time. first session with david laribee: “towards a new architect”.

man is dave a good speaker. nice minimalistic slides. and we got teamwork. i think a great exercise was the condensation of team values. we startet in small groups (5 people) – diversion phase. where we found around 25 values. all the stuff that came to our minds. then we voted on the values and found 5 top values (conversion phase, we could have summed al the teams values up but to see how it works it was enough) for which we had to find sentences to declare why we honour that value. dave suggested to print those team values so the team have them in mind always. great idea.

after the usual lunchbox i decided to attend the second workshop from dave. unfortunately it started a bit messy. not everybody understood what to do because the exercises where really abstract. and because i had to depart about an hour too early i couldnt see the end result.

as i mentioned my flight was early so i had to leave skillsmatter at 17 o’clock. too bad because they instantiated a discussion with all the speakers at 18 o’clock and a beer at the crown pub nearby after that. i should have planned my home ride on thursday. hmmm…next time.

baseline:
i think the progressive .net workshops from skillsmatter where great. i had very good conversations (mostly limited by my speaking skills). the speakers where always near. not that they leaved after their talk but one could always get to them and ask questions. the atmosphere was very familiar. i liked the location and the organisation was very good. two things i didnt like: the internet-connection was very bad. that was really really annoying. many attendees had 3g-connections but i think if i had used mine (german provider!!) i think by boss had killed me. the second thing: the lunch boxes where a little small for my taste. but i can recommend the workshops without a doubt.

skillsmatter, london: day 2

i am still not adapted to the hour time difference between germany and the uk. so i awoke a hour to early.

arrived early at the old session house where the workshops take place and decided to hear the f#-workshop with robert pickering. the workshop was full of f# content. robert is real expert. the speed we rushed through the slides was amazing. but at the and we arrived at some beautiful examples of the power of f# which robert ported from python out of the book “collective intelligence” by toby segaran – great read by the way. he drawed some nice dendrogramms e.g. of a blogclustering algorithm.

after the light lunchbag (nearly the same like yesterday) james, david and i got a small beer before we joined the advanced nhibernate workshop with ayende.

wow the room was full. big speaker, big room, big audience – great. so ayende told he has no slides and nothing prepared at all. he questioned the audience to supply topics he would then talk about. he collected about 25 topics…for a 4h workshop…not bad. and it was fun. for example the suggested topic “stored procedures” he wrote down as “stored procedures, and how they bite you in the ass”. ayende is really cool. the rest of the talk was also very passionate.

after that gojko guided the group to the alt.net beers. snacks and drinks where sponsored by thoughtworks and skillsmatter (thanks for that). i learned serialseb is the dictator of the alt.net beers. he managed the geeky crowd to really get to two talks around document databases and bdd. some of the speakers had an alcohol clouded mind to say the least. but it was real fun. it was an amazing day 2.

skillsmatter, london: day 1

so the first day is finished. when i arrived at skillsmatter i met michel. like expected. first talk with ian cooper about internal dsls in c#. cool intro to the matter. now i need to have a look at some stuff:

after that we got a lunchbag and sat in the sun for an hour. then sebastien lambla joined. i didnt know much about him but he seemed funny and interesting so i decided to see his talk instead of the fitnesse one. and it was great. he stated that he had only 3h of sleep because he had to get openrasta to work for the workshop. but he got it and the workshop went great.
when the workshop ended we all went to have a beer. there where some discussions with lambla aka serialseb, oren aka ayende and some other nice guys.
we ended the evening with pizza at pizza express with 14 funny people where we had also some great discussions about latin as a language in school and introducing agile techniques to teams in very big and long lasting projects. very interesting.

know i am done, have a good night