My name is Juri Strumpflohner and this is my technical blog. I'm a software architect, .Net, Android, Web and Java dev, TDD and best practices promoter and martial arts practitioner.

Recent Posts Subscribe

Dear reader of Juri's TechBlog,
I moved my blog to a new domain and a new hosting solution as well. I'm now blogging on juristr.com.

Instantiating object from generic type: Java vs. .Net

Consider the following .Net code:

public static class Processor
{
        public static TItem CreateInstance<TItem>() where TItem:new()
        {
            TItem result = new TItem();
            return result;
        }
}
This is a pretty straightforward class, although not so meaningless if left in this way. You may use this piece of code as follows:
class Program
{
    static void Main(string[] args)
    {
        Test t = Processor.CreateInstance<Test>();
        Console.Write(t.SomeInt);
    }
}

class Test
{
    public int SomeInt { get; set; }

    public Test()
    {
        SomeInt = 3;
    }

}
Nothing strange so far. What I want to show however is how simple it is to create an instance of a generic type in C#.

Now let's switch over to the Java world where I'd like to realize a similar thing. So first, create a class Processor again with a static method createInstance.
public class Processor {
 public static <T> T createInstance(){
  T t = new T();
  return t;
 }
}
Probably that's what you would write or better, would like to write since this will give you a nice compiler error. You cannot do "new T()" where T is a generic type parameter. So now the challenge starts. How can I create an instance. It turns out that you need the class for doing so s.t. it looks like
public class Processor {
 public static <T> T createInstance(Class clazz) throws InstantiationException, IllegalAccessException{
  T t = (T) clazz.newInstance();
  return t;
 }
}
And then you invoke it like
public class MainClass {

 public static void main(String[] args) throws InstantiationException, IllegalAccessException {
  Test t = Processor.createInstance(Test.class);
  System.out.println(t.getSomeInt());
 }
}
Note in Java you don't have to pass the generic type. The compiler will understand it outmatically. That's nice. However when looking at the overall solution, the C# example seems much more elegant. If you look at the "createInstance" method in the Java example you may also note that providing the class is somehow a duplicate information. If you're a clean-code fanatic like myself the immediate thought would be to somehow get this information form the generic parameter type directly. Through reflection? It turns out that to be a major challenge. Java has a mechanism called type erasure, which eliminates generics information at runtime in order to stay backward compatible. Read this article for more information.
Another guy which seemed to have the same problem proposed a possible workaround for this: happy reading ;)

Usually then, passing the class information in some acceptable way is the simpler and probably type-safer solution.

Accessing the host machine from your Android emulator

I recently started a project where I develop an Android app (there will some posts later on ;) ) which accesses a remote server as its back-end, hosted on the Google Appengine.
When you develop, you normally start your Appengine server locally from within Eclipse (this has been very nicely configured by the Google Eclipse plugin wizard) s.t. it runs on localhost:8080. However when you try to access "http://localhost:8080" from your Android app, you will get a nice "Connection refused" exception. This is because localhost is the phone itself, basically the emulator.

After posting on SO, some gave me the hint of starting the appengine with you public IP address. This can be done in the Eclipse Run/Debug configuration under the "(x)=" arguments tab by passing the "--address="



Fair enough, but this requires you to change the IP address in the run configuration every time you switch network + in the code (preferably in some properties file) where you access your webserver of course. Moreover when you develop in a team this is quite cumbersome.

There is however a far better solution. Thanks to a hint from a SO post, you can access your host machine with the IP address "10.0.2.2". This has been designed in this way by the Android team. So your webserver can perfectly run at localhost and from your Android app you can access it via "http://10.0.2.2:8080".

Repeater looses its data collection. ViewState problem?

A while back I experienced a really strange problem in one of our ASP.net applications, namely my repeater control which was loosing its data collection after a postback to the server. I got some minutes of time and thought to quickly post about the problem for you guys out there. I created a small demo app which reproduces the problem very clearly.

