<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>bbv Blog</title>
	<atom:link href="http://www.bbv.ch/?feed=rss2&#038;option=com_wordpress&#038;Itemid=173" rel="self" type="application/rss+xml" />
	<link>http://www.bbv.ch?option=com_wordpress&#038;Itemid=173</link>
	<description></description>
	<lastBuildDate>Wed, 03 Oct 2012 19:37:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Multithreaded programming with Qt</title>
		<link>http://www.bbv.ch/?p=1300&#038;option=com_wordpress&#038;Itemid=173</link>
		<comments>http://www.bbv.ch/?p=1300&#038;option=com_wordpress&#038;Itemid=173#comments</comments>
		<pubDate>Wed, 03 Oct 2012 19:33:18 +0000</pubDate>
		<dc:creator>remymahler</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Multi-Threading]]></category>
		<category><![CDATA[Qt]]></category>

		<guid isPermaLink="false">http://www.bbv.ch/?p=1300&#038;option=com_wordpress&#038;Itemid=173</guid>
		<description><![CDATA[Multithreading is becoming an increasingly important part of modern programming. One reason for this is that multithreading enables a program to make the best use of available CPU cycles, thus allowing very efficient programs to be written. Another reason is &#8230; <a href="http://www.bbv.ch/?p=1300&#038;option=com_wordpress&#038;Itemid=173">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Multithreading is becoming an increasingly important part of modern programming. One reason for this is that multithreading enables a program to make the best use of available CPU cycles, thus allowing very efficient programs to be written. Another reason is that multithreading is a natural choice for handling event-driven code, which is so common in today’s highly distributed, networked, GUI-based systems.</p>
<p>Of course, the fact that widely used operating systems support multithreading is also a factor. Whatever the reasons, the increased use of multithreading is changing the way that programmers think about the fundamental architecture of a program.</p>
<p>Although C++ does not contain built-in support (*) for multithreaded programs, it is right at home in this arena.</p>
<p>In this blog we will have a look at some features of multithreaded support in the Qt-Framework.</p>
<p><span id="more-1300"></span></p>
<p>Qt is a cross–platform application development framework, originally developed and released by Trolltech, a Norwegian company. It is used to develop desktop as well as embedded GUI applications. Qt is written in C++ and is fully object-oriented.</p>
<p>At the moment Qt supports Windows, Linux/X11, Mac OS X, Embedded Linux, Symbian and Windows CE.</p>
<p>(*This is true for the old C++03 standard. In C++11 there is now a standard threading library.)</p>
<h2>Multithreading support in Qt</h2>
<p>Multithreading with Qt was supported from the first days. Since Release of Qt 4.4 some changes in the basic concepts were introduced, which change the way we can implement multithreaded applications.</p>
<p>First let us have a look at the old way of implementing multithreading in Qt and afterwards we will give two examples of the new approaches.</p>
<p>(For the examples shown we used Qt 4.8 with Microsoft Visual Studio 2010 and the Qt Add-in 1.1.10.)</p>
<h2>Multithreading, the Old Style</h2>
<p>QThread is the working horse for concurrent programming. QThread is a very convenient cross platform abstraction of native platform threads.</p>
<p>It offers some simple operations for threading such as for starting, stopping threading, querying the state of the threading state, setting the priority of the thread, etc.</p>
<p>Before release Qt 4.4, the original QThread class was abstract, so sub-classing was necessary. This is comparable to the java style of threading-implementation, which meant creating a sub-class of QThread and implementing the run method. Here is an example in the old style:</p>
<pre class="brush: cpp; title: ; notranslate">
class SampleThread : public QThread
{
   Q_OBJECT

   protected:
   virtual void run()
   {
      // do some work
      qDebug() &lt;&lt; &quot;Hello from SampleThread: Thread Id:&quot; &lt;&lt; QThread::currentThreadId();

      // Enters the main event loop and waits until exit() is called.
      exec();
   }
};
</pre>
<p>Now some manipulations with the thread:</p>
<pre class="brush: cpp; title: ; notranslate">
SampleThread aThread;
// start thread
aThread.start();
// check if thread running, returns true
qDebug()&lt;&lt; &quot;thread running &quot; &lt;&lt; aThread.isRunning();
// check if thread finished, returns false
qDebug()&lt;&lt; &quot;thread finished&quot; &lt;&lt; aThread.isFinished();

// terminate thread and wait for termination
aThread.quit();
aThread.wait();

// check if thread running, returns false
qDebug()&lt;&lt; &quot;thread running &quot; &lt;&lt; aThread.isRunning();
// check if thread finished, returns true
qDebug()&lt;&lt; &quot;thread finished&quot; &lt;&lt; aThread.isFinished();
</pre>
<p>This is a programming paradigm that many multithreading libraries follow, with classes such as QMutex, QWaitCondition and QFuture.</p>
<p>QThread objects can communicate with each other by posting events with QCoreApplication::postEvent(QObject* receiver, QEvent* event) and processing them by overriding the operation bool QObject::event(QEvent* e).</p>
<p>Here an example:</p>
<pre class="brush: cpp; title: ; notranslate">
virtual bool event ( QEvent * e )
{
   if (e-&gt;type() == QEvent::User)
   {
      qDebug() &lt;&lt; &quot;Processing event&quot;;
      //...
      return true;
   }
   return false;
}
</pre>
<p>To synchronize threads we can use QWaitCondition. QWaitCondition provides a condition variable for synchronizing threads. In the caller thread you would call “wakeOne” to wake up one of many server objects or “wakeAll” to wake them all up.</p>
<p>In the server thread you wait on a locked QMutex object.</p>
<p>Let’s have a look at an example:</p>
<p>A client class cyclically calls “callWake” to wake up one or all server objects. The server objects wait on a QMutex object and log out some text when triggered.</p>
<pre class="brush: cpp; title: ; notranslate">
class Client : public QThread
{
   Q_OBJECT
   public:
   Client(QWaitCondition* cond):
      QThread(0),
      mpWaitCondition(cond){}
   protected:
   void run()
   {
      while(true)
      {
         sleep(1);
         callWake();
      }
   }
   private:
   void callWake()
   {
      // wake up the Server objects
      mpWaitCondition-&gt;wakeOne();
      //mpWaitCondition-&gt;wakeAll();
      qDebug() &lt;&lt; &quot;client  called wake all,.thread:&quot; &lt;&lt; QThread::currentThreadId();
   }

   QWaitCondition* mpWaitCondition;
};

class Server : public QThread
{
   Q_OBJECT
   public:
   Server(QWaitCondition* cond):QThread(0),
      mpWaitCondition(cond){}
   protected:
   void run()
   {
      while (true)
      {
         QMutexLocker locker(&amp;mutex);
         mpWaitCondition-&gt;wait(&amp;mutex);
         qDebug() &lt;&lt; &quot;Server triggered,........thread:&quot; &lt;&lt; QThread::currentThreadId();
      }
   }

   private:
   QWaitCondition* mpWaitCondition;
   QMutex mutex;
};
</pre>
<p>Now let’s instantiate the classes and see what happens:</p>
<pre class="brush: cpp; title: ; notranslate">
QWaitCondition mCond;

Client client(&amp;mCond);
Server server1(&amp;mCond);
Server server2(&amp;mCond);

server1.start();
server2.start();
client.start();
</pre>
<p>The output with “wakeOne” shows that only one of the two server objects is woken up.</p>
<pre class="brush: plain; title: ; notranslate">
client  called wake all,.thread: 0x1b70
Server triggered,........thread: 0x2438
client  called wake all,.thread: 0x1b70
Server triggered,........thread: 0x1a6c
client  called wake all,.thread: 0x1b70
Server triggered,........thread: 0x2438
</pre>
<p>Replacing “wakeOne” with “wakeAll” shows the expected output. Both servers are triggered:</p>
<pre class="brush: plain; title: ; notranslate">
client  called wake all,.thread: 0x1814
Server triggered,........thread: 0x1f94
Server triggered,........thread: 0xd7c
client  called wake all,.thread: 0x1814
Server triggered,........thread: 0x1f94
Server triggered,........thread: 0xd7c
</pre>
<h2>Multithreading, the new Style</h2>
<p>With Qt 4.4 some basic changes were added:</p>
<ul>
<li>Thread affinity was introduced at the base level of QObject, which is the base object for nearly all Qt related classes.</li>
<li>Signal and slot connections can now be used between objects of different thread affinity.</li>
<li>QThread gained a default run implementation.</li>
</ul>
<p>These changes allow us to implement multithreading in another more elegant way.</p>
<p>In the following example we want to implement a simple ping-pong with different threads. Here a sequence diagram of what we intend to code:</p>
<p><a href="http://www.bbv.ch/components/com_wordpress/wp/wp-content/uploads/2012/10/Sequence1.png"><img class="alignnone size-full wp-image-1303" src="http://www.bbv.ch/components/com_wordpress/wp/wp-content/uploads/2012/10/Sequence1.png" alt="" width="572" height="433" /></a></p>
<p>A ping object in thread “ClientThread” sends a “sendPing” to an object pong in “ServerThread”. The pong object sends back a “sendPong” to the ping object. The object ping starts a timer and sends back a “sendPing” at timer expiration.</p>
<p>The Ping class:</p>
<pre class="brush: cpp; title: ; notranslate">
class Ping : public QObject
{
   Q_OBJECT

signals:
   void sendPing();

public slots:
   void startTimerForPing()
   {
      qDebug() &lt;&lt; &quot;Ping::startTimerForPing,......Thread Id:&quot; &lt;&lt; QThread::currentThreadId();
      QTimer::singleShot(100, this, SLOT(timeoutSendPing()));
   }

   void timeoutSendPing()
   {
      qDebug() &lt;&lt; &quot;Ping::timeoutSendPing,........Thread Id:&quot; &lt;&lt; QThread::currentThreadId();
      emit sendPing();
   }
};
</pre>
<p>The Pong class:</p>
<pre class="brush: cpp; title: ; notranslate">
class Pong : public QObject
{
   Q_OBJECT

signals:
   void sendPong();

public slots:
   void receivePing()
   {
      qDebug() &lt;&lt; &quot;Pong::receivePing, sendPong,..Thread Id:&quot; &lt;&lt; QThread::currentThreadId();
      emit sendPong();
   }
};
</pre>
<p>Now let’s instantiate the classes and connect the signals and slots:</p>
<pre class="brush: cpp; title: ; notranslate">
// example pingpong
Ping ping;
Pong pong;

// connect the signals and slots *
pong.connect(&amp;ping, SIGNAL(sendPing()), SLOT(receivePing()));
ping.connect(&amp;pong, SIGNAL(sendPong()), SLOT(startTimerForPing()));
ping.connect(&amp;ClientThread, SIGNAL(started()), SLOT(startTimerForPing()));

QThread ClientThread;
QThread ServerThread;

// move the objects ping and pong to another thread.
// (i.e. set the thread affinity of the objects)
ping.moveToThread(&amp;ClientThread);
pong.moveToThread(&amp;ServerThread);

ClientThread.start();
ServerThread.start();
</pre>
<p>When we start it we get:</p>
<pre class="brush: plain; title: ; notranslate">
Ping::startTimerForPing,......Thread Id: 0x4318
Ping::timeoutSendPing,........Thread Id: 0x4318
Pong::receivePing, sendPong,..Thread Id: 0x419c
Ping::startTimerForPing,......Thread Id: 0x4318
Ping::timeoutSendPing,........Thread Id: 0x4318
Pong::receivePing, sendPong,..Thread Id: 0x419c
Ping::startTimerForPing,......Thread Id: 0x4318
Ping::timeoutSendPing,........Thread Id: 0x4318
Pong::receivePing, sendPong,..Thread Id: 0x419c
Ping::startTimerForPing,......Thread Id: 0x4318
</pre>
<p>The interesting thing here is the QObject::connect() method, which connects signals and slots:</p>
<pre class="brush: cpp; title: ; notranslate">
bool QObject::connect(const QObject *sender,
                      const char *signal,
                      const QObject *receiver,
                      const char *method,
                      Qt::ConnectionType type = Qt::AutoConnection);
</pre>
<p>The last parameter is the connection type and it is important to understand it.</p>
<p>The default value is Qt::AutoConnection, meaning that if the signal is emitted from a different thread than the receiving object, the signal is queued, behaving as Qt::QueuedConnection (asynchronous). Otherwise, the slot is invoked directly (synchronous), behaving as Qt::DirectConnection. The type of connection is determined when the signal is emitted.</p>
<p>However you can override the behavior: To synchronously call one thread from another you could use Qt::BlockingQueuedConnection meaning that the call will return after it was processed.</p>
<p>But be aware that you could run into big trouble, such as a deadlock. Let us create a deadlock situation by modifying the code above:</p>
<pre class="brush: cpp; title: ; notranslate">
pong.connect(&amp;ping, SIGNAL(sendPing()), SLOT(receivePing()), Qt::BlockingQueuedConnection);
ping.connect(&amp;pong, SIGNAL(sendPong()), SLOT(startTimerForPing()), Qt::BlockingQueuedConnection);
ping.connect(&amp;ClientThread, SIGNAL(started()), SLOT(startTimerForPing()), Qt::BlockingQueuedConnection);
</pre>
<p>When we start the example we get following output:</p>
<pre class="brush: plain; title: ; notranslate">
Qt: Dead lock detected while activating a BlockingQueuedConnection: Sender is QThread(0x20fbb8), receiver is Ping(0x20fba0)
</pre>
<p>So, at least we have some hints of a deadlock situation.</p>
<h2>Class QThreadPool</h2>
<p>QThreadPool was also introduced with Qt 4.4. It manages and recycles individual QThread objects to help reduce thread creation costs in programs that use threads. For performance reasons it is recommended that QThreadPool contains the same number of threads as the number of available cpu-cores.</p>
<p>QThreadPool expects an object of type QRunnable to execute it in a thread.</p>
<pre class="brush: cpp; title: ; notranslate">
class MyRunnable : public QRunnable
{
public:
   void run()
   {
      // the code you want to execute in a separate thread
      qDebug() &lt;&lt; &quot;MyRunnable::run start, Thread Id:&quot; &lt;&lt; QThread::currentThread();
   }
};
</pre>
<p>Let’s put it all together:</p>
<pre class="brush: cpp; title: ; notranslate">
MyRunnable* pWork = new MyRunnable();
pWork-&gt;setAutoDelete(false);
QThreadPool *threadPool = QThreadPool::globalInstance();

// gives the number of
qDebug() &lt;&lt; &quot;maxThreadCount:&quot; &lt;&lt; threadPool-&gt;maxThreadCount();
// start the work
threadPool-&gt;start(pWork);
…
// do something else
threadPool-&gt;waitForDone();
</pre>
<p>You might have noticed the command “setAutoDelete”. If we do not set it, the object will be deleted after termination by the QThreadPool object itself. So if you need to access the MyRunnable object after processing to get any results out of it, it is required to set auto-delete to false.</p>
<h2>Summary</h2>
<p>In this short overview we have seen that Qt provides quite a good foundation for platform independent multithreading in c++. The possibilities of Qt have become even better with the arrival of Qt 4.4. It allows us to write multithreaded application in a more elegant way.</p>
<p>At the moment we are waiting for the official release of Qt 5, which will also introduce some exciting new features.</p>
<p>For more information have a look at <a href="http://qt-project.org">http://qt-project.org</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.bbv.ch/?feed=rss2&#038;amp;p=1300&#038;option=com_wordpress&#038;Itemid=173</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Gradle build system: a short overview</title>
		<link>http://www.bbv.ch/?p=1243&#038;option=com_wordpress&#038;Itemid=173</link>
		<comments>http://www.bbv.ch/?p=1243&#038;option=com_wordpress&#038;Itemid=173#comments</comments>
		<pubDate>Wed, 12 Sep 2012 09:00:50 +0000</pubDate>
		<dc:creator>Marco Poli</dc:creator>
				<category><![CDATA[ALM]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Build]]></category>
		<category><![CDATA[Gradle]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.bbv.ch/?p=1243&#038;option=com_wordpress&#038;Itemid=173</guid>
		<description><![CDATA[Since the Gradle build system (http://www.gradle.org) gets more and more attention I decided to have a look at how it works. This article should give you a brief overview of some of the features so that you get the taste &#8230; <a href="http://www.bbv.ch/?p=1243&#038;option=com_wordpress&#038;Itemid=173">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Since the Gradle build system (<a href="http://www.gradle.org">http://www.gradle.org</a>) gets more and more attention I decided to have a look at how it works. This article should give you a brief overview of some of the features so that you get the taste of Gradle. It is not meant to be a tutorial to get you started and it&#8217;s recommended that you know about another build system. <span id="more-1243"></span></p>
<h2>What is it?</h2>
<p>Gradle is a build system that combines and extends the best features of Ant and Maven. It supports task based build processes like Ant and follows convention over configuration like Maven. On top of that, Gradle build scripts are written in the Groovy language allowing to define more complex behaviour in cases where it is necessary. But you don’t need to be a Groovy expert because Gradle comes with a domain specific language (DSL) to define the builds.</p>
<p>Dependencies can be managed using Ivy and Maven repositories or by yourself if that is required. Most of the behaviour is defined in Gradle plug-ins that ship with its distribution. They can be used out of the box and adapted to your needs.</p>
<h2>A simple example</h2>
<p>A simple example of a <code>build.gradle</code> script for a Java project looks like this:</p>
<pre class="brush: groovy; title: ; notranslate">
apply plugin: 'java'
</pre>
<p>It expects the default layout from Maven which consists of <code>src/main/java</code>, <code>src/main/resource</code>, <code>src/test/java</code> and <code>src/test/resource</code>. And it expects the source to be compatible with the current JVM it is running on. To change these properties of the &#8216;java&#8217; plug-in you can use Gradle&#8217;s DSL:</p>
<pre class="brush: groovy; title: ; notranslate">
sourceSets.main.java.srcDirs = ['src/java', 'src/generated']
sourceCompatibility = 1.6
</pre>
<h2>Dependency management</h2>
<h3>Repositories</h3>
<p>Gradle can access Maven and Ivy repositories. Here are some samples how to configure the repositories:</p>
<pre class="brush: groovy; title: ; notranslate">
repositories {
  mavenLocal()
  maven {
    url &quot;http://repo.mycompany.com/repo&quot;
  }
  mavenCentral()
}

repositories {
  ivy {
    url &quot;http://repo.mycompany.com/repo&quot;
  }
}
</pre>
<p>The look-ups will be done in the order given within the repositories section. So in the above Maven example it will first look in the local repository of the user, then on the company&#8217;s server and finally on Maven Central.</p>
<h3>Dependencies</h3>
<p>To depend on an internal module, i.e. a module from the same project, you just write:</p>
<pre class="brush: groovy; title: ; notranslate">
dependencies {
  compile project(':shared')
}
</pre>
<p>You can also add dependencies to external modules from Maven or Ivy repositories if you have defined them as described above.</p>
<pre class="brush: groovy; title: ; notranslate">
dependencies {
  runtime group: 'org.hibernate', name: 'hibernate', version: '3.0.5'
  testRuntime 'org.mockito:mockito-core:1.8.4'
}
</pre>
<p>The above sample contains the long and the short version of a module identifier. If you have a dependency on a local file then you can specify it with:</p>
<pre class="brush: groovy; title: ; notranslate">
dependencies {
  compile files('libs/a.jar', 'libs/b.jar')
  testCompile fileTree(dir: 'testlibs', include: '*.jar')
}
</pre>
<p>More sophisticated features can be found in the documentation and include stuff like:</p>
<ul>
<li>overwriting transitive dependencies</li>
<li>use Ivy specific dependency features</li>
<li>etc.</li>
</ul>
<h2>Tasks</h2>
<p>Tasks are the central building blocks of the build process. They consist of two lists of actions. One list is to configure the task and the other to execute it. Here is a sample:</p>
<pre class="brush: groovy; title: ; notranslate">
// Just define an empty task
task myTaskA

// Add a configuration action
myTaskA {
  println &quot;config A&quot;
}

// Add an execution action
myTaskA &lt;&lt; {
  println &quot;action A&quot;
}

// Another task depending on myTaskA with configuration and action
task myTaskB (dependsOn: myTaskA) {
  println &quot;config B&quot;

  doLast {
    println &quot;action B&quot;
  }
}
</pre>
<p>Now you can start it:</p>
<pre class="brush: bash; title: ; notranslate">
$ gradle myTaskB
</pre>
<p>The configuration steps will be executed first. And since myTaskB depends on myTaskA the output will be:</p>
<pre class="brush: bash; title: ; notranslate">
config A
config B
:myTaskA
action A
:myTaskB
action B

BUILD SUCCESSFUL
</pre>
<p>Tasks can also be of a predefined type. The follwoing example uses the JavaExec type to start some Java code:</p>
<pre class="brush: groovy; title: ; notranslate">
apply plugin: 'java'

… // dependencies, repositories etc.

task startMain(type: JavaExec, dependsOn: classes) {
  main = 'mypackage.Main'
  args = &quot;-x -y -z&quot;.split().toList()
  classpath sourceSets.main.classesDir
  classpath configurations.compile
}
</pre>
<p>The command <code>gradle startMain</code> prepares the classes and then starts the program using the classes and also the external dependencies as classpath.</p>
<h2>Maven sample comparison</h2>
<p>Just to be clear: this is not an A is better than B comparison. The purpose is only to show you the two different versions of a Maven and a Gradle build script that achieve the same thing.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;
   xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
   xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;

   &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

   &lt;groupId&gt;ch.bbv.mavendemo&lt;/groupId&gt;
   &lt;artifactId&gt;simpleMavenDemo&lt;/artifactId&gt;
   &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;

   &lt;properties&gt;
       &lt;java.source.version&gt;1.7&lt;/java.source.version&gt;
       &lt;junit.version&gt;4.8.2&lt;/junit.version&gt;
   &lt;/properties&gt;

   &lt;dependencies&gt;
       &lt;dependency&gt;
           &lt;groupId&gt;junit&lt;/groupId&gt;
           &lt;artifactId&gt;junit&lt;/artifactId&gt;
           &lt;version&gt;${junit.version}&lt;/version&gt;
           &lt;scope&gt;test&lt;/scope&gt;
       &lt;/dependency&gt;
   &lt;/dependencies&gt;

   &lt;build&gt;
       &lt;plugins&gt;
           &lt;plugin&gt;
               &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
               &lt;version&gt;2.3.1&lt;/version&gt;
               &lt;configuration&gt;
                   &lt;source&gt;${java.source.version}&lt;/source&gt;
                   &lt;target&gt;${java.source.version}&lt;/target&gt;
               &lt;/configuration&gt;
           &lt;/plugin&gt;
       &lt;/plugins&gt;
   &lt;/build&gt;
&lt;/project&gt;
</pre>
<p>In Gradle this would be:</p>
<pre class="brush: groovy; title: ; notranslate">
apply plugin: 'java'
apply plugin: 'maven'

group = 'ch.bbv.gradledemo'
version = '0.0.1-SNAPSHOT'
//the default artifact id is the project name, which is per default the directory name of the project

project.ext.junitVersion='4.8.2'

sourceCompatibility = 1.7
targetCompatibility = 1.7

repositories {
   mavenCentral()
}

dependencies {
   testCompile 'junit:junit:'+junitVersion
}
</pre>
<p>The ‘maven’ plug-in allows you to install the artifact in your local Maven repository. Gradle’s DSL makes the build script much easier to read. Of course one could use polyglot Maven but that didn’t take off yet.</p>
<h2>IDE integration</h2>
<p>The first thing I tried was the Gradle plug-in called &#8216;eclipse&#8217; (it&#8217;s a bit unlucky that everything is now called plug-in). This plug-in can generate eclipse configuration files with settings, project and classpath. This works quite well but you have to update and refresh the project yourself after changing the build.gradle file.</p>
<p>The opposite way around there are also plug-ins for eclipse. The first one is Groovy support so you can edit Groovy code in eclipse. The second one is the Gradle plug-in itself which manages the dependencies of your project, allows you to start Gradle tasks and more.</p>
<p>There is support for other IDEs as well. The current state of tooling can be found here: <a href="http://www.gradle.org/tooling">http://www.gradle.org/tooling</a></p>
<h2>Documentation</h2>
<p>Gradle comes with a comprehensive set of documentation including a user guide, reference material and even a book titled “Building and Testing with Gradle”. You can read the book online if you register on Gradleware’s web site. It’s a good read and covers all the stuff you need to get started with Gradle.</p>
<p>The user guide documents all the parts of Gradle and will be continuously extended as Gradle grows. The reference material is generated Java/Groovy doc for Gradle’s API and DSL.</p>
<h2>Conclusion</h2>
<p>I see three scenarios where Gradle can be a good candidate for your build system.</p>
<ol>
<li>If you are currently using Ant and the build.xmls get too complicated to handle. With the task based build and the support for existing Ant tasks, Gradle support the migration from Ant.</li>
<li>You have trouble to get Maven to do what you want and maybe already started to write your own Maven plug-ins. Gradle supports the convention over configuration paradigm similar to Maven but can also be scripted with Groovy to do more powerful stuff.</li>
<li>You start a new project.</li>
</ol>
<p>Gradle as a build system makes a very good impression to me. Hopefully there will be more plug-ins developed when more and more projects use it. I&#8217;ve seen that a Jacoco plug-in is under development for example. Gradle itself will continuously be extended and there is also a short- and long-term road-map available. It is licensed under the Apache License, Version 2.0 and is used by open source projects like Spring and Hibernate and also by commercial entities.</p>
<p>Even though it has a bit of a steep learning curve it is worth a closer look.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bbv.ch/?feed=rss2&#038;amp;p=1243&#038;option=com_wordpress&#038;Itemid=173</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>bbv Software Services with eu Domain</title>
		<link>http://www.bbv.ch/?p=1274&#038;option=com_wordpress&#038;Itemid=173</link>
		<comments>http://www.bbv.ch/?p=1274&#038;option=com_wordpress&#038;Itemid=173#comments</comments>
		<pubDate>Tue, 11 Sep 2012 19:57:09 +0000</pubDate>
		<dc:creator>Philipp Kronenberg</dc:creator>
				<category><![CDATA[Announcement]]></category>

		<guid isPermaLink="false">http://bbv.ch/?p=1274&#038;option=com_wordpress&#038;Itemid=173</guid>
		<description><![CDATA[As of now bbv Software Services also is available under www.bbv.eu to take into account the opening of our German branch earlier this month.]]></description>
			<content:encoded><![CDATA[<p>As of now bbv Software Services also is available under <a href="http://www.bbv.eu" target="_blank">www.bbv.eu</a> to take into account the opening of our German branch earlier this month.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bbv.ch/?feed=rss2&#038;amp;p=1274&#038;option=com_wordpress&#038;Itemid=173</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Agile Requirements Engineering mit dem Team Foundation Server 2012</title>
		<link>http://www.bbv.ch/?p=1233&#038;option=com_wordpress&#038;Itemid=173</link>
		<comments>http://www.bbv.ch/?p=1233&#038;option=com_wordpress&#038;Itemid=173#comments</comments>
		<pubDate>Fri, 07 Sep 2012 11:17:12 +0000</pubDate>
		<dc:creator>Philipp Kronenberg</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Agile]]></category>
		<category><![CDATA[ALM]]></category>
		<category><![CDATA[Requirement]]></category>
		<category><![CDATA[Team Foundation Server]]></category>
		<category><![CDATA[TFS]]></category>

		<guid isPermaLink="false">http://www.bbv.ch/?p=1233&#038;option=com_wordpress&#038;Itemid=173</guid>
		<description><![CDATA[In ihrem neusten Artikel zeigen die beiden Softwareingenieure von bbv Software Services, Thorsten Ruf und Roland Simon, die neuen Konzepte des Team Foundation Servers (TFS) 2012 für die aktive Unterstützung des agiles Requirements Engineerings. Sie beleuchten insbesondere die UI-Planung via Storyboard und den &#8230; <a href="http://www.bbv.ch/?p=1233&#038;option=com_wordpress&#038;Itemid=173">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In ihrem neusten Artikel zeigen die beiden Softwareingenieure von bbv Software Services, Thorsten Ruf und Roland Simon, die neuen Konzepte des Team Foundation Servers (TFS) 2012 für die aktive Unterstützung des agiles Requirements Engineerings. Sie beleuchten insbesondere die UI-Planung via Storyboard und den Request Feedback.</p>
<p>Thorsten Ruf und Roland Simon sind Experten für die Einführung, den Betrieb sowie individuelle Anpassungen und Migrationen des Team Foundation Servers.</p>
<p><a href="http://it-republik.de/dotnet/windowsdeveloper-ausgaben/Windows-Azure-000517.html" target="_blank">Erschienen im windows.developer, 10.2012</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.bbv.ch/?feed=rss2&#038;amp;p=1233&#038;option=com_wordpress&#038;Itemid=173</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to find misplaced or misnamed unit tests with NDepend</title>
		<link>http://www.bbv.ch/?p=1230&#038;option=com_wordpress&#038;Itemid=173</link>
		<comments>http://www.bbv.ch/?p=1230&#038;option=com_wordpress&#038;Itemid=173#comments</comments>
		<pubDate>Wed, 05 Sep 2012 10:50:44 +0000</pubDate>
		<dc:creator>ursenzler</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Clean Code]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[NDepend]]></category>
		<category><![CDATA[Unit-Test]]></category>

		<guid isPermaLink="false">http://www.bbv.ch/?p=1230&#038;option=com_wordpress&#038;Itemid=173</guid>
		<description><![CDATA[In my current project, we do a lot of refactoring to keep the source code as simple and understandable as possible. This involves a lot of renaming of classes and moving classes between namespaces to structure the code in a &#8230; <a href="http://www.bbv.ch/?p=1230&#038;option=com_wordpress&#038;Itemid=173">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In my current project, we do a lot of refactoring to keep the source code as simple and understandable as possible. This involves a lot of renaming of classes and moving classes between namespaces to structure the code in a better understandable way (<a title="Structure your code by feature" href="http://www.planetgeek.ch/2012/01/25/3077/">here</a> is explained how we structure our code). Sometimes, this results in unit tests not renamed or moved along with the production classes they test.</p>
<p>Therefore, I wrote some NDepend queries that show us these misplaced or misnamed test classes.</p>
<p><span id="more-1230"></span></p>
<h3>Our coding guidelines</h3>
<p>First, I have to state our coding guidelines regarding unit test structure and naming because the queries below are built against them.</p>
<h4>Unit test class name</h4>
<p>Each unit test class is named following this pattern:</p>
<p><code>[prefix]&lt;name of class under test&gt;Test</code></p>
<p>The prefix is optional and is used when multiple test classes exist for the same class under test. The prefix states which aspect of the class under test is tested in this specific test class. Then follows the name of the class under test and the suffix <code>Test</code>.</p>
<p>For example <code>FooTest</code> is the test class for class <code>Foo</code> and <code>ExceptionCasesBarTest</code> contains only the exception cases tests for class <code>Bar</code>.</p>
<h4>Unit test is in the same namespace as the class under test, but in a dedicated test assembly</h4>
<p>We put all our unit tests in assemblies named like the production assemblies with suffix <code>.Test</code>. That makes it easy to detect them and simplifies automatic builds.</p>
<p>Furthermore, a unit test class is always in the same namespace as the production class it is testing (we remove the <code>.Test</code> suffix in the default namespace of the test project).</p>
<h4>Name of system under test</h4>
<p>We always use the name <code>testee</code> for the instance that is under test. This helps to quickly grasp what is tested in a unit test.</p>
<pre class="brush: csharp; title: ; notranslate">
[TestFixture]
public class FooTest
{
    private Foo testee;

    [SetUp]
    public void SetUp()
    {
        this.testee = new Foo();
    }

    [Test]
    public void DoesMagic()
    {
        string actual = this.testee.DoMagic();

        actual.Should().Be(&quot;magic&quot;);  // this is FluentAssertions, check it out!
    }
}
</pre>
<h3>Finding misplaced unit tests</h3>
<p>This is the query we use to find misplaced unit test. A misplaced unit test is not in the same namespace as the class it tests:</p>
<pre class="brush: plain; title: ; notranslate">
from p in Assemblies.WithNameWildcardMatchNotIn(&quot;*.Test&quot;).WithNameWildcardMatch(&quot;MyProject*&quot;).ChildTypes()
from t in Assemblies.WithNameWildcardMatch(&quot;*.Test&quot;).ChildTypes()
where t.IsUsing(p)
    &amp;&amp; t.Name.EndsWith(p.Name + &quot;Test&quot;)
    &amp;&amp; t.ParentNamespace.Name != p.ParentNamespace.Name
select new { Class = p, Test = t, ClassNamespace = p.ParentNamespace, TestNamespace = t.ParentNamespace }
</pre>
<ul>
<li>select all types of our production assemblies (assemblies starting with our project name and not ending in <code>Test</code>)</li>
<li>select all types of our unit test assemblies</li>
<li>match test class and production class by checking whether the test class uses the production class and matches the name pattern (test class name ends with production class name + Test)</li>
<li>take only the found pairs that don&#8217;t have the same namespace</li>
<li>print the name of the class and test class and their namespaces</li>
</ul>
<h3>Finding misnamed unit tests (containing a testee):</h3>
<p>This is the query to find unit test classes with an incorrect name, not following our name pattern:</p>
<pre class="brush: plain; title: ; notranslate">
from p in Assemblies.WithNameWildcardMatchNotIn(&quot;*.Test&quot;).WithNameWildcardMatch(&quot;MyProject*&quot;).ChildTypes()
from t in Assemblies.WithNameWildcardMatch(&quot;*.Test&quot;).ChildTypes()
where t.IsUsing(p)
    &amp;&amp; t.Fields.Where(f =&gt; f.Name == &quot;testee&quot;).Any()
    &amp;&amp; t.Fields.Single(f =&gt; f.Name == &quot;testee&quot;).FieldType == p
    &amp;&amp; !t.Name.EndsWith(p.Name.Substring(0, p.Name.IndexOf(&quot;&amp;&amp; !t.IsGeneratedByCompiler
select new { Class = p, Test = t, t.ParentNamespace }
</pre>
<ul>
<li>select all types of our production assemblies (assemblies starting with our project name and not ending in <code>Test</code>)</li>
<li>select all types of our unit test assemblies</li>
<li>match test class and production class by checking whether the test class uses the production class and the type of the field testee</li>
<li>take only class pairs that do not follow the naming convention</li>
<li>skip generated classes</li>
</ul>
<h3>Finding unit tests missing <code>TestFixture</code> or not named with suffix <code>Test</code>:</h3>
<p>This query finds unit test classes that miss either the <code>TestFixture</code> attribute or the suffix <code>Test</code> in the class name:</p>
<pre class="brush: plain; title: ; notranslate">
from t in Assemblies.WithNameWildcardMatch(&quot;*.Test&quot;).ChildTypes()
where
(
    t.HasAttribute(&quot;NUnit.Framework.TestFixtureAttribute&quot;)
    &amp;&amp; !t.Name.EndsWith(&quot;Test&quot;)
) ||
(
    !t.HasAttribute(&quot;NUnit.Framework.TestFixtureAttribute&quot;)
    &amp;&amp; t.Name.EndsWith(&quot;Test&quot;)
) ||
(
    t.InstanceMethods.Where(m =&gt; m.HasAttribute(&quot;NUnit.Framework.TestAttribute&quot;) || m.HasAttribute(&quot;NUnit.Framework.TestCaseAttribute&quot;)).Any()
    &amp;&amp; !t.Name.EndsWith(&quot;Test&quot;)
)
orderby t.Name
select new { t, t.ParentNamespace }
</pre>
<ul>
<li>take all types from a test assembly that either have the <code>TestFixture</code> attribute or end with <code>Test</code>, but miss the other</li>
<li>take all types from a test assembly that do have test methods but their name do not end in <code>Test</code></li>
</ul>
<h3>Conclusions</h3>
<p>NDepend queries can easily be used to spot unit test classes not complying with your coding conventions.</p>
<p>This is a great help after a refactoring sessions to check whether all parts are still in their correct place.</p>
<p>These queries can easily be changed to be used for other testing frameworks than NUnit or other coding conventions.</p>
<p>Let me know if you have some cool NDepend queries of your own.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bbv.ch/?feed=rss2&#038;amp;p=1230&#038;option=com_wordpress&#038;Itemid=173</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exclusive RavenDB Workshop with Ayende Rahien in Lucerne</title>
		<link>http://www.bbv.ch/?p=1222&#038;option=com_wordpress&#038;Itemid=173</link>
		<comments>http://www.bbv.ch/?p=1222&#038;option=com_wordpress&#038;Itemid=173#comments</comments>
		<pubDate>Mon, 03 Sep 2012 09:21:26 +0000</pubDate>
		<dc:creator>Philipp Kronenberg</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[#dotznt]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[Ayende Rahien]]></category>
		<category><![CDATA[RavenDB]]></category>

		<guid isPermaLink="false">http://bbv.ch/?p=1222&#038;option=com_wordpress&#038;Itemid=173</guid>
		<description><![CDATA[We are extremely proud to present a 2-day workshop about RavenDB with the inventor himself. Oren Eini aka Ayende Rahien will visit Switzerland and share with you great insights into RavenDB and especially the new version 1.2 release. Falling asleep &#8230; <a href="http://www.bbv.ch/?p=1222&#038;option=com_wordpress&#038;Itemid=173">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>We are extremely proud to present a <strong>2-day workshop</strong> about RavenDB with the inventor himself. Oren Eini aka Ayende Rahien will visit Switzerland and share with you great insights into RavenDB and especially the new version 1.2 release. Falling asleep in your chair was yesterday. Ayende is not only a great speaker but also an extremely smart person which knows to challenge his audience. Be part of it!</p>
<p>You will learn how to use the Document Database RavenDB efficiently in your applications to save time and effort on communicating with database storage. During the course we will, as a team, build a practical application demonstrating all important data management patterns.</p>
<p>The course will be on <strong>October 1-2</strong> in Lucerne an will be held in Englisch. Limited seats available only.</p>
<p><strong><a href="http://bbv.ch/en/bbv-academy/304-2012-RavenDB-Workshop-%E2%80%93-2-Tage.html" target="_blank">Register now! </a></strong></p>
<p>Members of the .NET Usergroups Berne and Central Switzerland get a discount of 20%!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bbv.ch/?feed=rss2&#038;amp;p=1222&#038;option=com_wordpress&#038;Itemid=173</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Server-Side Traces des SQL Servers mit Hilfsprozeduren: Werkzeug für den Notfallkasten</title>
		<link>http://www.bbv.ch/?p=1216&#038;option=com_wordpress&#038;Itemid=173</link>
		<comments>http://www.bbv.ch/?p=1216&#038;option=com_wordpress&#038;Itemid=173#comments</comments>
		<pubDate>Tue, 21 Aug 2012 14:43:41 +0000</pubDate>
		<dc:creator>Philipp Kronenberg</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Announcement]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Datenbank]]></category>

		<guid isPermaLink="false">http://www.bbv.ch/?p=1216&#038;option=com_wordpress&#038;Itemid=173</guid>
		<description><![CDATA[In seinem neusten Artikel geht Georg Lampart auf die Server-Side Traces des SQL Servers ein. Probleme in der Datenbank kommen immer im ungünstigsten Moment: Der nächtliche Import schlägt fehl, Datenbanktransaktionen sind plötzlich langsam, bei einem Benutzer treten Datenbankfehler auf, die &#8230; <a href="http://www.bbv.ch/?p=1216&#038;option=com_wordpress&#038;Itemid=173">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In seinem neusten Artikel geht Georg Lampart auf die Server-Side Traces des SQL Servers ein. Probleme in der Datenbank kommen immer im ungünstigsten Moment: Der nächtliche Import schlägt fehl, Datenbanktransaktionen sind plötzlich langsam, bei einem Benutzer treten Datenbankfehler auf, die zudem auf der Testumgebung nicht nachvollzogen werden können. </p>
<p>Der SQL Server bietet mit den Server-Side Traces ein leistungsfähiges Werkzeug, das sich für Produktivsysteme sehr gut eignet. Der Einsatz wird mit vier Hilfsprozeduren vereinfacht, die im Artikel vorgestellt werden.</p>
<p>Georg Lampart ist Senior Software Engineer bei der bbv Software Services AG mit Schwerpunkt SQL-Server-Datenbankentwicklung sowie der .NET-Softwareentwicklung in Bereich Businessapplikationen.</p>
<p><a href="http://it-republik.de/dotnet/windowsdeveloper-ausgaben/Datenbanken-000508.html">Erschienen im windows.developer, 8.2012</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.bbv.ch/?feed=rss2&#038;amp;p=1216&#038;option=com_wordpress&#038;Itemid=173</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Client / Server Localization – Transfer resources</title>
		<link>http://www.bbv.ch/?p=1202&#038;option=com_wordpress&#038;Itemid=173</link>
		<comments>http://www.bbv.ch/?p=1202&#038;option=com_wordpress&#038;Itemid=173#comments</comments>
		<pubDate>Mon, 06 Aug 2012 18:47:50 +0000</pubDate>
		<dc:creator>Daniel Marbach</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Localization]]></category>

		<guid isPermaLink="false">http://www.bbv.ch/?p=1202&#038;option=com_wordpress&#038;Itemid=173</guid>
		<description><![CDATA[In my last post I described the ResourceManager and how to create a filebased ResourceManager. This post covers  how we can get resources from the server to the client and how to handle multiple resource managers and basenames. As we can &#8230; <a href="http://www.bbv.ch/?p=1202&#038;option=com_wordpress&#038;Itemid=173">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In my <a title="Client / Server Localization – Resources" href="http://www.planetgeek.ch/2012/03/23/client-server-localization-resources/" target="_blank">last post</a> I described the ResourceManager and how to create a filebased ResourceManager. This post covers  how we can get resources from the server to the client and how to handle multiple resource managers and basenames.<span id="more-1202"></span> As we can imagine a server could host multiple plugins and components which themselves would need to provide dynamic resources for the clients. In order to achieve a simple solution to compile also resources from plugins into binary resource files we need the following build task:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Project xmlns=&quot;http://schemas.microsoft.com/developer/msbuild/2003&quot;&gt;
  &lt;ItemGroup&gt;
    &lt;AvailableItemName Include=&quot;DynamicClientResource&quot; /&gt;
  &lt;/ItemGroup&gt;

  &lt;PropertyGroup&gt;
    &lt;ClientResourceDir&gt;$(OutDir)ClientResources\&lt;/ClientResourceDir&gt;
  &lt;/PropertyGroup&gt;

  &lt;PropertyGroup&gt;
        &lt;BuildDependsOn&gt;BuildClientResources;$(BuildDependsOn)&lt;/BuildDependsOn&gt;
  &lt;/PropertyGroup&gt;

  &lt;Target Name=&quot;BuildClientResources&quot; Outputs=&quot;%(DynamicClientResource.Identity)&quot;&gt;
    &lt;PropertyGroup&gt;
      &lt;ActualRelativeDir&gt;%(DynamicClientResource.RelativeDir)&lt;/ActualRelativeDir&gt;
      &lt;RelativeNamespace&gt;$(ActualRelativeDir.Replace(&quot;\&quot;,&quot;.&quot;))&lt;/RelativeNamespace&gt;
    &lt;/PropertyGroup&gt;
    &lt;MakeDir Directories=&quot;$(ClientResourceDir)&quot; Condition=&quot;Exists('%(DynamicClientResource.identity)')&quot;/&gt;
    &lt;GenerateResource
    UseSourcePath=&quot;true&quot;
    Sources=&quot;@(DynamicClientResource)&quot;
    OutputResources=&quot;@(DynamicClientResource-&gt;'$(ClientResourceDir)$(RootNamespace).$(RelativeNamespace)%(filename).resources')&quot;&gt;
    &lt;Output
      TaskParameter=&quot;OutputResources&quot;
      ItemName=&quot;Resources&quot;/&gt;
    &lt;/GenerateResource&gt;
  &lt;/Target&gt;
&lt;/Project&gt;
</pre>
<p>If we include this custom build target into our build process, plugins can simply choose the &#8220;DynamicClientResource&#8221; as custom build action for all our resource files.</p>
<p><a href="http://www.bbv.ch/components/com_wordpress/wp/wp-content/uploads/2012/08/CustomBuildAction.png"><img title="CustomBuildAction" src="http://www.bbv.ch/components/com_wordpress/wp/wp-content/uploads/2012/08/CustomBuildAction.png" alt="" width="315" height="87" /></a></p>
<p>The result of this custom target is that all plugins and components which define resources will build the binary resources into the same directory under &#8220;ClientResources\&#8221;. If we use WCF services we can now leverage WCF streaming services to transfer the binary resources to the client. A basic service contract could look like the following:</p>
<pre class="brush: csharp; title: ; notranslate">
    [ServiceContract(Namespace = &quot;http://www.planetgeek.ch/resources&quot;)]
    public interface IDynamicResourceService
    {
        [OperationContract]
        IEnumerable&lt;ResourceCatalogEntry&gt; ResourceCatalog();

        [OperationContract]
        Stream Resource(ResourceCatalogEntry resource);
    }

    [DataContract(Namespace = &quot;http://www.planetgeek.ch/resources&quot;)]
    public class ResourceCatalogEntry
    {
        [DataMember]
        public string FileName { get; set; }

        [DataMember]
        public string BaseName { get; set; }
    }
</pre>
<p>The service contract is split into two operations. One operation is to retrieve the whole resource catalog which contains information about the original file name and the base name of the resource. The second operation allows the client to stream a binary resource for a certain catalog entry. I think it is unnecessary to show how to implement the WCF service which fulfills this service contract. It is dead simple: Scan the client resource directory and provide resource catalog entries from the directory. For each acquired resource from the client open a read stream of the acquired catalog entry and return it to the client.</p>
<p>If we have this infrastructure in place the client can use a proxy to access the dynamic resource service. Upon start of the client all resources can be downloaded from the server and saved on the local disk. As you can imagine from the previous post we now need multiple file based resource managers on the client which are created dynamically from the downloaded binary resources from the server. In order to provide a unified interface for the client integration we need a simple resource manager decorator which handles this task for us.</p>
<pre class="brush: csharp; title: ; notranslate">
	public class ResourceManagerDecorator : IResourceManager
    {
        private readonly Dictionary&lt;string, ResourceManager&gt; resourceManagers;

        public ResourceManagerDecorator()
        {
            this.resourceManagers = new Dictionary&lt;string, ResourceManager&gt;();
        }

        public void AddResourceFile(string baseName, string resourceDirectory)
        {
            if (!this.resourceManagers.ContainsKey(baseName))
            {
                ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager(baseName, resourceDirectory, null);
                this.resourceManagers.Add(baseName, resourceManager);
            }
        }

        public bool IsValid(string resourceKey)
        {
			// Will be covered later
        }

        public string GetString(string resourceKey)
        {
			// Will be covered later
        }
    }
</pre>
<p>The decorator above simply creates a file based resource manager for each base name and hosts the created resource manager for future use. The next posts will cover how to build up dynamic resource keys so that they won&#8217;t collide on the client and how to hook up some magic with auto mapper to dynamically map resources with the resource manager decorator.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bbv.ch/?feed=rss2&#038;amp;p=1202&#038;option=com_wordpress&#038;Itemid=173</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Prism vs. Caliburn.Micro</title>
		<link>http://www.bbv.ch/?p=1063&#038;option=com_wordpress&#038;Itemid=173</link>
		<comments>http://www.bbv.ch/?p=1063&#038;option=com_wordpress&#038;Itemid=173#comments</comments>
		<pubDate>Thu, 26 Jul 2012 13:11:53 +0000</pubDate>
		<dc:creator>olegkopytkov</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[Caliburn]]></category>
		<category><![CDATA[Caliburn.Micro]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[prism]]></category>

		<guid isPermaLink="false">http://bbv.ch/?p=1063&#038;option=com_wordpress&#038;Itemid=173</guid>
		<description><![CDATA[One of the .NET tracks during the Bootcamp 2012 in Barcelona offered an opportunity to use, learn and analyze Caliburn.Micro 1.3. After using PRISM 1.0 for over a year I decided to compare those 2 MVVM frameworks. View and ViewModel &#8230; <a href="http://www.bbv.ch/?p=1063&#038;option=com_wordpress&#038;Itemid=173">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the .NET tracks during the Bootcamp 2012 in Barcelona offered an opportunity to use, learn and analyze Caliburn.Micro 1.3. After using PRISM 1.0 for over a year I decided to compare those 2 MVVM frameworks.<span id="more-1063"></span></p>
<p><strong>View and ViewModel communication</strong></p>
<p>I was amazed by how easy it was to start using the Caliburn.Micro, given I had some support from a CM expert. The communication between the View and ViewModel is straightforward, easy to use and yet very powerful. CM wins over PRISM in this department. <em>The ViewModel code is cleaner and I think that naming conventions are better than attributes</em>. They require more knowledge about the framework but also encourage faster implementation.</p>
<ul>
<li>Caliburn.Micro</li>
</ul>
<pre class="brush: csharp; title: ; notranslate">cal:Message.Attach=&quot;[Event Click] = [Action PortfolioClicked()]&quot;

public bool CanPortfolioClicked { ... }
public void PortfolioClicked() { ... }
</pre>
<ul>
<li>PRISM</li>
</ul>
<pre class="brush: csharp; title: ; notranslate">
&lt;Button Command=&quot;{Binding FinishCommand}&quot;/&gt;

this.FinishCommand = new DelegateCommand&lt;object&gt;(this.OnFinishCommand, this.OnCanFinishCommand);
private void OnFinishCommand(object obj) { ... }
private bool OnCanFinishCommand(object arg) { ... }</pre>
<p><strong>To choose or not to choose</strong></p>
<p>After having such a blast I had to dig deeper. I even tried to abandon the “one framework to rule them all” way of thinking. Theoretically it is possible to combine those two Frameworks. Prism provides great support for the modular application development and offers UnityBootstrapper and MefBootstrapper. Ninject Bootstrapper is available on the Ninject forums but it’s not officially supported. So basically we could use PRISM to discover and load the modules and Caliburn.Micro for the V &lt;-&gt; VM interaction.<br />
At some point I abandoned this idea since it’s just not needed:</p>
<ul>
<li>PRISM requires a View-First approach</li>
</ul>
<ol>
<li>The bootstrapper loads the modules.</li>
<li>The Views are located through the ViewExport Attributes</li>
<li>The view is instantiated and the VM is injected into the view</li>
</ol>
<pre class="brush: csharp; title: ; notranslate">
[ViewExport(RegionName = RegionNames.MainRegion)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class WatchListView : UserControl
{
     public WatchListView (WatchListViewModel watchListViewModel)
     {
          this.DataContext = watchListViewModel;
     }
}</pre>
<ul>
<li>Caliburn.Micro promotes a ViewModel-First approach</li>
</ul>
<ol>
<li>The bootstrapper loads the modules</li>
<li>IOC container finds the ViewModels that are injected into the ShellVM.</li>
<li>Views are resolved by the ViewModelBinder</li>
</ol>
<p>If the ViewModel-First approach is chosen, then a big part of PRISM is not required anymore and vice versa. Caliburn.Micro also supports View-First approach, which is not recommended. Even more Prism features would become redundant when using the Caliburn.Micro with View-First approach.</p>
<p><strong>EventAggregation</strong></p>
<p>Event aggregation is another important feature provided by both frameworks. The purpose of the Event Aggregator is to simplify event registration by channeling events from multiple objects into a single object. The usage feature is pretty much identical in both frameworks.</p>
<ul>
<li>PRISM</li>
</ul>
<p>In PRISM, an event is declared by inheriting from a CompositePresentationEvent where T is the message payload.<br />
Subscribing has up to five parameters including whether to hold a strong or weak reference to the subscriber, which thread to call subscribers on, a filter to determine if the subscriber gets the event, and the delegate to invoke.<br />
The defaults work for most situations.</p>
<pre class="brush: csharp; title: ; notranslate">
public class FooEvent : CompositePresentationEvent&lt;FooEventArgs&gt; { }
myEventAggregator.GetEvent&lt;FooEvent&gt;().Publish(fooEventArgs);
myEventAggregator.GetEvent&lt;FooEvent&gt;().Subscribe(OnFoo);
</pre>
<ul>
<li>Caliburn.Micro</li>
</ul>
<p>Event Aggregation in Caliburn Micro is simple.  In Caliburn Micro, events are plain old CLR objects (poCo).  The event argument payload, if needed, is declared in the event as one or more simple properties. Somehow the way the event aggregation works reminds me of EvenBroker in APPcelerate.<br />
This IHandle approach makes explicit and clear at a glance the relationship between interested subscribers and their subscribed events.<br />
<em>Caliburn.Micro isn’t as powerful as PRISM. Yet it prevents you from creating bugs that are very hard to pinpoint.</em> It holds weak references in the event aggregator and executes events on the UI thread.</p>
<pre class="brush: csharp; title: ; notranslate">
public class FooEvent { public string myProp; }
public class Foo : IHandle&lt;FooEvent&gt;
    {
        private IEventAggregator myEventAggregator;

        public Foo()
        {
            myEventAggregator.Subscribe(this);
        }

        public void Handle(FooEvent message)
        {

        }
    }
myEventAggregator.Publish&lt;FooEvent&gt;(new FooEvent());
</pre>
<p><strong>Navigation</strong></p>
<p>The basic navigation features are supported by both frameworks. After spending some hours analyzing the navigation features in Caliburn.Micro I have to say that PRISM offers more functionality. I wasn&#8217;t able to find support for the following features in Caliburn.Micro:</p>
<ol>
<li>State-Based Navigation &#8211; Used to display the same data with different formats and styles.</li>
<li>View lifetime management.</li>
<li>Navigation history</li>
<li>Exception handling to prevent application crashes on navigation exceptions. (For example if the view is missing or view model produces an exception during the navigation)</li>
</ol>
<p><strong>When to use PRISM or Caliburn.Micro?</strong></p>
<p>I&#8217;ve started comparing those two frameworks to find a better one. Right now I think that they&#8217;re both good just for a different type of application. If I had to develop an application with a lot of different teams working on the same application I would still pick PRISM. Support for the development of modular applications and navigation support wins here. For the smaller projects, which are being developed by a single team, I would pick Caliburn.Micro, especially if the team consists of developers that are inexperienced with both frameworks. Caliburn.Micro has everything that should be supported by a MVVM framework. On top of that less functionality also means lower complexity, resulting in lower probability of misuse or bugs.</p>
<p><strong>Further Informations</strong></p>
<p>In case you&#8217;d like more in depth information, here are some links that proved to be very informative:</p>
<ol>
<li><a title="PRISM Navigation" href="//msdn.microsoft.com/en-us/library/gg430861(v=pandp.40).aspx#sec1">http://msdn.microsoft.com/en-us/library/gg430861(v=pandp.40).aspx#sec1</a> - PRISM Navigation</li>
<li><a href="http://devlicio.us/blogs/rob_eisenberg/archive/2010/07/06/caliburn-micro-soup-to-nuts-pt-1-configuration-actions-and-conventions.aspx">http://devlicio.us/blogs/rob_eisenberg/archive/2010/07/06/caliburn-micro-soup-to-nuts-pt-1-configuration-actions-and-conventions.aspx</a> - Everything you could possibly want to know about Caliburn.Micro. A series written by Rob Eisenberg.</li>
</ol>
<p><em>I would like to thank Daniel Marbach for his invaluable help. He supported me on the technical part considering Caliburn.Micro and was kind enough to review the posting.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.bbv.ch/?feed=rss2&#038;amp;p=1063&#038;option=com_wordpress&#038;Itemid=173</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Usage of dynamic memory in a real time system</title>
		<link>http://www.bbv.ch/?p=1161&#038;option=com_wordpress&#038;Itemid=173</link>
		<comments>http://www.bbv.ch/?p=1161&#038;option=com_wordpress&#038;Itemid=173#comments</comments>
		<pubDate>Mon, 16 Jul 2012 19:20:43 +0000</pubDate>
		<dc:creator>remymahler</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[realtime]]></category>
		<category><![CDATA[tlsf]]></category>

		<guid isPermaLink="false">http://www.bbv.ch/?p=1161&#038;option=com_wordpress&#038;Itemid=173</guid>
		<description><![CDATA[Memory management is one of the most fundamental areas of software engineering. In many scripting languages you do not have to worry about memory management, but that does not make memory management any less important. In languages like C and &#8230; <a href="http://www.bbv.ch/?p=1161&#038;option=com_wordpress&#038;Itemid=173">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Memory management is one of the most fundamental areas of software engineering.<br />
In many scripting languages you do not have to worry about memory management, but that does not make memory management any less important.</p>
<p>In languages like C and C++, memory management was left to the responsibility of the software engineer. Modern C++ designs make heavy use of dynamic memory. (e.g. Inversion of control, dependency injection, factories, collections of objects, design for testability, event passing with objects, etc.)<br />
This is a standard practice in desktop applications, where memory is freely available and latency not an issue.</p>
<p>On embedded and real time systems, the situation is different:<br />
Dynamic allocation of memory may be non-deterministic, depending on the underlying operating system. Fragmentation of the dynamic memory pool can lead to a slower system responsibility over time or even worse to “out of memory” exceptions, even if there is enough memory available.</p>
<p>A conservative approach in designing real-time systems is not to use dynamic memory at all. But there are also other possibilities to implement such systems.<br />
<span id="more-1161"></span></p>
<h2>C++ Memory Spaces</h2>
<p>First let us have a look at the memory usage in C++:<br />
In C++ memory can be regarded as being divided into three parts. There is static memory, automatic variables and dynamic memory.</p>
<ul>
<li>Static memory allocation refers to the process of allocating memory at compile-time before the associated program is executed. The actual allocation of addresses to variables is performed by the embedded software development toolkit.</li>
<li>All variables declared within a block of code are automatic by default. This means they are allocated and de-allocated automatically when the program flow enters and leaves the variable&#8217;s scope. Automatic variables are stored on the stack.</li>
<li>Dynamic memory is allocated from the heap. The two key dynamic memory functions are new and delete. The allocation and deletion of memory are non-deterministic operations on most operating systems. Depending on the dynamic memory allocation strategy we may observe a degradation of performance over time due to fragmentation issues.</li>
</ul>
<p>Static memory should not cause any run-time problems. Automatic variables shouldn’t be a problem either, unless the stack size is too small and a stack overflow occurs.</p>
<p>Dynamic memory however is a big issue. One approach to manage dynamic memory on a real-time system is to use a fixed-size pre-allocated memory block, a memory pool.</p>
<h2>Memory pooling</h2>
<p>A Memory pool allows dynamic memory allocation comparable to malloc or C++’s operator new. But almost all implementations suffer from fragmentation because of variable block sizes. The use of memory pools has been considered a source of in-determinism in the real-time domain, due to the unconstrained response time of dynamic storage allocation algorithms and the fragmentation problem.</p>
<p>However there are some memory pool implementations that are capable to circumvent these issues.<br />
One of those is TLSF. (<a href="http://www.gii.upv.es/tlsf">http://www.gii.upv.es/tlsf/ </a>)</p>
<h2>Two-Level Segregated Fit memory allocator (TLSF)</h2>
<p>TLSF is a general purpose dynamic memory allocator specifically designed to meet real-time requirements. TLSF implements a two level mechanism:</p>
<p>The first level uses an array which divides free blocks in classes, that are a power of two apart (8, 16, 32, 64, etc.).  The second level subdivides each first-level class in a linear manner. The second level contains an associate bitmap used to mark which lists are empty and which ones contain a free block.</p>
<p>The advantages of this approach are:</p>
<ul>
<li>Bounded Response Time: TLSF has a constant cost for memory allocation and de-allocation of O(1).</li>
<li>Fast: TLSF executes a maximum of 168 processor instructions in a x86 architecture. It can be slightly lower or higher, depending on the compiler and optimization.</li>
<li>Efficient Memory Use: The maximum fragmentation measured is lower than 25%.</li>
</ul>
<p>(For more documentation on TLSF see also: <a href="http://www.gii.upv.es/tlsf/main/pubs/">http://www.gii.upv.es/tlsf/main/pubs/</a>)</p>
<h2>Example in c++</h2>
<p>TLSF uses a plain c interface style api. In order to use TLSF from c++ one has to overload the new and delete operators.<br />
Here are the functions that have to be implemented:</p>
<pre class="brush: cpp; title: ; notranslate">
#ifndef WRAPPER_H
#define WRAPPER_H
#include
void* operator new(std::size_t p_RequestedSize) throw (std::bad_alloc);
void operator delete(void* p_Address) throw();

void* operator new[](std::size_t p_RequestedSize) throw (std::bad_alloc);
void operator delete[](void* p_Address) throw();

void* operator new(std::size_t p_RequestedSize, const std::nothrow_t&amp; pc_Exception) throw();
void operator delete(void* p_Address, const std::nothrow_t&amp; pc_Exception) throw();

void* operator new[](std::size_t p_RequestedSize, const std::nothrow_t&amp; pc_Exception) throw();
void operator delete[](void* p_Address, const std::nothrow_t&amp; pc_Exception) throw();
#endif // WRAPPER_H
</pre>
<p>And the implementation:</p>
<pre class="brush: cpp; title: ; notranslate">
#include &quot;wrapper.h&quot;
extern &quot;C&quot;{
#include
}
void* operator new(std::size_t p_RequestedSize) throw (std::bad_alloc){
   void* const result = ::tlsf_malloc(p_RequestedSize);
   if (0 == result) {// throw exception }
   return result;
}

void operator delete(void* p_Address) throw(){
   return ::tlsf_free(p_Address);
}
// other operators follow the same scheme...
</pre>
<p>Now let’s have a look at a little demo program:</p>
<pre class="brush: cpp; title: ; notranslate">
#include
#include
#include
extern &quot;C&quot;
{
#include
}
#include &quot;wrapper.h&quot; // This redefines new and delete
// Test class
class DummyClass
{
public:
   DummyClass(){ s_counter++;};
   virtual ~DummyClass(){s_counter--;};
   static unsigned int s_counter;
protected:
   unsigned short m_pBuffer [100];
};
unsigned int DummyClass::s_counter = 0;
//-------------------------------------
int main()
{
    int mPoolSize = 65536;
    void* mPoolbuffer = ::malloc(mPoolSize);

    // create memory pool
    ::memset(mPoolbuffer, 0, mPoolSize);
    ::init_memory_pool(mPoolSize, mPoolbuffer); // TLSF function

    // statistics
    size_t  used = get_used_size(mPoolbuffer); // TLSF function
    std::cout &lt;&lt; &quot;Before new DummyClass....:&quot; &lt;&lt; used &lt;&lt; std::endl;

    // usage of operator new()
    DummyClass* pClass = new DummyClass();

    // statistics
    used = get_used_size (mPoolbuffer); // TLSF function
    std::cout &lt;&lt; &quot;After new DummyClass.....:&quot; &lt;&lt; used &lt;&lt; std::endl;

    // usage of operator delete()
    delete pClass;

    // statistics
    used = get_used_size(mPoolbuffer); // TLSF function
    std::cout &lt;&lt; &quot;After delete pClass......:&quot; &lt;&lt; used &lt;&lt; std::endl;

    // usage of operator new[]()
    char* pCharArray = new char[245];

    // statistics
    used = get_used_size(mPoolbuffer); // TLSF function
    std::cout &lt;&lt; &quot;After new char[245]......:&quot; &lt;&lt; used &lt;&lt; std::endl;

    // usage of operator delete[]()
    delete [] pCharArray;

    // statistics
    used = get_used_size(mPoolbuffer); // TLSF function
    std::cout &lt;&lt; &quot;After delete [] pChar....:&quot; &lt;&lt; used &lt;&lt; std::endl;

    // delete memory pool
    ::destroy_memory_pool(mPoolbuffer); // TLSF function
    return 0;
}
</pre>
<p>(* To enable statistics enable TLSF_STATISTIC (1) in tlsf.cpp )</p>
<p>And the output is:</p>
<pre class="brush: cpp; title: ; notranslate">
Before new DummyClass....:6384
After new DummyClass.....:6608
After delete pClass......:6384
After new char[245]......:6656
After delete [] pChar....:6384
</pre>
<h2>Summary</h2>
<p>TLSF enables you to predictably use dynamic memory in real-time applications. But the usage of dynamic memory will always increase the complexity of a real-time system. Therefore its use should be restricted to cases where it is really needed, for example in message communication related operations. Because don’t forget, with dynamic memory allocation, memory leaks can plague the system for a long time. (see also <a href="http://www.bbv.ch/?p=961&amp;option=com_wordpress&amp;Itemid=173">C++ Memory error detection on a Linux platform</a>)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bbv.ch/?feed=rss2&#038;amp;p=1161&#038;option=com_wordpress&#038;Itemid=173</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
