What is wisdom?

Beautiful old people wisdom collected in one superb book.

My favorite one:

…you don’t stop doing things because you’re old, you’re old because you stop doing things…

Graphite for WPF

In a previous post I described Graphite for Silverlight which allows you to display diagrams inside a browser with automatic layout (the spring-embedder algorithm). In a swift move I converted the library to a WPF control, which at the same time allowed me to add some features which were less trivial in Silverlight because of the constraint Silverlight imposes in comparison to WPF.

To demonstrate Graphite for WPF I created some kind of ’star sky’ of science. Ideas, persons and standard nodes are all styled in the host application and you can experiment with the Graphite API and the visual representation (look into the App.Xaml file). When hovering over a node a custom tooltip appears which can also be customized, see the description of Graphite for Silverlight for more details. Zooming of the diagram is implemented through the mouse-wheel. The only restriction of the demo is the maximum amount of ten nodes.

Loading nodes accurs through some XML format which you can define yourself, it’s not part of the control and it allows in this way a wide variety of imports/exports. It would be quite easy, in particular, to attach the application to some web or WCF service and load/unload nodes accordingly (Google search results, social network visualization and so on). See also Microsoft’s .NetMap initiative in this context (it’s not WPF though).

Download the demo

The physics of networks

In its simplest form, a network is a collection of points, or nodes, joined by lines, or edges. As purely theoretical objects, networks have been the subject of academic scrutiny since at least the 18th century. But they have taken on a new practical role in recent years as a primary tool in the study of complex systems—real-world systems of interacting components, for which networks provide a simple but tremendously useful representation.1 The internet, for example, can be represented as a network of computers linked by data connections. The World Wide Web is a network of information stored on webpages and connected by hyperlinks. Social networks of friendships between individuals have received a lot of recent attention, and other kinds of social networks, such as those of professional or business contacts, are also attracting their share of interest. Biological networks, such as the interrelated metabolic reactions that run the cell or the food web of predator–prey relations in an ecosystem, are of interest in both experimental and theoretical biology. And networks are increasingly common in the study of epidemiology, computer viruses, computer software, genetics, human transportation and communication, human language, books, movies, music, and many other things. But how do physicists enter the picture?

Physicists’ interest in networks is relatively recent. Progress in the first 200 years of the field was mostly the work of mathematicians and social scientists. Leonhard Euler is often credited with the first rigorous result in graph theory (the mathematical study of networks), with his solution of the famous Königsberg bridge problem in 1765. Kenneth Appel and Wolfgang Haken’s 1976 proof of the four-color theorem—that four colors are sufficient to color any map in such a way that any two adjacent regions are of different colors—is perhaps the best known recent achievement of graph theory. The empirical study of networks, meanwhile, has its foundations in sociology, in which researchers have been studying social networks since the 1930s.

Interest in networks has, however, seen its most spectacular growth in the past 10 years, with much of the fundamental research in the area being conducted, perhaps surprisingly, by physicists, whose methods turn out to be well suited to the problems of the field. The approach taken by physicists differs from those of mathematicians and sociologists in two important ways. First, unlike most mathematical work, it is founded on and largely inspired by empirical studies of real-world networks such as the internet, friendship networks, and biological networks. One reason for the subject’s rise in popularity has certainly been the increased availability of accurate and substantial network data sets.

Second, unlike most sociologists, physicists have been concerned largely with statistical properties of networks—their overall shapes and statistical signatures—rather than with properties of individual nodes or groups of nodes. Whereas a sociologist might have asked, “Which nodes in this network have the most connections?” a physicist might ask, “What is the average number of connections a node has?” or, “What is the distribution of the number of connections?” In asking those questions, physicists have stumbled across a number of intriguing network properties, mostly unremarked in earlier work, that have inspired an impressive array of new theories, techniques, algorithms, models, and measures to describe and illuminate the function of networked systems. Physicists are by no meansthe only contributors to the outpouring of new work—mathematicians, computer scientists, social scientists, biologists, and many others have made fundamental contributions—but physicists have played a central role, and physics journals have published much of the foundational work in the field.

[Taken from Physics Today November 2008 p33]

Silverlight diagramming with spring-embedder layout

Many years ago when Java appeared on the scene a little demo applet was delivered together with the Java SDK. It was not a huge piece of software but it sparked many ideas and a whole industry evolved around it (see TouchGraph for example), especially in the academic world. In those days things were frustrating for a Visual Basic developer, well any Microsoft developer in fact, because we only had ActiveX controls and these were far behind in many respects. It took many years for Microsoft to get over the COM and ActiveX disaster, it took us developers many years to finally have the possibility to do what Java was enabling then. Through Silverlight there’s finally the ease of .Net inside the browser and, in fact, much more; a lightweight version of WPF which includes animation and other fancy Flash-like stuff.
Read more

The bare bones of Unity interceptions

The Enterprise Library 4.1 was released together with Unity 1.2 in which a whole interception mechanism was added as part of the aspect-oriented approach to coding and a merge of the policy injection ideas. This little note is just a stepping stone if you wish to play with the new interception namespace.

Interceptions through attributes on interfaces