Consider the following ASPX page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RepeaterViewstateProblem._Default" %>
<%@ Register src="Controls/RecursiveIterateControl.ascx" tagname="RecursiveIterateControl" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>List of Persons</h2>
        <asp:Repeater ID="repeaterPersons" runat="server">
            <HeaderTemplate>
                <ul>
            </HeaderTemplate>
            <ItemTemplate>
                <li><%# Eval("Firstname") %> <%# Eval("Surname") %></li>
            </ItemTemplate>
            <FooterTemplate>
                </ul>
            </FooterTemplate>
        </asp:Repeater>
        
        <asp:Button ID="buttonSubmit" runat="server" Text="Provocate a postback!" 
            onclick="buttonSubmit_Click" />
    </div>
    </form>
</body>
</html>
It's quite simple. There is a Repeater control and a button for creating a postback to the server. In the codebehind I write the following
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace RepeaterViewstateProblem
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                repeaterPersons.DataSource = CreateDummyPersonList();
                repeaterPersons.DataBind();
            }
        }

        private IList<Person> CreateDummyPersonList()
        {
            return new List<Person>{
                new Person { Firstname = "Juri", Surname="Strumpflohner"},
                new Person { Firstname = "Jack", Surname="XYZ"}
            };
        }

        protected void buttonSubmit_Click(object sender, EventArgs e)
        {

        }
    }

    class Person
    {
        public string Firstname { get; set; }
        public string Surname { get; set; }
    }
}
I have a dummy class Person which is used for data binding. For that purpose I create a simple collection of Person objects which are being bound to the Repeater control. I'm doing this just once, when a GET request is done to the page. During POSTs the ASP.net ViewState mechansim will keep the bound data collection for me. Running the example, you should get the following output:



When clicking on the button, a postback to the server will be done and the ViewState will still maintain the elements of your Repeater control. So everything fine till now.

A functionality which is often needed in web apps is to dynamically search for control instances at runtime when you just have the corresponding IDs. This can be achieved through the Control.FindControl(...) method, but often I found that you have the need for a recursive version which traverses the Control hierarchy starting from a certain root. I've implemented such a recursive method. There's nothing bad with this except that you have to pay attention which root you provide such that you don't traverse the whole hierarchy which, on large sites, may cause some performance problems. So let's implement such a recursive find in a UserControl which is then placed on the main page I've shown above.
RecursiveIterateControl.ascx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

namespace RepeaterViewstateProblem.Controls
{
    public partial class RecursiveIterateControl : System.Web.UI.UserControl
    {
        public string ControlIDToSearch { get; set; }

        protected override void OnInit(EventArgs e)
        {
            Control ctrl = FindControlRecursive(this.Page, ControlIDToSearch);
        }

        /// <summary>
        /// Recursive version of the FindControl method.
        /// </summary>
        /// <param name="parent">Parent to where to start the search for the control</param>
        /// <param name="controlId">ID of the control to search for</param>
        /// <returns></returns>
        private Control FindControlRecursive(Control parent, string controlId)
        {
            if (controlId == parent.ID)
                return parent;

            foreach (Control ctrl in parent.Controls)
            {
                Control tmp = FindControlRecursive(ctrl, controlId);
                if (tmp != null)
                    return tmp;
            }

            return null;
        }
    }
}
On the main page I include the UserControl and pass it the ID of - say - the button "buttonSubmit":
<uc1:RecursiveIterateControl ID="RecursiveIterateControl1" ControlIDToSearch="buttonSubmit" 
                runat="server" />

Now re-run the application and hit the button to launch the postback. You'll notice that your repeater is empty, getting the following screen:

So why did this happen? The only thing we have added is the method for recursively iterating through the control hierarchy which doesn't contain any objectionable code. I'll tell what the problem is.

There are a few things here you have to consider. First of all about the ASP.net page lifecycle and how the ViewState is being handled. The following diagram shows it:

Note, the ViewState is deserialized and loaded back on the controls after the OnInit and before the PageLoad event. Actually the FindControlRecursive() is called during the OnInit event but we are doing nothing with the ViewState, so that should be fine.

The next thing I looked at was at the Repeater code directly using the Reflector. The only thing that's being accessed on the Repeater is its Control property when it is being traversed during the execution of the FindControlRecursive. The Repeater control actually overrides that property and defines it as follows:
public override ControlCollection Controls
    {
        get
        {
            this.EnsureChildControls();
            return base.Controls;
        }
    }

The "EnsureChildControls()" will trigger a call to the CreateChildControls() which is usually overridden by composite server controls. If you continue to search that on the Repeater control you get this code...
protected internal override void CreateChildControls()
    {
        this.Controls.Clear();
        if (this.ViewState["_!ItemCount"] != null)
        {
            this.CreateControlHierarchy(false);
        }
        else
        {
            this.itemsArray = new ArrayList();
        }
        base.ClearChildViewState();
    }
...and here is the problem. According to the ASP.net page lifecycle we know that the ViewState will be loaded after the OnInit event of the page. However our call of the FindControlRecursive(..) method inside the OnInit will trigger down till the CreateChildControls() method of the Repeater control is being called. And since the ViewState is not yet loaded back, the condition (this.ViewState["_!ItemCount"] != null) will evaluate to false with the effect that a new empty collection is being created and the ViewState of the childs is being cleared. In fact, every call to the "Control" property of the Repeater during a state in the page lifecycle where the ViewState has not yet been loaded back, will result in loosing all of its values.

Now imagine you notice this problem in a big web app, probably days or even weeks after you or even someone else in the team has added that FindControlRecursive(..) call somewhere in the codebase. It actually took me two days to figure out this problem!

As a solution you may pay attention to just call the FindControlRecursive(..) method during the PageLoad event or later. Alternatively you could implement a SafeFindControlRecursive(..) which takes care of this problem. This could look like the following:
private Control SafeFindControlRecursive(Control parent, string controlId)
{
    if (controlId == parent.ID)
        return parent;

    foreach (Control ctrl in GetControlCollection(parent))
    {
        Control tmp = SafeFindControlRecursive(ctrl, controlId);
        if (tmp != null)
            return tmp;
    }

    return null;
}

private ICollection GetControlCollection(Control parent)
{
    if (parent is Repeater)
    {
        return new Control[0];
    }
    else
    {
        return parent.Controls;
    }
}
This takes care of not accessing the Control collection of a Repeater control which is normally also not needed to be traversed.

You can download the Visual Studio project showing this problem here.

Visual Studio 2010 Beta2: Cannot start application

After installing the new Visual Studio 2010 Ultimate beta2 release today, I just started to play a bit, trying out the new features. One was to move the Solution Explorer panel out of the main Visual Studio frame onto my second monitor and then again back into the main window. I shouldn't have done that. VS crashed and restarting it gave me the nice error message "The application cannot start".


Nice surprise! As a workaround to fix this problem navigate (inside the command prompt window) to the installation directory of Visual Studio "..\Microsoft Visual Studio 10.0\Common7\IDE" and type
devenv /resetuserdata
The consequence: you loose all of your preferences.

Part 1: Writing testable code for the Android

Creating testable code is one of the major aims when designing good, maintainable applications. I actually just started to take a look at developing for the Android and after playing a bit around with UI components, I started to develop a design that allows me to create a nicely testable Android app.



One of the major flaws in an untestable design is a very tight coupling between the view components and the actual model. This is often one of the issues why applications are hardly or even not testable at all. Btw, when I'm talking about testability, I consider writing automated unit tests of course. So my first approach was to see how to decouple this logic. MVC is a good tool for doing so.

When programming for the Android OS, you have roughly these three concepts:
  • Activities
  • Layouts
  • Adapters
If you're familiar with J2ME programming, an Activity would probably mostly correspond to what is called a MIDlet there. It is a modular component which has a certain lifecycle and is most commonly but not necessarily associated to a single view (in the UI sense). Simply speaking they could be seen as UI views.
The UI part on Android is organized very nicely. All of the UI components can be written in a declarative way inside special XML files where the so-called "layouts" are being defined. From a conceptual point of view it has some similarities with XAML files used in WPF and Silverlight. This piece of XML code shows for instance an UI with vertically aligned buttons:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">

 <Button android:text="0" android:layout_width="fill_parent"
  android:layout_height="wrap_content" android:id="@+id/button1"></Button>

 <Button android:text="0" android:id="@+id/button2"
  android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
 <Button android:text="0" android:id="@+id/button3"
  android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>