In order to intercept things through attributes you need to define your own attributes based on the HandlerAttribute class, like this for instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class WatchAttribute : HandlerAttribute
{
    public override ICallHandler CreateHandler(IUnityContainer container)
    {
        return new WatchHandler();
    }
}
public class WatchHandler : ICallHandler
{
    public int Order { get; set; }
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        Debug.WriteLine(string.Format("Method '{0}' on object '{1}' was invoked.", input.MethodBase.Name, input.Target.GetType()));
        return getNext()(input, getNext);
 
    }
 
}

Nothing extraordinary here except maybe the Order property on which more below. Next, you can put this attribute either on interface members or on the members of a class. Let’s use an interface first:

1
2
3
4
5
6
7
8
9
10
11
12
public interface IAction
{
    [Watch]
    void Run();
}
public class SomeAction : IAction
{
    public void Run()
    {
        //whatever
    }
}

The interception consists of ’something’ happening when the ‘Run’ method is called on any class implementing the IAction interface. This is quite a powerful feature; by defining an attribute and putting it on whatever interface member you can propagate some action to a wide set of classes. This gives a centralized handler across your all API, which is usually referred to as cross-cutting code in aspect-oriented terms.

Of course, in order to let things happen you need to weave it into a Unity container:

1
2
3
4
5
IUnityContainer container = new UnityContainer();
container.AddNewExtension< Interception>();
container.RegisterType< IAction, SomeAction>().Configure< Interception>().SetInterceptorFor< IAction>(new InterfaceInterceptor());
IAction action = container.Resolve< IAction>();
action.Run();

Notice the InterfaceInterceptor instance through which you tell the container to watch interceptions defined on an interface type.

On running the code you will see something like

Method ‘Run’ on object ‘DynamicModule.ns.Wrapped_IAction_7f6d32c1ea784597a6b488b524f25b0f’ was invoked.

in which you can see that some wrapping occured under the cap of Unity and a proxy was created to intercept the ‘Run’ calls.

Interceptions through attributes on virtual methods

The necessary code to intercept virtual methods is really the same as before except that now you need to use the VirtualMethodInterceptor rather than the InterfaceInterceptor:

1
container.Configure< Interception>().SetInterceptorFor< SomeAction>(new VirtualMethodInterceptor());

and instead of putting the Watch attribute on the interface you need to set it on a virtual method

1
2
3
4
5
6
7
8
public class SomeAction
{
    [Watch]
    public virtual void Run()
    {
        //whatever
    }
}

Interceptions through rules

The alternative to attribute based interceptions is to filter out the stuff you want to intercept through a rule, say like the following:

1
2
3
4
5
6
7
public class MyRule : IMatchingRule
{
    public bool Matches(MethodBase member)
    {
        return member.Name == "DoIt";
    }
}

The MethodBase gives you information on the member being part of some class and you could inject at this place some security code to check access to the member. This rule is baked into the container through the configuration of the Interception block:

1
2
3
4
5
6
7
8
9
10
11
IUnityContainer container = new UnityContainer();
container.AddNewExtension< Interception>();
container.RegisterType< MyClass>();
container.Configure<interception>()
    .AddPolicy("TheNameYouLike")
    .AddMatchingRule(new MyRule())
    .AddCallHandler(new WatchHandler());
container.Configure< Interception>().SetInterceptorFor< MyClass>(new TransparentProxyInterceptor());
MyClass c = container.Resolve< MyClass>();
c.DoIt();
</interception>

You can add multiple handlers to a rule but there is a catch here: the class you wish to intercept needs to inherit from MarshalByRefObject. While it doesn’t harm to let one of your classes inherit from it, it does represent a constraint in general.

1
2
3
4
5
6
7
8
9
10
11
12
13
public class MyClass : MarshalByRefObject
{
    public virtual void DoIt()
    {
        //whatever you like
        return;
    }
    [InjectionConstructor]
    public MyClass()
    {
 
    }
}

If you scan the inheritance list of MarshalByRefObject you’ll not see many classes you use in mainstream code and, in fact, the MarshalByRefObject seems to me more a remnant of the remoting era. So, for practical purposes this could be a problem.

Order please

The ICallHandler has an Order property which allows you to organize handler if multiple have been assigned. As an experiment, define the following handlers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class WatchHandler : ICallHandler
{
    public int Order { get; set; }
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        Debug.WriteLine(string.Format("First watch: Method '{0}' on object '{1}' was invoked and caught in order {2}.", input.MethodBase.Name, input.Target.GetType(), Order));
        return getNext()(input, getNext);
 
    }
 
}
public class WatchHandler2 : ICallHandler
{
    public int Order { get; set; }
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        Debug.WriteLine(string.Format("Second watch: Method '{0}' on object '{1}' was invoked  and caught in order {2}.", input.MethodBase.Name, input.Target.GetType(),Order));
        return getNext()(input, getNext);
 
    }
 
}

and assign them like this

1
2
3
4
5
6
7
WatchHandler w1 = new WatchHandler { Order = 1};
WatchHandler2 w2 = new WatchHandler2 { Order = 2};
container.Configure< Interception>()
    .AddPolicy("TheNameYouLike")
    .AddMatchingRule(new MyRule())
    .AddCallHandler(w2)
    .AddCallHandler(w1);

Now switch the last two line of code and you will notice that it doesn’t matter in which order they are put there. This is because the Order property is called to organize them and we assigned a higher rank to the second handler. Not a formidable feature but you never know.

keep looking »

© 2008 The Orbifold.