</LinearLayout>



Such a declarative UI concept is very helpful when separating logic from the view.
The last thing are the adapters. They are basically the bridge between the model data and the UI layouts with its components. It's basically a data-binding mechanism which does already most of the job of synchronizing model data with what's being visualized on the UI. There are a couple of different adapters which are quite flexible and can be further customized by overriding them.

(Part 2: Writing testable code for the Android »)
(link will be activated as soon as that post goes online)

Google Wave...a first comment

I've now played a bit around with Google Wave for nearly two weeks now and it's quite cool. The real-time collaborative editing is just amazing, as you can also see in the dozen of demonstration videos which are around the web already. There are a lot of cool features to discover and additional ones come up continuously. I guess however, Wave will even become more useful once more of my friends get access to it so that you can really collaborate and try it out in deep.

Wave is still in its very early stages and sometimes you also notice that it's still in a preview phase. Often it reacts very slowly, Waves don't load or some functions like moving waves to the trash have a very high delay. Of course there are also a lot of useful functionalities still missing but I mean, that's a price I can pay for being able to participate in the preview :)

Today I opened a new wave for managing a project we're going to start for a university course. I thought it might be a good occasion to try out Wave and to keep useful information about the project in a central place s.t. it can be easily accessed by the team members. Normally I use Google Docs for this kind of purposes which btw is really great for sharing and collaborative editing. You wouldn't imagine how much faster you are when you share a GDocs document with your team mate for contemporaneously constructing documents or reports and then when you're finished you export them as PDF and submit them :) . Works really great. Parallel editing in GDocs is not fully real-time but has some delay of about 5 seconds.
But for the purpose of trying out Wave I thought to use that this time. So I just opened a new one, wrote some sections for the different kind of purposes and then intuitively took dragged our PDF file containing the initial project proposal from the OSX dock stack into the wave. And voilá, the document gets uploaded.




Really intuitive :). I expect a lot of new interesting features coming up..

Blog to learn...

John Skeet answered a question on SO related to how to learn good programming in terms of learning good software design.
I liked John's statement which btw explains pretty much why to have a technical blog like this one here.

[...]Write. Blog about what you've done and how well it's worked. This goes beyond looking carefully - just working out how to express your successes and failures will make them clearer in your own mind. Be warned: writing can be addictive and time-consuming.[...]
Actually this is a pretty good known concept: learn by reflecting about it (remember retrospectives in agile development ;) ). And that's what you do when you explain things to others (like when you blog about a topic). For doing so you really have to have a deep understanding, unless you're just pointing out things of course.

Annotation tools for the Mac

When you create scientific reports or you just prepare for exams you usually have to go over a whole bunch of papers, lecture notes and websites. The old way is to print them out and use some highlighter to mark the most important parts. But often I prefer to just highlight the pdf files directly on my notebook while reading or flying over them. You also save the environment by not printing everything which you probably will throw away anyway later on.

On Windows and Linux I used to do it with the build-in mechanism supported by MS PowerPoint but just for PP slides of course. For the rest I used Jarnal, a cross-platform Java-based app. However Jarnal did never really convince me. It is more suitable for tablets rather than for normal notebooks. But now I found Skim.

Skim is a PDF reader and note-taker for OS X. It is designed to help you read and annotate scientific papers in PDF, but is also great for viewing any PDF file.
 ..and it's Open Source wherefore it's always worth mentioning. A list of features can be found here. Beside an excellent UI experience and the capability of support of interaction with LaTeX, SynTeX etc it is really cool that you're PDF's itself won't get polluted by your annotations. This means you just open your pdf file with Skim, put your annotations and highlightings and save it as usual. If you then open the pdf just normally with Previewer you won't see anything of your previous edits. Of course there is also the option of exporting your edits.



Btw, for direct highlighting of webpages you might consider Scrapbook which is a nice add-on for Firefox.