<?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>Semantic Architecture</title>
	<atom:link href="http://www.semanticarchitecture.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.semanticarchitecture.net</link>
	<description>Software Architecture &#38; Development</description>
	<lastBuildDate>Mon, 13 Feb 2012 21:16:39 +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>Writing a WordPress Twitter Widget</title>
		<link>http://www.semanticarchitecture.net/writing-a-wordpress-twitter-widget/</link>
		<comments>http://www.semanticarchitecture.net/writing-a-wordpress-twitter-widget/#comments</comments>
		<pubDate>Sun, 12 Feb 2012 08:23:48 +0000</pubDate>
		<dc:creator>kalkie</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.semanticarchitecture.net/?p=339</guid>
		<description><![CDATA[A WordPress plugin that shows real-time tweets that match a given search terms. This article describes how I developed this WordPress plugin.]]></description>
			<content:encoded><![CDATA[<p>On the bottom right of the screen you see a live Twitter stream. New tweets that match a given search term are show in real-time. The client script contacts Twitter to get these latest tweet so no server code is running.</p>
<p>This Twitter stream is implemented using a WordPress widget. Widgets are WordPress Plugins that add visual and interactivity options and features, such as sidebar widgets for post categories, tag clouds, navigation, search, etc. Widgets can be added, removed or rearranged via the WordPress Widgets panel and therefore require no code.</p>
<div style="height: 2em; visibility: hidden;">ANY CHARACTER HERE</div>
<h1>Widgets</h1>
<p>In this post I will explain how you can implement your own WordPress widget by showing you how I implemented the Twitter widget. The programming languages I used to develop a WordPress widget are <a title="Hypertext Preprocessor" href="http://www.php.net/" target="_blank">PHP</a> and <a title="Javascript" href="http://www.w3schools.com/js/">javascript</a> together with some HTML and CSS. I also used the <a title="JQuery" href="http://jquery.com/" target="_blank">JQuery </a>and <a title="JQuery UI" href="http://jqueryui.com/" target="_blank">JQuery UI</a> libraries for selecting HTML element and animation. PHP is the standard programming language to implement WordPress plugins.</p>
<p><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/02/Widget_Overview.jpg"><img class="size-full wp-image-346 alignnone" title="WordPress Widgets Panel" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/02/Widget_Overview.jpg" alt="" width="754" height="249" /></a></p>
<p>To start with a WordPress plugin you have to create a file with the extension .php. The file name should resemble the name of your plugin. At the top of the file a multi-line comment should be created according to the WordPress plugin format. By using this format WordPress recognizes the file as a WordPress plugin.</p>
<pre class="brush: php; title: ; notranslate">/*
Plugin Name: Twitter search smooth scrolling
Plugin URI: http://www.semanticarchitecture.net/writing-a-wordpress-twitter-widget/
Description: This plug-in shows the most recent tweets that match the search term.
Version: 1.0
Author: Patrick Kalkman
Author URI: http://www.semanticarchitecture.net/
License: GPL2
*/</pre>
<p>Notice the fields on each line such as &#8220;Plugin Name:&#8221; and &#8220;Version:&#8221;. Only the &#8220;Plugin Name&#8221; is required, the rest of the fields are optional. It is however good practice to fill the complete header. After this header it is normal to place a reference to the license of your plug-in. Most WordPress plugins use the GPL license.</p>
<h2>Widget</h2>
<p>The easiest way to create a widget is to subclass <em>WP_Widget. </em>This base class defines the basic skeleton for a WordPress widget.</p>
<pre class="brush: php; title: ; notranslate">class Foo_Widget extends WP_Widget {
 function __construct() {
   parent::WP_Widget();
  }

 function widget( $args, $instance ) {
 }

 function update( $new_instance, $old_instance ) {
 }

 function form( $instance ) {
 }
}</pre>
<p>The constructor and the four methods are going to be used to implement our widget. Let&#8217;s define them one by one.</p>
<ul>
<li>Constructor &#8211; set the name and description of the widget.</li>
<li>widget &#8211; outputs the HTML content of the widget.</li>
<li>update &#8211; processes the options that should be saved.</li>
<li>form &#8211; outputs the HTML for the options form.</li>
</ul>
<h2>Options</h2>
<p>Each WordPress widget can create options. Options are fields that can be filled using the WordPress user interface. These can be use to change the default behavior of your widget.</p>
<p><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/02/Widget_Options.jpg"><img class="size-full wp-image-374 alignnone" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="WordPress Widget Options" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/02/Widget_Options.jpg" alt="WordPress Widget Options" width="261" height="339" /></a></p>
<p>The Twitter widget has 5 options.</p>
<ul>
<li>Title &#8211; the title of the widget, shown at the top of the widget.</li>
<li>Search_query &#8211; the string used to filter the tweets.</li>
<li>refresh_interval &#8211; the time to wait until reading new tweets from Twitter.</li>
<li>tweet_interval &#8211; the time to wait before a new Tweet is shown.</li>
<li>tweet_animation_interval &#8211; the duration of the scroll and fade-in effect.</li>
</ul>
<p>The user interface to let the user enter the values of these options is created in the  <em>form</em> method. In this method HTML markup is added to add the form. See the example below which constructs the input field for the Title of the widget.</p>
<pre class="brush: php; title: ; notranslate">

function form( $instance ) {
 $defaults = array('title' =&gt; __('Semantic Tweets', WIDGET_NAME));
 $instance = wp_parse_args((array)$instance, $defaults);
 $title = strip_tags($instance['title']);?&gt;

 &lt;p&gt;
   &lt;?php _e('Title', WIDGET_NAME) ?&gt;:
   &lt;input class=&quot;widefat&quot;
     name=&quot;&lt;?php echo $this-&gt;get_field_name('title'); ?&gt;&quot; type=&quot;text&quot;
     value=&quot;&lt;?php echo esc_attr($title); ?&gt;&quot;/&gt;
 &lt;/p&gt;

 &lt;?php
}
</pre>
<p>A normal input element is used for entering values. The <em>_e()</em> function is used for localization, it uses the &#8216;Title&#8217; as the key to search for translations in the context of the widget. <em>esc_attr</em> encodes less than, greater than, ampersand, double quote and single quote. The actual value is output via $title. Multiple input fields can be created by copying this row.</p>
<h2>Update</h2>
<p>The update method is triggered when the user presses the save button in the options screen.</p>
<pre class="brush: php; title: ; notranslate">function update($new_instance, $old_instance) {
 $instance = $old_instance;
 $instance['title'] = strip_tags($new_instance['title']);
 $instance['search_query'] = strip_tags($new_instance['search_query']);
 $instance['refresh_interval'] = strip_tags($new_instance['refresh_interval']);
 $instance['tweet_interval'] = strip_tags($new_instance['tweet_interval']);
 $instance['tweet_animation_duration'] =
   strip_tags($new_instance['tweet_animation_duration']);
 return $instance;
 }</pre>
<p><em>$new_instance</em> contains the values of the fields that the user entered. By copying those values to the $instance and returning the $instance the values get saved to the WordPress database. The <strong>strip_tags</strong> is a PHP function that removes the HTML and PHP tags from the given string.</p>
<h2>Widget</h2>
<p>The widget method creates and displays the actual widget. It output HTML that forms the widget.</p>
<pre class="brush: php; title: ; notranslate">
function widget($args, $instance) {

  echo $before_widget;
  echo $before_title . $title . $after_title; ?&gt;
  &lt;div class=&quot;twitter-search-widget&quot;&gt;search-query=&quot;&lt;?php echo $search_query; ?&gt;&quot;
     refresh-interval=&quot;&lt;?php echo $refresh_interval; ?&gt;&quot;
     tweet-interval=&quot;&lt;?php echo $tweet_interval; ?&gt;&quot;
     tweet-animation-duration=&quot;&lt;?php echo $tweet_animation_duration; ?&gt;&quot;&gt;
  &lt;/div&gt;
&lt;?php echo $after_widget;
}</pre>
<p>The <strong><em>$before_widget</em></strong> and <strong><em>$after_widget</em></strong> are variables that contain markup that can be manipulated by themes. The same goes for <strong><em>$before_title</em></strong> and <em><strong>$after_title. </strong></em>Therefore, to let your widget be theme-able, you should use these variables.</p>
<p><em><strong></strong></em>The twitter widget basically is a div with an unordered list, for each new tweet an list item will be created in the unordered list. The list items will be created by javascript.</p>
<h2>Registering Javascript</h2>
<p>Javascript can be use and is supported by WordPress. Most WordPress version already include JQuery. The proper way to register a JavaScript library is by using the functions <em><strong>wp_register_script</strong></em> and <em><strong>wp_enqueue_script. </strong></em></p>
<pre class="brush: php; title: ; notranslate">function initialize_script() {
  wp_register_script('twitter-search-widget',
     plugins_url('twitter-search-smooth-scrolling.js',__FILE__ ));
  wp_enqueue_script('twitter-search-widget', array('jquery'));
};</pre>
<p>With wp_register_script you assign a key to JavaScript file and specify the location of the file. The <em><strong>plugins_url</strong></em> retrieves the url to the plugins directory or to a specific file within that directory. You can hardcode the plugin slug in $path or pass<em><strong> __FILE__</strong></em> as a second argument to get the correct folder name.</p>
<p><em><strong>Wp_enqueue_script</strong></em> provides a safe way of adding JavaScript to a WordPress page. Basically, it includes the script if it hasn&#8217;t already been included, and load the one that WordPress ships. Note, the second argument that states that the twitter-search-widget JavaScript file is dependent on JQuery. This makes sure that the JQuery library is loaded before this JavaScript file.</p>
<h2>Registering CSS</h2>
<p>CSS is registered using the same method as with JavaScript. The functions for registering and queueing are called <em><strong>wp_register_style</strong></em> and <em><strong>wp_enqueue_style. </strong></em>Below the actual initialization script of the twitter widget is shown.</p>
<pre class="brush: php; title: ; notranslate">function initialize_script() {
  wp_register_script('twitter-search-widget',
    plugins_url('twitter-search-smooth-scrolling.js',__FILE__ ));
  wp_enqueue_script('twitter-search-widget', array('jquery'));

  wp_register_style('twitter-search-widget-style',
    plugins_url('twitter-search-smooth-scrolling.css',__FILE__ ));
  wp_enqueue_style('twitter-search-widget-style');
};</pre>
<h2>Directory organization</h2>
<p>WordPress stores all its plugins in the plug-in folder under wp-content. To be able to install your plugin you need to add the plugin file to the plugin directory. If you have more than one file it is better to create a folder with the same name as the widget and store all files in there.</p>
<h2>Source Code</h2>
<p>The source code of this plug-in is can be found on <a title="Twitter Smooth Scrolling plugin" href="http://wordpress.org/extend/plugins/twitter-search-smooth-scrolling/" target="_blank">WordPress.org</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.semanticarchitecture.net/writing-a-wordpress-twitter-widget/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Androng a pong clone for Android</title>
		<link>http://www.semanticarchitecture.net/androng-a-pong-clone-for-android/</link>
		<comments>http://www.semanticarchitecture.net/androng-a-pong-clone-for-android/#comments</comments>
		<pubDate>Mon, 30 Jan 2012 17:58:03 +0000</pubDate>
		<dc:creator>kalkie</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.semanticarchitecture.net/?p=263</guid>
		<description><![CDATA[This article describes how I developed and published Androng, a clone of the classic game Pong that runs on Android. I developed the game using Java and it supports a single and a two-player mode. Below are two in-game screenshots. Pong Pong is a game that was originally developed as a electronic version of ping [...]]]></description>
			<content:encoded><![CDATA[<p>This article describes how I developed and published Androng, a clone of the classic game Pong that runs on Android. I developed the game using Java and it supports a single and a two-player mode. Below are two in-game screenshots.</p>
<div>
<table style="border-collapse: collapse;" border="0">
<tbody>
<tr>
<td style="padding: 2px;"><img style="background-image: none; padding-left: 0px; padding-right: 0px; padding-top: 0px; border-width: 0px;" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Androng_Screenshot11.png" alt="" border="0" /></td>
<td style="padding: 2px;" align="center"><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Androng_Screenshot3_2.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="Androng_Screenshot3_2" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Androng_Screenshot3_2.png" alt="Androng_Screenshot3_2" border="0" /></a></td>
</tr>
</tbody>
</table>
</div>
<p><img title="Screenshot of the original version of Pong by Atari" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Original_Pong.png" alt="Screenshot of the original version of Pong by Atari" width="140" height="105" border="0" /></p>
<h1>Pong</h1>
<p>Pong is a game that was originally developed as a electronic version of ping pong. Atari originally created the game in 1972. The goal is to defeat your opponent by getting a higher score. In my implementation,whoever reaches 10 points first, wins the game.</p>
<h1><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Android_Logo.jpg"> <img title="Android_Logo" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Android_Logo.jpg" alt="Android_Logo" width="107" height="123" border="0" /></a>Android</h1>
<p>Android is an operating system for mobile devices based on the Linux 2.6 kernel. Android Inc developed Android and Google bought Android in 2005. Although it is an operating system for mobile devices, the operating system itself is big. It consists of more than 12 millions lines of code. Android supports a multitude of different mobile devices and a special version of Android (version 3.0 Honeycomb) will be available for tablet devices.</p>
<p>You can develop Android apps in <a title="Native development for Android" href="http://developer.android.com/sdk/ndk/index.html" target="_blank">C++</a> and <a title="Mono for Android" href="http://mono-android.net/" target="_blank">.Net</a> but most Android development is done in Java. The reason that I used Java is that it is close to C#, the language I use during my day job. To develop Java applications for Android you need the <a title="The Android SDK" href="http://developer.android.com/sdk/index.html" target="_blank">Android SDK</a>, the <a title="The Java development kit" href="http://www.oracle.com/technetwork/java/javase/downloads/index.html" target="_blank">Java SDK</a> and an Integrated Development Environment (IDE) such as <a title="Download Eclipse" href="http://www.eclipse.org/downloads/" target="_blank">Eclipse</a> or <a title="JAVA IDE" href="http://www.jetbrains.com/idea/download/" target="_blank">IntelliJ®</a>.</p>
<p>I used the community edition of IntelliJ®, which is free. This because during my day job I use Visual Studio® and <a title="Resharper" href="http://www.jetbrains.com/resharper/" target="_blank">Resharper</a>® which shares many similarities with IntelliJ®. Resharper® and IntelliJ® share a lot of  keyboard shortcuts, they are both developed by the company <a title="JetBrains" href="http://www.jetbrains.com/" target="_blank">JetBrains</a>® . Note, that although Java can be used for development not all Java libraries are available, only those supported by the Android runtime.</p>
<h1>Android Game development</h1>
<p>When you start developing games on Android, you have three possible graphics implementation. You can use the drawable package and use a <strong>view</strong> or a <strong>canvas. </strong>On the other hand, you can use the <a title="OpenGL ES" href="http://www.khronos.org/opengles/" target="_blank"><strong>OpenGL ES</strong></a><strong> API</strong> that is a special implementation of the <a title="Open Graphics Library" href="http://www.opengl.org/" target="_blank">OpenGL</a> specification for embedded devices. OpenGL ES includes support for 3D graphics. For Androng, I decided to use the graphics package and draw using a <strong>canvas</strong>. The canvas package is fast enough to support the animation and movement needed for this game.</p>
<h2>Activities</h2>
<p>An Android application revolves around Activities and Views. An activity is a part of the application that provides a screen to interact with. An application can consists of multiple activities. Android starts the activity specified in the manifest of an application. This manifest is important, it is a configuration file that specifies information the system needs before it can start your application. For example, which permissions are necessary for the application to run. When starting, Android calls the onCreate method of the specified activity. The source code below shows the main activity of Androng. All activities should derive from the Activity class.</p>
<pre class="brush: java; title: ; notranslate">public class AndrongActivity extends Activity
{
  private AndrongSurfaceView pongSurfaceView;

  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    pongSurfaceView = (AndrongSurfaceView) findViewById(R.id.androng);
    pongSurfaceView.setTextView((TextView) findViewById(R.id.text));
  }

....
}</pre>
<h2>Views</h2>
<p>A view creates the user interface of an activity and derives from the View class. A total view can consists of view groups and views. View groups are used to group views. They follow the composite design pattern. The user interface of an application can consist of multiple views, a so-called hierarchy of views. You can use code or a resource file to define the layout of a view. The flexibility of your user interface increases by using a resource layout file. It becomes easier to maintain and includes support for localisation. The layout resource file is implemented using XML. The resource file below shows the layout of Androng.</p>
<pre class="brush: xml; title: ; notranslate">&lt;!--?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?--&gt;&lt;/pre&gt;
&lt;pre id=&quot;pre1&quot; lang=&quot;xml&quot;&gt;&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;&gt;
    &lt;net.semantic.games.AndrongSurfaceView
      android:id=&quot;@+id/androng&quot;
      android:layout_width=&quot;match_parent&quot;
      android:layout_height=&quot;match_parent&quot;/&gt;
    &lt;RelativeLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot; &gt;
        &lt;TextView
          android:id=&quot;@+id/text&quot;
          android:text=&quot;Androng&quot;
          android:visibility=&quot;visible&quot;
          android:layout_width=&quot;wrap_content&quot;
          android:layout_height=&quot;wrap_content&quot;
          android:layout_centerInParent=&quot;true&quot;
          android:layout_alignParentBottom=&quot;true&quot;
          android:layout_marginBottom=&quot;10px&quot;
          android:gravity=&quot;center_horizontal&quot;
          android:textColor=&quot;#99FFFFFF&quot;
          android:textSize=&quot;16sp&quot;/&gt;
     &lt;/RelativeLayout&gt;
&lt;/FrameLayout&gt;
</pre>
<p>All layouts types are viewgroups and are used to create hierarchical models. Androng uses a FrameLayout which is the simplest layout object. A FrameLayout is a blank reserved space on the screen that can be filled with one object. All the child objects are pinned to the left top corner. It is not possible to specify a location for a child, each consecutive child is drawn over earlier objects which can obscure the previous one.</p>
<p><img class="aligncenter" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px; margin: 15px;" title="Visual representation of the Androng layout " src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Layout.png" alt="Visual representation of the Androng layout" width="214" height="266" align="left" /></p>
<p>In the case of Androng, the AndrongSurfaceView and the TextView are drawn on top of each other. Loading the XML in the user interface is done in the onCreate method of the activity <strong>setContentView(R.layout.main);</strong> where R.layout.main identifies the XML file in the resource.</p>
<p>Other layout types are possible. There is a <strong>LineairLayout</strong>, a <strong>RelativeLayout</strong>, a <strong>TableLayout </strong>and an <strong>AbsoluteLayout. </strong> Each of these layouts  have their own strength. I would not recommend using the AbsoluteLayout for your application because it may look good on your device but may well differ on another device.</p>
<p>We now have a user interface, lets see if we can draw resources to the screen.</p>
<h2></h2>
<h2></h2>
<h2></h2>
<h2></h2>
<h2></h2>
<h2>Drawing using Canvas</h2>
<p>Before you can draw a resource on to a canvas, you need to have a resource to draw and acquire a canvas to draw upon. The Canvas is acquired using a SurfaceView, this is a drawable surface that lies beneath the active view window. For Androng, I implemented a class named AndrongSurfaceView which extends SurfaceView, this is the same view as mentioned in the layout file. The source code below shows a part of the AndrongSurfaceView class.</p>
<pre class="brush: java; title: ; notranslate">
public class AndrongSurfaceView extends SurfaceView
  implements SurfaceHolder.Callback
{
  private AndrongThread androngThread;
  private TextView statusText;
  private SurfaceHolder holder;
  private Context context;

  public AndrongSurfaceView(Context context, AttributeSet attrs)
  {
    super(context, attrs);
    this.context = context;
    this.holder = getHolder();
    holder.addCallback(this);
    setFocusable(true);
  }
......
</pre>
<p>By calling a method lockCanvas on the SurfaceHolder we get an instance of the Canvas class which can be used to manipulate the pixels on a surface.</p>
<pre class="brush:java">Canvas canvas = surfaceHolder.lockCanvas(null);</pre>
<p>A resource can be obtained through the context of the application. For example, the following source code draws the background of the game each frame.</p>
<pre class="brush: java; title: ; notranslate">
Bitmap backgroundImage =
  BitmapFactory.decodeResource(resources, R.drawable.background2);
canvas.drawBitmap(backgroundImage, 0, 0, null);
</pre>
<h2>Frame speed independent animation</h2>
<p>Android runs on many devices, each with their own hardware specification. This means that the processing speed of the devices that run your application will be different. This in its turn means that the animation speed of a sprite, such as the ball of the Androng game differs per device. This is an unwanted situation, game play could differ per device. Therefore, we want to animate the game independently of the processing power of the device. We achieve this by incorporating time into the application and specify animation speed in pixel movement per time.</p>
<h3>Getting high-resolution timing from Android</h3>
<p>There 3 different ways to get time from the Android OS.</p>
<ol>
<li>currentTimeMillis()</li>
<li>upTimeMillis()</li>
<li>elapsedRealtime()</li>
</ol>
<p>The first is System.currentTimeMillis() which expresses the number of milliseconds since the epoch. Epoch on Unix based system is January 1, 1970. This obviously depends on the current time of the device, when the time switches due to the phone network or due to a user, this number can jump back or forth.</p>
<p>The second System.upTimeMillis is the number of milliseconds since the device was booted. This clock stops when the device goes into sleep mode, but isn’t affected by time shifts.</p>
<p>The third and last option is elapsedRealtime(), this is also the number of milliseconds since the device booted. The difference with the second option is that this keeps running when the device goes into sleep mode.</p>
<p>For our frame speed independent animation I choose upTimeMillis because the first option may jump forward or backward which is not good for calculating the frame speed and the third option keeps running while the game is paused which is also troubling for calculating the frame speed. The following code calculates the number of frames per second using the second option.</p>
<pre class="brush: java; title: ; notranslate">
while (isRunning)
{
  currentTimeInMillis = System.upTimeMillis();
  double timeNeededToDrawFrame = (currentTimeInMillis – previousTimeInMillis) / 1000;
  previousTimeInMillis = currentTimeInMillis;
  DrawFrame(time);
  UpdatePhysics(timeNeededToDrawFrame);
}
</pre>
<p>The variable timeNeededToDrawFrame is send to all the objects that make up the game screen. For example, the Ball receives this and has a speed of 2 horizontal pixels per second. By multiplying this with the time needed to draw this frame we get the number of pixels that the ball should move. The same is done with the vertical speed. This enables frame speed independent animation.</p>
<h1><span style="font-size: 20px;">Collision Detection</span></h1>
<p>Most, if not all games need collision detection. There are many ways of detecting if two game objects collide. Androng combines both the bounding box and pixel methods. The bounding box method can be easily illustrated with the following picture.</p>
<h3><img src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Bounding_Box_Hit_Detection.png" alt="" /></h3>
<p>The following algorithm detects if the virtual boxes around each sprite overlaps with the other.</p>
<pre class="brush: java; title: ; notranslate">
if (bottom1 &lt; top2)   return false; if (top1 &gt; bottom2)
  return false;
if (right1 &lt; left2)   return false; if (left1 &gt; right2)
  return false;

//bounding box do overlap
</pre>
<p>The bounding box collision detection algorithm is a fast way to detect a collision, but if the shapes are not rectangular such as the ball we could get false positives. For example, in the following situation the bounding box detection would detect a collision while in fact there isn’t one.</p>
<p><img src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Bounding_Box_Hit_Detection_False_Positive.png" alt="" /></p>
<h3>Pixel Perfect Detection</h3>
<p>We could solve this by using a bounding circle for the ball, but I wanted to solve this using a more generic approach, using the pixels of the sprite. Therefore, when the bounding box algorithm detects a collision we scan the overlap in both sprites for pixels. If the same location in both sprites contains a pixel (color != 0) we have a collision.</p>
<p><img src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Pixel-Detection.png" alt="" width="473" height="307" /></p>
<p>The algorithm determines the width and height of the overlapping box and where in each sprite the box is. The algorithm scans each pixel in the box for a collision. Reading the pixel from the bitmap is possible by calling the getBitmap() method on the Drawable. See the method CollidesWith of the sprite class in the source code for the full collision detection routine.</p>
<h2>Sound Management</h2>
<p>Androng plays a sound whenever the ball collides with a paddle, the wall or when a player scores. Playing a sound using Android is easy. The media player or Sound Pool classes can play sounds. I used the Sound Pool classes because they offer more flexibility. Playing sounds using the Sound Pool classes use the AudioManager,  the AudioManager is a so called Android system service. Below the source code is shown to get the AudioManager system service and to play the media file “hit”. Hit is played when the ball hits a paddle or the side.</p>
<pre class="brush: java; title: ; notranslate">
AudioManager mAudioManager =
  (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
SoundPool mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
mSoundPool.play(R.raw.hit, streamVolume, streamVolume, 1, 0, 1);
</pre>
<p>All the sounds of the game are pre-loaded into a SoundPoolMap and are played from this SoundPoolMap. All sound management methods are grouped into a single class SoundManager, see the sourcecode for the class. The class is based on an example provided by <a title="Android Development Blog" href="http://www.droidnova.com/creating-sound-effects-in-android-part-1,570.html" target="_blank">Stephen Flockton</a>, who writes a blog around Android development. Score State Management</p>
<h2>Input Management</h2>
<p>The game can be controlled using the touch screen of an Android device, this is called the Touch mode. The touch mode is activated if you touch a button on the screen with your finger. Handling touch mode events is as simple as overriding the onTochEvent of the SurfaceView.  Below the signature of the onTouchEvent is shown.</p>
<pre class="brush:java">public boolean onTouchEvent(MotionEvent event)</pre>
<p>This event gets thrown when you touch the screen with one or more fingers. The MotionEvent argument has a method called getPointerCount(), this method returns the number of fingers that are placed on the screen. Although this actually depends on the capability of the device and the version of Android. Androng has a two player mode where two players can play against each other using there fingers on the same device. In this mode the getPointerCount() method is used. If there are two fingers touching the screen of the device, the index = 0 represents the first finger,  while index = 1 represents the second finger. Using the index in the method getX or getY on the event the position of the fingers can be determined.</p>
<pre class="brush:java">float xPosition1 = event.getX(pointerIndex);
float yPosition1 = event.getY(pointerIndex);</pre>
<p>The xPosition1 and yPosition1 are used to place the paddle on the screen.</p>
<h2>Notifications</h2>
<p>Androng uses Toast notifications to tell the user about certain events such as how to start the game and which player has won the game. A toast notification is a message that pops up on the surface of the window. The message automatically fades in and out and stays on the screen for a predetermined amount of time. The following code places a toast notification on the Androng game screen.</p>
<p><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Toast.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="Toast" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Toast.png" alt="Toast" border="0" /></a></p>
<pre class="brush: java; title: ; notranslate">
Toast toast =
  Toast.makeText(context, &quot;Select Menu for a new game.&quot;, Toast.LENGTH_LONG);
toast.show();
</pre>
<p>The constant Toast.LENGTH_LONG according to the Android documentation will say to Android that the text notification should be shown for a long period. Default, Toast.LENGHT_LONG corresponds to 3.5s. Show() will actually show the text on the screen.</p>
<h1>Application Life-Cycle Management</h1>
<p>As Android is an operating system for mobile devices, it needs special attention for managing the scares resources of such a device. Each Android application runs in its own process and is able to perform a specific task. A task can consists of multiple activities. Each Android application should manage the Application Lifecycle. For example, it is possible that the Android OS decides to suspend or destroy your application when it needs extra resources. Therefore, your application should be able save and restore its state when this is needed.</p>
<h2>Activity Life-Cycle</h2>
<p>As mentioned before, an Android application consists of activities, it is in these activities you should manage your applications lifecycle. There are three possible scenarios possible for starting or restarting your application.</p>
<table style="border-collapse: collapse;" border="1">
<thead>
<tr>
<td>Fresh Start</td>
<td>Fresh Restart</td>
<td>Restart From Pause</td>
</tr>
</thead>
<tbody>
<tr>
<td><code>onCreate</code></td>
<td><code>onRestart</code></td>
<td></td>
</tr>
<tr>
<td><code>onStart</code></td>
<td><code>onStart</code></td>
<td></td>
</tr>
<tr>
<td><code>onResume</code></td>
<td><code>onResume</code></td>
<td><code>onResume</code></td>
</tr>
</tbody>
</table>
<p>All these “on*” methods are part of an activity. The fresh start scenario happens when you normally start your application. The Fresh restart scenario happens after Android has stopped your activity, just before it starts again. The last scenario Restart from pause, happens when the system is about to start resuming a previous activity. When an other application gets to the foreground your activity gets paused. <a title="Activity Lifecycle" href="http://developer.android.com/reference/android/app/Activity.html" target="_blank">This</a> show a total graphical overview of the application life-cycle.</p>
<p>Note, that also when you change the orientation of an Android device, your application gets restarted</p>
<h2>Restart Thread</h2>
<p>Drawing of the game screen and physics calculation runs on a separate thread.</p>
<pre class="brush: java; title: ; notranslate">
While (isRunning)
{
  .....
}
</pre>
<p>The thread runs continuously in a loop guarded by a single Boolean isRunning. When the program stops the isRunning Boolean gets set to false and the thread stops running. In the method surfaceDestroyed that gets called by the Android OS, I waited using a Join statement.</p>
<pre class="brush: java; title: ; notranslate">
public void surfaceDestroyed(SurfaceHolder surfaceHolder)
{
  androngThread.setRunning(false);
  boolean retry = true;
  while (retry)
  {
    try
    {
      androngThread.join();
      retry = false;
    }
    catch (InterruptedException e)
    {
    }
  }
}
</pre>
<p>The method sets the boolean isRunning to false using the setRunning method, this stops the thread from running. Next, the code calls androngThread.join() which according to the documentation blocks the current thread until the receiver finishes its execution and dies.</p>
<p>Exactly the behavior I was looking for. However, during a restart or resume of the application I got the error <em>“Thread already started”</em> while trying to (re)start the thread.  It seems that the join statement succeeded but did not stopped the thread. There are other methods available on the thread class such as stop() and destroy() but according to the documentation they are all deprecated and shouldn’t be used. I decided to solve this problem while creating the thread.</p>
<p>The code below shows my solution, I do not find it an elegant one but it works.</p>
<pre class="brush: java; title: ; notranslate">
public void surfaceCreated(SurfaceHolder surfaceHolder)
{
  androngThread.setRunning(true);
  try
  {
    androngThread.start();
  }
  catch (Exception error)
  {
    androngThread = CreateNewAndrongThread();
    androngThread.start();
    androngThread.setRunning(true);
  }
}
</pre>
<p>The method tries to start the thread, when it fails, the exception handler creates a new thread and starts the newly created thread.</p>
<h1>Android Market</h1>
<p>I wanted to publish Androng on Android Market. Android Market is an open distribution platform for Android applications. Open means that your applications are not policed and there is no approval process. The visibility of your application depends on the rating you get from customers. Android market is not the only distribution platform for Android applications, another publication channel is Amazon. Currently, this is only open to customers from the United States.</p>
<p>There is a one time $25 registration fee before you can publish your games on Android Market. Besides that, for every app sold on Android Market, Google receives a 30% fee. Which to my opinion is reasonable compared with other publication channel.  Androng is free and can be downloaded from Android market.</p>
<p><img src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Publish-Android-Market.png" alt="" /></p>
<p>The community edition of IntelliJ gives you the opportunity to package the application. Before you publish your application, you must sign the application using a public private key combination. Updates of the application must use the same key for signing.  This package with .apk extension can be published on Android market. You have to fill in some fields before publishing such as a description and some screenshots, logo’s etc. If you have an Android phone you can download the game <a title="Androng market download link" href="https://market.android.com/details?id=net.semantic.games&amp;feature=search_result" target="_blank">here via Android market</a>. The nice thing about Android market is that you get insight into the users of your application. It shows if the users got any errors, which Android versions they use and the type of devices they have. For example, the screenshot below shows the type of devices that downloaded Androng.</p>
<p><img style="display: inline;" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Insight_Phones.png" alt="" /></p>
<h2>Source Code</h2>
<p>The source code of Androng can be found at <a href="http://www.codeproject.com/KB/android/Androng.aspx">CodeProject</a>. if you use the community edition of IntelliJ, you can open the project file. Otherwise, you can open the individual source or java files.</p>
<h2>Next version</h2>
<p>For the next version of Androng, I have the following features planned, in no particular order.</p>
<ul>
<li>Usage of a real physics engine such as <a title="Open source physics engine" href="http://www.box2d.org/" target="_blank">Box2d</a> or <a title="Android Physics Engine" href="http://www.andengine.org" target="_blank">AndEngine</a></li>
<li>High score list, with central storage on the web</li>
<li>Usage of Google Juice for dependency injection</li>
<li>Better graphics</li>
<li>Increased freedom of movement of the bats</li>
<li>Support for Android version 1.6</li>
<li>Promotion video</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.semanticarchitecture.net/androng-a-pong-clone-for-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PDF reporting using ASP.NET MVC</title>
		<link>http://www.semanticarchitecture.net/pdf-reporting-using-asp-net-mvc/</link>
		<comments>http://www.semanticarchitecture.net/pdf-reporting-using-asp-net-mvc/#comments</comments>
		<pubDate>Sat, 28 Jan 2012 09:17:31 +0000</pubDate>
		<dc:creator>kalkie</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://www.semanticarchitecture.net/?p=26</guid>
		<description><![CDATA[Almost every web application, needs a reporting option. Many times the client wants to generate a PDF report that corresponds with the web page he or she is viewing. Using iTextSharp, a free C# PDF library this is possible. This article describes and includes a solution for creating reports using iTextSharp and ASP.NET MVC3. Background [...]]]></description>
			<content:encoded><![CDATA[<p>Almost every web application, needs a reporting option. Many times the client wants to generate a PDF report that corresponds with the web page he or she is viewing. Using <a href="http://sourceforge.net/projects/itextsharp/">iTextSharp</a>, a free C# PDF library this is possible. This article describes and includes a solution for creating reports using <a href="http://sourceforge.net/projects/itextsharp/">iTextSharp</a> and ASP.NET MVC3.</p>
<h2><a name="Background1"></a>Background</h2>
<p><a href="http://sourceforge.net/projects/itextsharp/">iTextSharp</a> is a free C# PDF library that is ported from the Java-PDF Library <a href="http://itextpdf.com/">iText</a>. <a href="http://itextpdf.com/">iText</a> was launched in 2000 and is a popular open source Java library for programmatic creation and manipulation of PDF. As with many successful open-source Java libraries it was ported to C# under the name iTextSharp. iTextSharp has been under development since 2008 and is distributed under the <a href="http://www.gnu.org/licenses/agpl.html">GNU Affero General Public License version 3.</a></p>
<p>At its core <a href="http://sourceforge.net/projects/itextsharp/">iTextSharp</a> is an api to manipulate PDF creation. For a recent project I was looking for a solution that would enable me to create PDF documents from existing HTML documents or Views used in an ASP.NET MVC3 project. The ideal solution for me would be to throw an existing ASP.NET MVC3 view at it and let it generate a PDF that is exactly the same as the HTML rendered by a browser.</p>
<p>The solution described here uses the <code>HTMLWorker</code> class from <a href="http://sourceforge.net/projects/itextsharp/">iTextSharp</a> to generate a PDF from an HTML view. HTMLWorker is a <a href="http://sourceforge.net/projects/itextsharp/">iTextSharp</a> class that is able to parse an HTML document and generate a PDF using the what is called the <code>SimpleParser</code> of <a href="http://sourceforge.net/projects/itextsharp/">iTextSharp</a>. Notice the name <code>SimpleParser</code> which indicates that not all HTML elements and css styles are supported. However, I was able to get good results using this solution.</p>
<p>To add reporting to your ASP.NET MVC3 project, first add the PDFReportGenerator project to your solution and add the iTextSharp.dll binary to your solution. PDFReportGenerator needs a reference to the binary. By adding the binary to the solution you are able to build the project directly from source control. Check the demo src for an example.</p>
<h2><a name="Creatingareport.2"></a>Creating a report.</h2>
<p>Follow the following steps to generate an actual report from your web application.</p>
<ol>
<li>Create a controller that derives from PdfViewController.</li>
<li>Create a view that generates the HTML which should be translated to a PDF report.</li>
<li>Create an action on a controller which calls the ViewPDF method on the PdfViewController.</li>
<li>Create a link to trigger the action on the controller.</li>
</ol>
<p>The following paragraph describes these steps in more detail.</p>
<h3>Create a controller that derives from <i>PdfViewController</i></h3>
<p>Create a new or reuse an existing Controller and let it derive from <code>PdfViewController</code> from the PdfReportGenerator project.</p>
<p>This enables your controller to call the ViewPDF method of the <code>PDFViewController</code> which generates the real PDF. In the demo project this is the <code>HomeController</code>.</p>
<h3><a name="CreateaviewthatgeneratestheHTML4"></a>Create a view that generates the HTML</h3>
<p>Create a View that should be translated to a report. This could be an existing view or a new view specially for reporting. I usually create a new view as it lets me control the HTML markup for the report. As stated earlier the report generator does not support all the HTML markup. In the demo project this is the <code>PrintDemo</code> view.</p>
<p>Below the PrintDemo view from the demo project is shown. This is just a simple ASP.NET Razor view with a table and some rows. It uses a strongly typed model but that it not necessary. A <strong>tip</strong> when trying to design your report is to add borders to your <code>table</code> or <code>div</code>. Using these borders when looking at the generated PDF you can clearly see the start and end of the areas of your report.</p>
<pre class="brush: csharp; title: ; notranslate">@using MvcReportGeneratorDemo.Models
@model CustomerList
&lt;br /&gt;
&lt;table cellpadding=&quot;3&quot; cellspacing=&quot;3&quot;&gt;
    &lt;tr border=&quot;1&quot; bgcolor=&quot;#777777&quot; color=&quot;#ffffff&quot;&gt;
        &lt;td&gt;Name&lt;/td&gt;
        &lt;td&gt;Address&lt;/td&gt;
        &lt;td&gt;Place&lt;/td&gt;
    &lt;/tr&gt;
    @foreach (Customer customer in Model)
    {
        &lt;tr border=&quot;1&quot;&gt;
            &lt;td&gt;@customer.Name&lt;/td&gt;
            &lt;td&gt;@customer.Address&lt;/td&gt;
            &lt;td&gt;@customer.Place&lt;/td&gt;
        &lt;/tr&gt;
    }
&lt;/table&gt;</pre>
<p>Create an action which calls the ViewPDF method</p>
<p>The PdfViewController class from which your controller derives, contains a ViewPDF method. This method has the following signature.</p>
<pre class="brush: csharp; title: ; notranslate">protected ActionResult ViewPdf(string pageTitle,
            string viewName, object model)</pre>
<h4><a name="Parameters6"></a>Parameters</h4>
<dl>
<dt>pageTitle</dt>
<dd>Type: System.StringThe title of the report which appears on the header of the page.</dd>
</dl>
<dl>
<dt>viewName</dt>
<dd>Type: System.StringThe name of the view which should be converterd to a report.</dd>
</dl>
<dl>
<dt>model</dt>
<dd>Type: System.Object</dd>
</dl>
<p>The model that is rendered by the view.</p>
<p>This methods generates the HTML view and converts into a PDF report and sends this PDF as a binary stream back to the client. This means that when the client has a PDF plugin installed, the PDF is shown inside the browser.</p>
<p>From an action inside your controller this method should be called to generate the report and send it to the cliënt. The following action from the Demo application generates the PDF. &#8220;Customer report&#8221; is the title of the report, &#8220;PrintDemo is the name of the view and the model is returned by the <code>CreateCustomerList()</code> which as its name implies generates a dummy list with customers.</p>
<pre class="brush: csharp; title: ; notranslate">public ActionResult PrintCustomers()
{
   return this.ViewPdf(&quot;Customer report&quot;,
        &quot;PrintDemo&quot;, CreateCustomerList());
}</pre>
<p>The last step is to create a link on a page that calls this action to actually print the report.</p>
<h3>Trigger the action on the controller</h3>
<p>A simple method to create a link to trigger the action on the controller is by using an <i>ActionLink</i>. This link calls the action that we defined on the controller.</p>
<pre class="brush: csharp; title: ; notranslate">@Html.ActionLink(&quot;Print customers&quot;,
      &quot;PrintCustomers&quot;, null,
      new { target = &quot;_blank&quot; })</pre>
<p>These are the steps you need to create PDF reports from your ASP.NET MVC3 projects.</p>
<p>Read the next part of the article if you are interested how into the details of how the PdfReportGenerator actually converts the ASP.NET MVC3 view into a report.</p>
<h2>Detailed Reporting Project Overview</h2>
<p>The <i>PdfReportGenerator</i> project consist of 6 classes which can be seen in the image below. The PdfReportGenerator assembly works by rendering the ASP.NET MVC3 view into a string and converting this string with HTML using the iTextSharp into a PDF report.</p>
<p><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/ASP_MVC3_PDF_Reporting.png"><img class="alignnone  wp-image-28" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="ASP_MVC3_PDF_Reporting" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/ASP_MVC3_PDF_Reporting.png" alt="Class model used for PDF reporting" /></a></p>
<h3><a name="RenderinganASP.NETMVC3viewintoastring9"></a>Rendering an ASP.NET MVC3 view into a string</h3>
<p>The class <code>HtmlViewRenderer</code> is responsible for rendering the ASP.NET view into a string. The method RenderViewToString has the following signature.</p>
<pre class="brush: csharp; title: ; notranslate">public string RenderViewToString(Controller controller,
      string viewName, object viewData)</pre>
<p>The arguments are <code>viewName</code> which is the name of the view that should get rendered to a <code>string</code> including the model <code>viewData</code> that is needed by the view. The controller is necessary</p>
<p>to be able to use to render the view using the view engine of ASP.NET MVC.</p>
<h3><a name="ConvertthehtmlstringintoaPDFbytearray10"></a>Convert the html string into a PDF byte array</h3>
<p>Once we have the html in a string the <code>StandardPdfRenderer</code> converts the html string into a PDF byte array. The class <code>StandardPdfRenderer</code> has a method <code>Render</code> with the following signature.</p>
<pre class="brush: csharp; title: ; notranslate">public byte[] Render(string htmlText, string reportTitle)</pre>
<p>The <code>htmlText</code> is the rendered view as a string that was produced by the <code>HtmlViewRender</code>, the <code>pageTitle</code> is as the name suggests the title of the report.</p>
<h3><a name="Sendthebytearraybacktotheclientasastream11"></a>Send the byte array back to the client as a stream</h3>
<p>The last step is to convert the byte array into an instance of the <code>BinaryContentResult</code> class. The class <code>BinaryContentResult</code> derives from the ASP.NET MVC <code>ActionResult</code>. It overrides the ExecuteResult and returns the content as a binary stream.</p>
<p>The class <code>PdfViewController</code> is the class that combines these classes. The method <code>ViewPdf</code> uses all the three previously mentioned classes to generate the PDF as shown in the code below</p>
<pre class="brush: csharp; title: ; notranslate">protected ActionResult ViewPdf(string pageTitle,
                    string viewName, object model)
{
 // Render the view html to a string.
 string htmlText =
       this.htmlViewRenderer.RenderViewToString(this,
           viewName, model);
 // Let the html be rendered into a PDF document
 // through iTextSharp.
 byte[] buffer = standardPdfRenderer.Render(htmlText,
           pageTitle);
 // Return the PDF as a binary stream to the client.
 return new BinaryContentResult(buffer,
           &quot;application/pdf&quot;);
}</pre>
<h2><a name="PointsofInterest12"></a>Points of Interest</h2>
<p><b>Colors</b><br />
iTextsharp supports color out of the box, in the demo application the background colors of the rows are alternated using different colors. These colors are visible in the report.</p>
<p><b>New page support</b><br />
One thing that I needed with my project that was not supported by the HTML conversion in iTextSharp was functionality to force a page break.Most of the time with reporting you need to be able to force a page break, for example if you want a graph to start always on a new page. The way I solved this was to add support for it to iTextSharp.</p>
<p>As it is open-source you are able to add new features to it. I added support for a non existing HTML tag called <code>&lt;np /&gt; </code> which forces iTextSharp to create a new page. I created a patch so that it could be committed to the <a href="http://sourceforge.net/tracker/?func=detail&amp;aid=3396638&amp;group_id=72954&amp;atid=536238">iTextSharp project</a>. I do not know if it will be included in the main trunk of the project as it feels somewhat strange to invent new html tags just to support a page break. But if you need it, you can use the patch to compile iTextSharp with new page support.</p>
<p><b>Images</b><br />
It is possible to add images to the report by using an <code>&lt;img src="" /&gt;</code> tag. I had no success with dynamically generated images. So therefore, I generated the images that I needed before the action conversion process took place.</p>
<p><b>ASP.Net Support</b><br />
It should be possible to use the same kind of solution using older versions of ASP.NET MVC. However, I have not tried it.</p>
<p><b>Other Options</b><br />
After I wrote this post several people mentioned other alternatives for generating PDF reports using ASP.NET MVC. Michael Johnson wrote a <a title="Generate PDF using WKHtmlToPDF" href="http://subvert.ca/Blog/wkhtmltopdf-in-MVC3">blog post</a> about using WkHtmlToPDF and someone mentioned using <a title="Generate PDF using flying saucer" href="http://xhtmlrenderer.java.net/">Flying Saucer</a> for generating PDF&#8217;s.</p>
<p>The source code of the solution can be found on <a href="http://www.codeproject.com/KB/aspnet/ASP_MVC_Reporting.aspx">CodeProject</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.semanticarchitecture.net/pdf-reporting-using-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Digest Authentication on a WCF REST Service</title>
		<link>http://www.semanticarchitecture.net/digest-authentication-on-a-wcf-rest-service/</link>
		<comments>http://www.semanticarchitecture.net/digest-authentication-on-a-wcf-rest-service/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 21:05:18 +0000</pubDate>
		<dc:creator>kalkie</dc:creator>
				<category><![CDATA[Software Architecture]]></category>

		<guid isPermaLink="false">http://www.semanticarchitecture.net/?p=158</guid>
		<description><![CDATA[This article explains a different authentication mechanism called Digest Authentication which provides an alternative. This security mechanism is more secure than Basic Authentication and does not have the drawbacks from using a https tunnel.]]></description>
			<content:encoded><![CDATA[<p>This is a follow-up on <a title="Basic Authentication on a WCF REST service" href="http://www.semanticarchitecture.net/basic-authentication-on-wcf-rest/" target="_blank">my earlier article</a> that described how to use BASIC Authentication with a WCF REST Service. The disadvantage of <a title="Basic Authentication on a WCF REST Service" href="http://www.semanticarchitecture.net/basic-authentication-on-wcf-rest/" target="_blank">that solution</a> was that you need a https tunnel to really secure the username password verification process. Although possible, this is not always a feasible situation, for example, if you don&#8217;t want to invest in certificates or loose performance when using a https tunnel.</p>
<p>This article explains a different authentication mechanism called Digest Authentication which provides an alternative. This security mechanism is more secure than Basic Authentication and does not have the drawbacks from using a https tunnel.</p>
<p>Digest Authentication is available on multiple web servers and supported by multiple internet browsers. The drawback when using Digest Authentication with Internet Information server is that it automatically authenticates credentials against active directory. This article describes an implementation which enables you to secure a WCF REST service with Digest Authentication and authenticate against any back-end.</p>
<p>Digest Authentication was first described in <a title="An Extension to HTTP : Digest Access Authentication" href="http://www.ietf.org/rfc/rfc2069.txt" target="_blank">RFC 2069</a> as an extension to HTTP Basic Authentication. Later, the verification algorithm and security was improved by <a title="HTTP Authentication: Basic and Digest Access Authentication" href="http://www.ietf.org/rfc/rfc2617.txt" target="_blank">RFC 2617</a>. This is the current stable specification. The implementation in this article is based on that <a title="HTTP Authentication: Basic and Digest Access Authentication" href="http://www.ietf.org/rfc/rfc2617.txt" target="_blank">RFC 2617</a> specification. Digest Authentication is more secure because it uses <a title="MD5 cryptographic hashing" href="http://en.wikipedia.org/wiki/MD5" target="_blank">MD5 cryptographic hashing</a> and the use of a nonce to discourage cryptanalysis.</p>
<h2><a name="OverviewofDigestCommunication1"></a>Overview of Digest Communication</h2>
<p>Digest communication starts with a client that requests a resource from a web server. If the resource is secured with Digest Authentication, the server will respond with the http status code 401, which means Unauthorized.</p>
<p><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Digest-Authentication-Communication.png"><img class="wp-image-182 aligncenter" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="Digest-Authentication-Communication" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Digest-Authentication-Communication.png" alt="" width="500" height="300" /></a></p>
<p>In the same response, the server indicates in the HTTP header with which mechanism the resource is secured. The HTTP header contains the following <strong>&#8220;WWW-Authenticate: Digest realm=&#8221;realm&#8221;, nonce=&#8221;IVjZjc3Yg==&#8221;, qop=&#8221;auth&#8221;</strong>. The first thing you should notice is the string <strong>Digest</strong> in the response, here the server indicates that the resource that was requested by the client is secured using Digest Authentication. Secondly, the server indicates the type of Digest Authentication algorithm to use by the client with <strong>Quality Of Protection (QOP)</strong> and the string called nonce which I will explain later in this article.</p>
<p>An internet browser responds to this by presenting the user a dialog, in this dialog the user is able to enter his username and password. Note, that this dialog does not show the warning about transmitting the credentials in clear text as with a Basic Authentication secured site.</p>
<p><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Digest-Authentication-Credentials-Screen.png"><img class="aligncenter" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="Digest-Authentication-Credentials-Screen" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Digest-Authentication-Credentials-Screen.png" alt="" width="450" height="265" /></a></p>
<p>When the user enters the credentials in this dialog, the browser requests the resource from the server again. This time, the client adds additional information to the HTTP header regarding Digest Authentication.</p>
<p><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Digest-Authentication-Second1.png"><img class="alignnone size-full wp-image-191" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="Digest-Authentication-Second1" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Digest-Authentication-Second1.png" alt="" width="500" height="391" /></a></p>
<p>The server validates the information and returns the requested resource to the client. The details of the response from the server and the additional request of the client will be described in the following part of this article.</p>
<h2><a name="DigestAuthentication2"></a>Digest Authentication</h2>
<p>When the server responds to an unauthenticated client request, the server adds a nonce and a qop key to the header of the HTTP response. Both are typical for Digest Authentication. First, the nonce will be described and second the QOP quality of protection.</p>
<h3><a name="TheNonce3"></a>The Nonce</h3>
<p>The Nonce stands for &#8220;Number used Once&#8221;, this is a pseudo random number that ensures that old communications between a client and a server cannot be reused in replay attacks. A replay attack is a network attack in which previous valid data transmission is repeated. This is done by an adversary who intercepts the data and retransmit it. According to the RFC 2716 specification, the Nonce is a server specified data string which should be uniquely generated each time a 401 response is returned by the server. The 401 response that is sent back to the client includes the Nonce generated by the server. According to RFC 2716, the client should add this nonce to the header of next requests.</p>
<h3><a name="GeneratingtheNonce4"></a>Generating the Nonce</h3>
<p>The format of the nonce depends on the implementation. Each RFC 2617 digest authentication implementation may define their own nonce format. However, one should carefully design the format of the nonce as it is a part of the quality of the security. For my implementation, I choose to include a date time stamp and the IP address of the client into the nonce. The implementation generates the nonce as follows.</p>
<pre class="brush: csharp; title: ; notranslate">
Nonce = Base64( TimeStamp : PrivateHash)
</pre>
<p>The nonce is generated by <a title="Base64 encoding" href="http://en.wikipedia.org/wiki/Base64" target="_blank">base64</a> encoding the <em>string </em>that is constructed by concatenating the time stamp, a colon and a generated private hash. In the source code, this is handled by the <em>NonceGenerator </em>class which has a <em>Generate </em>method that generates the <em>Nonce string</em>.</p>
<pre class="brush: csharp; title: ; notranslate">public string Generate(string ipAddress)
{
   double dateTimeInMilliSeconds =
      (DateTime.UtcNow - DateTime.MinValue).TotalMilliseconds;

   string dateTimeInMilliSecondsString =
      dateTimeInMilliSeconds.ToString();

   string privateHash = privateHashEncoder.Encode(
      dateTimeInMilliSecondsString,
      ipAddress);

   string stringToBase64Encode =
      string.Format(&quot;{0}:{1}&quot;, dateTimeInMilliSecondsString,
       privateHash);

   return base64Converter.Encode(stringToBase64Encode);
}</pre>
<p>MD5 is used to generate the private hash of the <em>string </em>that is constructed by concatenating the time stamp, a colon, the IP address of the client, a colon and a private key that is only known to the server. As MD5 is used, the generation is one-way. It is not possible to reconstruct this information from the private hash.</p>
<pre class="brush: csharp; title: ; notranslate">PrivateHash = MD5Hash( TimeStamp : IP Address : Private key)</pre>
<p>In the source code, generating the private hash is handled by the method <em>Encode </em>in the <em>PrivateHashEncoder </em>class. It uses the <em>MD5Encoder </em>class to actually generate the MD5 hash.</p>
<pre class="brush: csharp; title: ; notranslate">public string Encode(string dateTimeInMilliSecondsString,
    string ipAddress)
{
  string stringToEncode = string.Format(
     &quot;{0}:{1}:{2}&quot;,
     dateTimeInMilliSecondsString,
     ipAddress,
     privateKey);

  return md5Encoder.Encode(stringToEncode);
}</pre>
<h3><a name="ValidatingtheNonce5"></a>Validating the Nonce</h3>
<p>Every time the client sends the nonce to the server, the server validates if this is the nonce that the server sends to the client. The server validates the nonce in two steps:</p>
<p>The first thing that this implementation on the server does is validate if this <em>PrivateHash </em>was generated by this server and returned to this client. The server does this by generating the <em>PrivateHash </em>with the time stamp that is available in the Nonce and the IP address of the client. If this does not deliver the same <em>PrivateHash </em>as in the nonce from the client, the nonce is incorrect and the server responds with a 401. The <em>NonceValidator </em>is responsible in the source code for validating this nonce.</p>
<pre class="brush: csharp; title: ; notranslate">public virtual bool Validate(string nonce,
   string ipAddress)
{
   string[] decodedParts = GetDecodedParts(nonce);
   string md5EncodedString = privateHashEncoder.Encode(
      decodedParts[0],
      ipAddress);

   return string.CompareOrdinal(
      decodedParts[1],
      md5EncodedString) == 0;
}</pre>
<p>Secondly, the server checks if the Time Stamp is too old. The server holds a certain time-out for a nonce. For example, the time-out is 300 seconds. The server validates if the time stamp in the nonce is not older than 300 seconds. If the nonce is older than 300 seconds, the server returns an indication in the HTTP header that the received nonce is too old together with a new nonce. RFC 2617 uses a special key called <strong>Stale</strong> in the header that is sets to <em>true </em>when the Nonce is too old. The <em>NonceValidator </em>is also responsible for checking if the time stamp is too old.</p>
<pre class="brush: csharp; title: ; notranslate">public virtual bool IsStale(string nonce)
{
   string[] decodedParts = GetDecodedParts(nonce);

   DateTime dateTimeFromNonce =
     nonceTimeStampParser.Parse(decodedParts[0]);

   return dateTimeFromNonce.AddSeconds(
      staleTimeOutInSeconds) &lt; DateTime.UtcNow;
}</pre>
<p>By using a time stamp and the IP address in the nonce, we make sure that the request is recent and comes from the client that requested the resource.</p>
<h3><a name="QualityOfProtection6"></a>Quality Of Protection</h3>
<p>Digest Authentication allows the server to ask which algorithm the client should use to encrypt the credentials of the user. Digest Authentication allows the following Quality Of Protection.</p>
<ul>
<li><strong>none</strong> = Default protection compatible with <a title="An Extension to HTTP : Digest Access Authentication" href="http://www.ietf.org/rfc/rfc2069.txt" target="_blank">RFC 2069</a></li>
<li><strong>auth</strong> = Increased protection that includes a client nonce and a client nonce counter</li>
<li><strong>auth-int</strong> = Increased protection and integrity that included all of auth and a hash of the contents of the body</li>
</ul>
<p>Note that it is a request from the server, the client itself is allowed to choose a lesser secure qop algorithm. If the server requests for <em>auth</em>, it is ok for the client to start communicating with the default or none qop.</p>
<p>The implementation with this article supports both <strong>default/none</strong> and auth. The class <em>DefaultDigestEncoder </em>and the class <em>AuthDigestEncoder </em>implement the default and the auth type of quality of protection. Both classes derive from <em>DigestEncodeBase </em>which holds common functionality.</p>
<p><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/DigestEncoder.png"><img class="alignnone size-full wp-image-193" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="DigestEncoder" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/DigestEncoder.png" alt="" width="427" height="444" /></a></p>
<p>At runtime, the server instantiates both types of encoders and stores them in a dictionary with the qop algorithm as the key. This enables the server to easily switch between different types of encoders at runtime.</p>
<pre class="brush: csharp; title: ; notranslate">internal class DigestEncoders :
   Dictionary
{
 public DigestEncoders(MD5Encoder md5Encoder)
 {
  Add(DigestQop.None, new DefaultDigestEncoder(md5Encoder));
  Add(DigestQop.Auth, new AuthDigestEncoder(md5Encoder));
 }

 public virtual DigestEncoderBase GetEncoder(
    DigestQop digestQop)
 {
  return this[digestQop];
 }
}</pre>
<h3><a name="NoneordefaultQOP7"></a>None or Default QOP</h3>
<p>When an internet browser receives 401 HTTP status code with Digest in the authentication header, it will show a dialog for entering the username and password. When the client uses the <strong>default qop</strong> which is compatible with <a title="An Extension to HTTP : Digest Access Authentication" href="http://www.ietf.org/rfc/rfc2069.txt" target="_blank">RFC 2069</a>, the client encrypts the user name and password as follows.</p>
<pre class="brush: csharp; title: ; notranslate">HA1 = MD5( username : realm : password)
HA2 = MD5( method : digestURI)
response = MD5( HA1 : nonce : HA2)</pre>
<p>An MD5 hash is created from the user name, realm and password, a separate MD5 hash is created from the HTTP method and the URI of the resource that the client requests. The response is created through a MD5 hash that combines the previous two MD5 hashes and the server generated nonce. The <em>DigestEncoderBase </em>class holds the functionality to generate both the HA1 and HA2 hashes.</p>
<pre class="brush: csharp; title: ; notranslate">private string CreateHa1(DigestHeader digestHeader,
   string password)
{
  return md5Encoder.Encode(
    string.Format(
    &quot;{0}:{1}:{2}&quot;,
    digestHeader.UserName,
    digestHeader.Realm,
    password));
}

private string CreateHa2(DigestHeader digestHeader)
{
  return md5Encoder.Encode(
    string.Format(
    &quot;{0}:{1}&quot;,
    digestHeader.Method,
    digestHeader.Uri));
}
</pre>
<p>The base classes <em>AuthDigestEncoder</em> and <em>DefaultDigestEncoder</em> are responsible for generating the response. This last step, generating the response, is what differs in the two derived classes. The response of the <strong>Auth</strong> algorithm should be generated differently. The Auth algorithm includes a <em>nonceCount</em> and a client generated Nonce in the response. Also, the actual qop string is concatenated before the hash is calculated.</p>
<pre class="brush: csharp; title: ; notranslate">response = MD5(HA1:nonce:nonceCount:clientNonce:qop:HA2)</pre>
<p>This is why the Auth algorithm is more secure than Default, the server performs an additional check to see if the <em>nonceCount</em> is incremented by the client with every request. The <em>CreateResponse</em> method of the <em>AuthDigestEncoder</em> generates the Auth response.</p>
<pre class="brush: csharp; title: ; notranslate">public override string CreateResponse(
   DigestHeader digestHeader,
   string ha1,
   string ha2)
{
  return
   md5Encoder.Encode(
     string.Format(
     &quot;{0}:{1}:{2}:{3}:{4}:{5}&quot;,
     ha1,
     digestHeader.Nonce,
     digestHeader.NounceCounter,
     digestHeader.Cnonce,
     digestHeader.Qop.ToString(),
     ha2));
}</pre>
<h3><a name="ExtendingWCFREST8"></a>Extending WCF REST</h3>
<p>To be able to integrate Digest Authentication with WCF REST, the WCF REST framework has to be extended. This is done by creating a custom <em>RequestInterceptor</em>. For more information, take a look at my <a title="Extending WCF REST through RequestInterceptor" href="BasicAuthWCFRest.aspx" target="_blank">previous article</a> on CodeProject which explains this extension in more detail.</p>
<h3><a name="RetrievingandStoringusercredentials9"></a>Retrieving and Storing User Credentials</h3>
<p>The password of the user is transmitted as part of the response generated by the client to the server. It is not possible for the server to extract the password from the response. The server generates a response and checks if the response is equal to the response that was given by the client. This means that there are two options for storing and retrieval of user credentials using Digest Authentication.</p>
<ul>
<li>The first and most secure option is for every user to store the HA1 key in the credentials data storage and validate using the stored HA1 key. This has a disadvantage because you have to change the HA1 key in the data storage if the username, password or realm changes.</li>
<li>The second option is to store the password of the use in the credentials data storage in such a way that it is possible to retrieve the original password. This is obviously less secure than the first option.</li>
</ul>
<h3><a name="Usingthesourcecode10"></a>Using the Source Code</h3>
<p>If you want to secure your own WCF REST service with Basic Authentication using the provided source code, you need to execute the following steps:</p>
<ul>
<li>Add a reference to the <em>DigestAuthenticationUsingWCF </em>assembly</li>
<li>Create a custom membership provider derived from <em>MembershipProvider</em></li>
<li>Implement the <em>ValidateUser</em> method against your back-end security storage</li>
<li>Create a custom membership user derived from Membership user</li>
<li>Implement the <em>GetUser</em> method against your back-end security storage</li>
<li>Create a custom <em>DigestAuthenticationHostFactory</em>, see the example in the provided source code</li>
<li>Add the new <em>DigestAuthenticationHostFactory </em>to the markup of the <em>.svc</em> file</li>
</ul>
<h2><a name="PointsofInterest11"></a>Points of Interest</h2>
<p>The provided source code is developed using TDD and uses the <a href="http://nunit.org/">NUnit framework</a> for creating and executing tests. <a href="http://www.ayende.com/projects/rhino-mocks.aspx">Rhino mocks</a> is used as a mocking framework inside the unit tests.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.semanticarchitecture.net/digest-authentication-on-a-wcf-rest-service/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The business case for a DI framework</title>
		<link>http://www.semanticarchitecture.net/the-business-case-for-a-di-framework/</link>
		<comments>http://www.semanticarchitecture.net/the-business-case-for-a-di-framework/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 20:32:22 +0000</pubDate>
		<dc:creator>kalkie</dc:creator>
				<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.semanticarchitecture.net/?p=153</guid>
		<description><![CDATA[Every Architecture Design decision should be based on one or more Non-Functional requirements. Each Non-Functional requirement in its case should be based on a business need. Recently I asked myself what are the business needs for using a dependency injection (DI) framework?]]></description>
			<content:encoded><![CDATA[<p>Every Architecture Design decision should be based on one or more <strong>Non-Functional requirements</strong>. Each Non-Functional requirement in its case should be based on a business need. Recently I asked myself what are the <strong>business needs</strong> for using a <strong>dependency injection</strong> <strong>(DI) framework</strong>?</p>
<p>Which visible, tangible benefit would be reached using a DI framework? This blog post describes the arguments we used to successfully convince management.</p>
<p><strong>Dependency Injection Framework</strong></p>
<p>A <strong>dependency injection framework</strong> is a software module that manages the dependencies of your application. Dependency Injection is a specific form of <a href="http://en.wikipedia.org/wiki/Inversion_of_control">inversion of control</a> where the concern being inverted is the process of obtaining the needed dependency. An excellent discussion on how to use a DI container can be found <a title="Dependency Injection Inversion" href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion" target="_blank">here</a> by Uncle Bob. Inversion of Control is one of the <a title="SOLID Design Principles" href="http://www.semanticarchitecture.net/post-with-picture/solid-software-architecture" target="_blank">SOLID design principles</a>. There are many types of dependency injection frameworks, for a comparison take a look at <a title="Comparison of DI frameworks" href="http://blog.ashmind.com/2008/08/19/comparing-net-di-ioc-frameworks-part-1/" target="_blank">this</a> and <a title="Comparison of DI frameworks" href="http://blog.ashmind.com/2008/09/08/comparing-net-di-ioc-frameworks-part-2/" target="_blank">this</a> blog post from Andrey Shchekin.</p>
<p><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/DIP.png"><img class="alignnone  wp-image-121" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="DIP" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/DIP.png" alt="SOLID Dependency Inversion Principle" width="634" height="411" /></a></p>
<p><strong>Convincing management</strong></p>
<p>Recently at LetsGrow we started using a dependency injection or DI framework for the LetsGrow.com platform. We are using <a title="Test Driven Development (TDD)" href="http://en.wikipedia.org/wiki/Test-driven_development" target="_blank">Test Driven Development (TDD)</a> and using a DI framework seemed to be the next logical step. This would remove the implementation of several builder patterns and would make implementing tests easier. It would also make the LetsGrow.com platform more flexible. Although these benefits were clear to me, I had a hard time convincing management of the business benefits of a DI framework.</p>
<p><strong>Who makes the design decision?</strong></p>
<p>One could argue that the design decision of using a <strong>DI Framework</strong> should be made by an architect. I think that introducing a DI framework also comes at a cost. Surely the benefits will be greater in the long run, but the development of new functionality will be slower during the introduction of a DI framework. The development team has to learn how to use such a framework, some existing code will change with no visible benefit for the user of the application. Therefore, I think that such a decision should be made in cooperation with management.</p>
<p><strong>Business benefits</strong></p>
<p>The primary benefits of using a DI framework are that it makes the source code of an application <strong>easier to understand</strong>, <strong>to maintain</strong> and <strong>to extend</strong>. Using a DI framework will <strong>reduce</strong> the amount of <strong>source code</strong> which will <strong>decrease the time</strong> it takes to implement <strong>new functionality</strong> in your application. In the long-term, this results in <strong>reduced maintenance costs</strong>,<strong> lower bug rates</strong> and thus<strong> increased customer satisfaction</strong>.</p>
<p>Secondary benefits are that <strong>configuration </strong>of an application will be more obvious as it sits in a <strong>central place</strong>. All instances of objects will be created the same way (<strong>consistency</strong>). When using a DI framework it becomes possible to switch implementations at run-time. For end-to-end tests it becomes possible to replace key components of the application with fake implementations.</p>
<p><strong>Risks</strong></p>
<p style="text-align: justify;">We also looked at the possible risks of introducing a DI framework. We identified the following risks:</p>
<ul>
<li>increased memory usage</li>
<li>performance overhead</li>
<li>complexity in configuration</li>
<li>less transparent source code</li>
</ul>
<p>After some research we found that there was indeed an increase in memory and some performance overhead but they were marginal. I think that everyone that wants to use a DI framework should also do this research themselves because this could differ per application.</p>
<p>Complexity in configuration is a real risk. If you describe each dependency of each class in the configuration file,  the configuration file becomes too large and complex. Only these dependencies that should be managed by the framework should be described using the configuration file. Hartmut Wilms also discusses this risk in <a href="http://www.innoq.com/blog/hw/2007/08/29/dependency_injection_good_or_bad_practice.html" target="_blank">this</a> blog post.  The last risk, less transparent source code we think will be temporary. Developers will have to get used to using a DI framework and the fact that the DI framework takes care of creating instances of objects.</p>
<p><strong>Conclusion</strong></p>
<p>My conclusion is that with the arguments mentioned in this post you should have no trouble convincing management of the business benefits of using a DI framework for your application. If you have more benefits or convinced your organization using a totally different arguments let me know. I would love to hear it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.semanticarchitecture.net/the-business-case-for-a-di-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Basic Authentication On WCF Rest</title>
		<link>http://www.semanticarchitecture.net/basic-authentication-on-wcf-rest/</link>
		<comments>http://www.semanticarchitecture.net/basic-authentication-on-wcf-rest/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 20:24:37 +0000</pubDate>
		<dc:creator>kalkie</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.semanticarchitecture.net/?p=128</guid>
		<description><![CDATA[This article explains a method to secure a REST based service using basic authentication. The service itself is implemented using Microsoft Windows Communication Foundation. The authentication of the credentials should be possible against any type of back-end. For example authenticate against active directory, custom file or a database. Default, Basic Authentication is possible in combination with WCF and [...]]]></description>
			<content:encoded><![CDATA[<p>This article explains a method to secure a REST based service using basic authentication. The service itself is implemented using Microsoft Windows Communication Foundation. The authentication of the credentials should be possible against any type of back-end.</p>
<p>For example authenticate against active directory, custom file or a database. Default, Basic Authentication is possible in combination with WCF and IIS, authentication is only possible then against active directory. This article and provided source code can be used in two ways. First just download the code, go down to the use the code part and implement your WCF service using Basic authentication. Second you can use the article to learn about what exactly is Basic Authentication and how can WCF be extended in a simple way.</p>
<h2>Basic Authentication</h2>
<p>Basic authentication is a standard protocol defined within Http 1.0 that defines an authentication scheme. In this scheme the client must authenticate itself with a user-id and password. Basic authentication is described in <a href="http://www.faqs.org/rfcs/rfc2617.html">RFC 2617</a>. When a client requests a resource from a site that is protected using Basic Authentication the server returns a 401 “Not authorized” response. Inside this response the server has added an sign that the site is protected using Basic Authentication. The server adds <em>WWW-Authenticate: Basic realm=”site”</em> to the header of the response, <em>Basic</em> indicates that the authentication scheme is Basic Authentication. Realm is an string that indicates which part of the site is protected. It has no further usage in the actual authentication mechanism itself.</p>
<p>An internet browser generates a dialog based on this response message, this dialog shows the realm and allows a user to enter a user name and password.</p>
<p><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/BasicAuthenticationUsingWCFRest_1.png"><img class="alignnone size-full wp-image-147" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="BasicAuthenticationUsingWCFRest_1" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/BasicAuthenticationUsingWCFRest_1.png" alt="Request Response Flow Basic Authentication" width="500" height="300" /></a></p>
<p>When a user enters the user name and password, the client resents the request but adds <em>“Authorization: Basic SGVsbG8gQmFzZTY0″</em> to the header of the request. The strange characters after <em>Basic</em> are the user name and password separated by a single colon “:” in a base64 encoded string. The server decodes the string, extracts the credentials and validates them against the back-end. When the credentials are correctly validated the server returns the requested content to the client.</p>
<p><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/BasicAuthenticationUsingWCFRest_2.png"><img class="alignnone size-full wp-image-148" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="BasicAuthenticationUsingWCFRest_2" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/BasicAuthenticationUsingWCFRest_2.png" alt="Request Response Flow Basic Authentication" width="500" height="300" /></a></p>
<h2>Extending WCF Rest</h2>
<p>WCF REST is part of the <a href="http://aspnet.codeplex.com/releases/view/24644">WCF Rest starter kit</a>. Unlike standard WCF, the WCF starter kit provides a simple way to apply behaviour to all server operations. Adding this behavior to normal WCF can get fairly complex. WCF Rest uses Request Interceptors. Request interceptors shield you from the more complex extensibility points. Request Interceptors are executed at the WCF channel level and enable you to interpret the incoming request and generate an appropriate response.</p>
<pre class="brush: csharp; title: ; notranslate">public class MyRequestInterceptor : RequestInterceptor
{
  public override void ProcessRequest
        (ref RequestContext requestContext)
  {
    //Access request with requextContext.RequestMessage
  }
}</pre>
<p>By deriving a new class from the RequestInterceptor base class you create a custom request interceptor. The method ProcessRequest is executed for every request that arrives at the service. Inside this method we read the header of the request and decode the base64 encoded string if it is present. If it is not present we generate a response that includes <em>WWW-Authenticate: Basic realm=”site”</em> in the header.</p>
<h2>Linking the custom RequestInterceptor to the service</h2>
<p>The RequestInterceptor can be linked to the service by creating a custom ServiceHostFactory. The ServiceHostFactory is responsible for provides instances of ServiceHost in managed hosting environments. By Managed hosting environments Microsoft means IIS hosted services. The CreateServiceHost method of the ServiceHostFactory creates a new WebServiceHost and adds the new RequestInceptor to the Interceptors collection.</p>
<pre class="brush: csharp; title: ; notranslate">public class BasicAuthenticationHostFactory :
   ServiceHostFactory
{
  protected override ServiceHost CreateServiceHost
         (Type serviceType, Uri[] baseAddresses)
  {
    var serviceHost = new WebServiceHost2(serviceType,
        true, baseAddresses);
    serviceHost.Interceptors.Add(
        requestInterceptorFactory.Create(&quot;DataWebService&quot;,
            new CustomMembershipProvider()));
    return serviceHost;
  }
}</pre>
<p>This new ServiceHostFactory is linked to the service through the markup file (.svc) of the service. Inside the markup, you override the host factory of the service.</p>
<pre class="brush: csharp; title: ; notranslate">ServiceHost Language=&quot;C#&quot; Debug=&quot;true&quot;
   Service=&quot;WCFServer.Service&quot;
   Factory=&quot;WCFServer.BasicAuthenticationHostFactory&quot;</pre>
<h2>Custom MembershipProvider</h2>
<p>The provided source code uses a MembershipProvider to actually authenticate the credentials of the client. You can write your own MembershipProvider by deriving from MembershipProvider. The only method that needs to be implemented is the ValidateUser method. This is the method the code uses to validate the user. This customer MembershipProvider is linked to the RequestInterceptor in the CreateServiceHost method of the ServiceHostFactory.</p>
<pre class="brush: csharp; title: ; notranslate">public class CustomMembershipProvider : MembershipProvider
{
  public override bool ValidateUser(string username,
        string password)
  {
    //perform validation return false;
  }
  ...</pre>
<h2>Security context</h2>
<p>After we have authenticated the incoming request, we have to create and set the security context. This enables the usage of the client credentials inside a service method. WCF uses the thread local ServiceSecurityContext for this. After the request has been authenticated, a new ServiceSecurityContext is created and added to the incoming request. This enables retrieving the user name inside the service method with ServiceSecurityContext.Current.PrimaryIdentity.Name</p>
<h2>Using the code</h2>
<p>If you want to secure your own WCF REST service with Basic Authentication, you need to execute the following steps:</p>
<ul>
<li>Add a reference to the BasicAuthenticationUsingWCF assembly</li>
<li>Create a new membership provider derived from MembershipProvider</li>
<li>Implement the ValidateUser method against your back-end security storage</li>
<li>Create a custom BasicAuthenticationHostFactory</li>
<li>Add the new BasicAuthenticationHostFactory to the markup of the .svc file</li>
</ul>
<p><strong>Points of Interest</strong></p>
<p>Although Basic Authentication is a method to secure a web site or service, the authentication mechanism itself is not secure. The user name and password are send base64 encoded over the internet. To make this more secure, the server should offer the service using https. Https secures the channel so that the base64 encoded user name and password cannot be decrypted.</p>
<p>This article and source code are based on the example of <a href="http://weblogs.asp.net/cibrax/archive/2009/03/20/custom-basic-authentication-for-restful-services.aspx">Pablo M. Cibraro</a> who deserves the credit for the solution. The provided sourcecode is developed using TDD and uses the <a href="http://www.nunit.org/">NUnit framework</a> for creating and executing tests. <a href="http://www.ayende.com/projects/rhino-mocks.aspx">Rhino mocks</a> is used as a mocking framework inside the unit tests.</p>
<h2>Source Code</h2>
<p><a title="CodeProject" href="http://www.codeproject.com/KB/WCF/BasicAuthWCFRest.aspx" target="_blank">The source can be found at CodeProject</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.semanticarchitecture.net/basic-authentication-on-wcf-rest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SOLID Design Principles</title>
		<link>http://www.semanticarchitecture.net/solid-design-principles/</link>
		<comments>http://www.semanticarchitecture.net/solid-design-principles/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 20:07:44 +0000</pubDate>
		<dc:creator>kalkie</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.semanticarchitecture.net/?p=115</guid>
		<description><![CDATA[Recently two colleagues and I did a workshop in which we explained SOLID Software development. SOLID is an acronym that stand for five principles for object-oriented development. SOLID stands for Single Responsibility, Open Closed, Liskov Substitution, Interface Segregation and the Dependency Inversion Principle. These principles can help a software developer manage dependencies between software components. Bob Martin the author of the [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Recently two colleagues and I did a workshop in which we explained <strong>SOLID</strong> Software development. <strong>SOLID</strong> is an acronym that stand for five principles for object-oriented development. SOLID stands for <span style="color: #000000;">Single Responsibility</span>, <span style="color: #000000;">Open Closed</span>, <span style="color: #000000;">Liskov Substitution</span>, <span style="color: #000000;">Interface Segregation </span>and the <span style="color: #000000;">Dependency Inversion Principle.</span></p>
<p style="text-align: justify;">These principles can help a software developer manage dependencies between software components. Bob Martin the author of the principles writes <em>“So dependency management, and therefore these principles, are at the foundation of the -ilities that software developers desire”. </em>You can read the original article <a title="Bob Martin Original SOLID Article" href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod" target="_blank">here</a>.</p>
<p style="text-align: justify;">These -ilities that Bob Martin refers to are the non functional requirements of a software product. I think that a software architecture is responsible for implementing the non functional or quality attributes of a software product. Therefore, I think that the SOLID design principles are one of the most fundamental rules for designing a robust software architecture. During the workshop we showed the following pictures to introduce a single principle. Can you spot the principle just by looking at a picture? The pictures are from <a href="http://www.lostechies.com/blogs/derickbailey/archive/2009/02/11/solid-development-principles-in-motivational-pictures.aspx" target="_blank">this site</a> which also explains the SOLID design principles.</p>
<p style="text-align: justify;"><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/SRP.png"><img class="alignnone  wp-image-119" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="SRP" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/SRP.png" alt="SOLID Single Responsibility Principle" width="659" height="444" /></a></p>
<p style="text-align: justify;"><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/OCP.png"><img class="alignnone  wp-image-120" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="OCP" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/OCP.png" alt="SOLID Open Close Principle" width="641" height="426" /></a></p>
<p style="text-align: justify;"><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/DIP.png"><img class="alignnone  wp-image-121" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="DIP" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/DIP.png" alt="SOLID Dependency Inversion Principle" width="634" height="411" /></a></p>
<p style="text-align: justify;"><strong style="text-align: center;"><a title="LetsGrow SOLID Software development" href="http://www.slideshare.net/kalkie/letsgrow-solid-software-development">LetsGrow SOLID Software development</a></strong></p>
<p style="text-align: justify;"><strong style="text-align: center;"></strong>The nice thing about the SOLID principles that they can be used on many levels. For example, the Single Responsibility principle can be used on method level, class level, library level and even on (sub)system level. The same goes for the other principles. The slide show below shows the slides on slide-share that we used for the workshop.</p>
<p style="text-align: center;"><object type='application/x-shockwave-flash' wmode='opaque' data='http://static.slideshare.net/swf/ssplayer2.swf?id=3837230&doc=letsgrowsolidsoftwaredevelopment-100424042706-phpapp01' width='425' height='348'><param name='movie' value='http://static.slideshare.net/swf/ssplayer2.swf?id=3837230&doc=letsgrowsolidsoftwaredevelopment-100424042706-phpapp01' /><param name='allowFullScreen' value='true' /></object></p>
<div style="text-align: justify;"></div>
]]></content:encoded>
			<wfw:commentRss>http://www.semanticarchitecture.net/solid-design-principles/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Discover Non-functional Requirements</title>
		<link>http://www.semanticarchitecture.net/discover-non-functional-requirements/</link>
		<comments>http://www.semanticarchitecture.net/discover-non-functional-requirements/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 07:08:03 +0000</pubDate>
		<dc:creator>kalkie</dc:creator>
				<category><![CDATA[Software Architecture]]></category>

		<guid isPermaLink="false">http://www.semanticarchitecture.net/?p=110</guid>
		<description><![CDATA[I talked about the importance of Non-functional requirements in my earlier post “Non-functional requirements define a Software Architecture”. What I did not describe was how you can discover the Non-functional requirements? My preferred method when it comes to requirements gathering, functional or Non-functional, is through interactive workshops. During these workshops you facilitate the requirements gathering using interactive [...]]]></description>
			<content:encoded><![CDATA[<p>I talked about the importance of Non-functional requirements in my earlier post <a title="Non Functional-requirements define a software architecture" href="http://www.semanticarchitecture.net/post-with-picture/non-functional-requirements-define-a-software-architecture" target="_blank">“Non-functional requirements define a Software Architecture”</a>. What I did not describe was how you can <strong>discover</strong> the <strong>Non-functional requirements</strong>?</p>
<p>My preferred method when it comes to requirements gathering, functional or Non-functional, is through interactive workshops. During these <strong>workshops</strong> you facilitate the requirements gathering using interactive methods. I find that workshops with the main stakeholders are very time effective and create a common ground.</p>
<p>You should decide a standard set of Non-functional requirements for your company. This list of standard Non-functional requirements will function as your checklist at the start of a project. By using a standard you create consistency through all of your projects. You can choose from a number of existing standards or you could create your own. The thing is that not all of these standard will fit your organization, some will be too small, too complex or too large.</p>
<p>You can use any of the following standards or a combination as your <strong>Non-functional requirements checklist</strong></p>
<ul>
<li><a title="ISO/IEC 9126 Software engineering — Product quality" href="http://en.wikipedia.org/wiki/ISO/IEC_9126" target="_blank">ISO 9126</a></li>
<li><a title="QUINT" href="http://complexitymap.com/quint2/index.html" target="_blank">QUINT (Quality In Information Technology) a superset of 9126</a></li>
<li><a title="Functionality Usability Reliability Performance Supportability" href="http://en.wikipedia.org/wiki/FURPS" target="_blank">FURPS (Functionality Usability Reliability Performance Supportability)</a></li>
<li><a title="ISO/IEC 25030 Software product Quality Requirements and Evaluation" href="http://webstore.iec.ch/preview/info_isoiec25001%7Bed1.0%7Den.pdf" target="_blank">ISO/IEC SQuaRE (Software product Quality Requirements and Evaluation)</a></li>
<li><a title="SUMI Software Usability Measurement Inventory" href="http://sumi.ucc.ie/whatis.html" target="_blank">SUMI (Software Usability Measurement Inventory)</a></li>
</ul>
<p>A workshop is the process in which you find the <strong>Non-functional requirements</strong> of your application. If you have done a number of these <strong>requirements workshops, </strong>you often find a <strong>stable set </strong>that are important for all the applications that you develop. For example, in industrial applications, reliability and time behavior are often the most important. What would be the contents of such a workshop?</p>
<p><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Which-Non-functional-Requirement.jpg"><img class="alignnone size-full wp-image-111" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="Which-Non-functional-Requirement" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Which-Non-functional-Requirement.jpg" alt="Which non-functional requirement" width="513" height="385" /></a></p>
<p style="text-align: center;">
<p>Depending on the maturity of your organization, you first need to <a title="Create Awareness about the importance of Non-functional requirements" href="http://www.semanticarchitecture.net/post-with-picture/non-functional-requirements-define-a-software-architecture" target="_blank">create awareness about the importance of Non-functional requirements</a>. Next,  invite the stakeholders of your application to a <a title="QUINT Quality In Information Technology" href="http://complexitymap.com/quint2/index.html" target="_blank">QUINT</a> workshop. In this first workshop you are going to find the most important <strong>Non functional requirements</strong> of your application. For this first step I often use the main categories of <a title="Quality In Information Technology" href="http://complexitymap.com/quint2/index.html" target="_blank">QUINT</a> (Functionality, Reliability, Usability, Efficiency, Maintainability and Portability). In the invitation of the workshop add some home-work for the participants which explains these categories.</p>
<p>At the start of the workshop explain the main categories and answer any questions about the home-work. The goal of this workshop is to determine a prioritized list with the most important <a title="Quality In Information Technology" href="http://complexitymap.com/quint2/index.html" target="_blank">QUINT</a> categories for your application. An effective method to create this list is <a title="Dot voting" href="http://www.innovationtools.com/Articles/ArticleDetails.asp?a=141" target="_blank">dot-voting</a>. Each participant gets three dots that he or she can use to vote on a category. The total number of votes on a category determines the order.</p>
<p>After a first voting round, the stakeholders need to discuss the outcome, is this what they expected? Reassure the stakeholders that all <a title="Non-functional requirements definition" href="http://en.wikipedia.org/wiki/Non-functional_requirement" target="_blank">Non-functional requirements</a><strong> </strong>are important and will get a place in the <strong>software architecture</strong>. This prioritized list is used as a basis for our <strong>design decisions</strong>. After the discussion, do another voting round to create the final list.</p>
<p>This workshop, which can be done in one or two hours creates a prioritized list of <strong>Non-functional requirements</strong>. This list will be the basis of the <strong>software architecture</strong> of your application. In a follow-up of this workshop you could descend to the real attributes of <a title="Quality In Information Technology" href="http://complexitymap.com/quint2/index.html" target="_blank">QUINT</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.semanticarchitecture.net/discover-non-functional-requirements/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LetsGrow WordPress Weather Plugin</title>
		<link>http://www.semanticarchitecture.net/letsgrow-wordpress-weather-plugin/</link>
		<comments>http://www.semanticarchitecture.net/letsgrow-wordpress-weather-plugin/#comments</comments>
		<pubDate>Tue, 24 Jan 2012 21:25:36 +0000</pubDate>
		<dc:creator>kalkie</dc:creator>
				<category><![CDATA[Software Architecture]]></category>

		<guid isPermaLink="false">http://www.semanticarchitecture.net/?p=90</guid>
		<description><![CDATA[The sidebar of this page shows the LetsGrow.com WordPress Weather plug-in. This WordPress plug-in shows a map of the Netherlands together with real-time temperature and radiation data. The plug-in retrieves the data directly from LetsGrow.com using LetsGrow Services. LetsGrow Services is a module that enables customers or partners of LetsGrow.com to develop third-party applications that use the data from the LetsGrow platform. The LetsGrow.com [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">
<p style="text-align: justify;">The sidebar of this page shows the <strong>LetsGrow.com WordPress Weather</strong> plug-in. This WordPress plug-in shows a map of the Netherlands together with real-time temperature and radiation data. The plug-in retrieves the data directly from <a href="http://www.semanticarchitecture.net/2010/04/11/letsgrow/" target="_self">LetsGrow.com</a> using <strong>LetsGrow Services</strong>.</p>
<p style="text-align: justify;">LetsGrow Services is a module that enables customers or partners of LetsGrow.com to develop third-party applications that use the data from the LetsGrow platform. The LetsGrow.com WordPress Weather plug-in shows the power and flexibility of the LetsGrow.com platform.</p>
<p style="text-align: justify;"><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/LetsGrow-Services.png"><img class="alignleft  wp-image-91" style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="LetsGrow Services" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/LetsGrow-Services.png" alt="LetsGrow Services" width="365" height="368" /></a>LetsGrow has been collecting data from different brands of climate computers and plant sensors for over five years. A customer can use and integrate this information into custom applications through LetsGrow Services.</p>
<p style="text-align: justify;">As the figure shows LetsGrow Services run on machines in the LetsGrow Data Centre. Businesses can create applications that consume these services and offer new services to their customers.</p>
<p>Here are some examples of the kinds of applications that could be built using LetsGrow Services.</p>
<ul>
<li style="text-align: justify;">A research institute or university could combine the large amount of historically data that is available in LetsGrow. This may lead to better understanding and insights in the growing process of crops that can help reduce the energy demand of a greenhouse. Note that a customer maintains ownership of the data in LetsGrow. First, a customer gives explicit consent to use the data. Then a  research institute can use the data.</li>
</ul>
<ul>
<li style="text-align: justify;">A horticultural advisor of a customer could extract the data of the customer and perform calculations on the data. The results of these calculations could be stored in LetsGrow using LetsGrow Services. A customer can see the original data combined with the results of the calculation in one single view.</li>
</ul>
<ul>
<li style="text-align: justify;">Affiliates or partners of LetsGrow could create custom modules using LetsGrow data. For example, a flowering prediction module that has a model that predicts the flowering date of a crop. These extra modules may even lead to automatic changes in the greenhouse settings to aim for a specific flowering date.  These extra modules could be offered to the customers of LetsGrow.</li>
</ul>
<p>For more information about LetsGrow Services take a look at the document <a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Introducing-LetsGrow-Services.pdf"><strong><img class="alignnone " style="border-style: initial; border-color: initial; border-image: initial; border-width: 0px;" title="pdf document" src="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/pdficon_small.gif" alt="pdf document" width="14" height="14" /></strong></a><a href="http://www.semanticarchitecture.net/www/wp-content/uploads/2012/01/Introducing-LetsGrow-Services.pdf"><strong>Introducing LetsGrow Services </strong><span style="color: #c0c0c0;"><strong>(PDF, 750K)</strong></span></a><strong> </strong>which describes LetsGrow services in more detail.</p>
<p><strong>Semantic Architecture?</strong></p>
<p style="text-align: justify;">Ok, but how is this related to <strong>Semantic Architecture</strong> and the <strong>Semantic Web</strong>? It isn’t! Currently the LetsGrow platform doesn’t use a Semantic Architecture or Semantic Web technologies. In the next post I will explain how a Semantic Architecture could be used to solve the problems I had during the implementation. Also I will describe the details about how I created this WordPress plug-in.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.semanticarchitecture.net/letsgrow-wordpress-weather-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Calculate sunrise, sunset and maximum solar radiation</title>
		<link>http://www.semanticarchitecture.net/calculate-sunrise-sunset-and-maximum-solar-radiation/</link>
		<comments>http://www.semanticarchitecture.net/calculate-sunrise-sunset-and-maximum-solar-radiation/#comments</comments>
		<pubDate>Tue, 24 Jan 2012 21:13:48 +0000</pubDate>
		<dc:creator>kalkie</dc:creator>
				<category><![CDATA[Software Architecture]]></category>

		<guid isPermaLink="false">http://www.semanticarchitecture.net/?p=78</guid>
		<description><![CDATA[I got some requests for releasing the library that calculates the sunrise, sunset and maximum solar radiation of the LetsGrow WordPress Weather plug-in. I extracted the algorithms from the implementation on the platform LetsGrow.com and decided to release it. It is possible to calculate the sunrise, sunset and maximum solar radiation using some well-known formulas. For [...]]]></description>
			<content:encoded><![CDATA[<p>I got some requests for releasing the library that calculates the sunrise, sunset and maximum solar radiation of the LetsGrow WordPress Weather plug-in. I extracted the algorithms from the implementation on the platform <a title="LetsGrow.com Growing data onlony" href="http://www.letsgrow.com" target="_blank">LetsGrow.com</a> and decided to release it.</p>
<p>It is possible to calculate the sunrise, sunset and maximum solar radiation using some well-known formulas. For those of you who are interested in these formulas take a look at the following pages at Wikipedia (<a href="http://en.wikipedia.org/wiki/Declination" target="_blank">Declination of the Sun</a>, <a href="http://en.wikipedia.org/wiki/Sunrise" target="_blank">Sunrise</a>, <a href="http://en.wikipedia.org/wiki/Sunset" target="_blank">Sunset</a>). If you just want to calculate the sunrise, sunset and maximum solar radiation take a look below on how to use the code.</p>
<p>I wrote the code in C# and packed it in a Visual Studio 2008 solution. It has two assemblies, Astronomy and AstronomyTest. The assembly Astronomy has the SolarCalculator class which performs the real calculation. The assembly AstronomyTest has several unit-tests that validates the calculations against external sources. The SolarCalculator class needs the longitude, latitude, time-zone and whether to use daylight savings. You can create  an instance of the SolarCalculator like this:</p>
<pre class="brush: csharp; title: ; notranslate">
const Double Longitute = 5.127869;
const Double Latitude = 52.108192;
const int LongituteTimeZone = 15;
const bool UseSummerTime = true;
SunCalculator calculator = new
  SunCalculator(Longitute, Latitude,
  LongituteTimeZone, UseSummerTime);
</pre>
<p>The actual calculation of sunrise, sunset and maximum solar radiation can be seen below.</p>
<pre class="brush: csharp; highlight: [6]; title: ; notranslate">
DateTime sunRise = calculator.CalculateSunRise(
   new DateTime(2010, 4, 1));
DateTime sunSet = calculator.CalculateSunSet(
   new DateTime(2010, 4, 1));
Double maximumSolarRadiation =
   calculator.CalculateMaximumSolarRadiation(
      new DateTime(2010, 1, 1, 1, 3, 0));
</pre>
<p>The DateTime returned from CalculateSunRise and CalculateSunSet includes the sunrise and sunset time. For more information take a look at the unit-tests in the assembly AstronomyTest which explain the usage in more detail.</p>
<p>I added <a href="http://www.codeproject.com/KB/recipes/SolarCalculator.aspx">an article to The Code Project</a> which also explains the usage of the library including a download link of the source code.</p>
<p><a title="Solar Calculator - Calculate Sunrise and Sunset" href="http://www.codeproject.com/KB/recipes/SolarCalculator.aspx" target="_blank"><img style="float: left;" title="Solar Calculator on The Code Project" src="http://www.codeproject.com/App_Themes/Std/Img/logo225x90.gif" alt="Code Project Logo" width="225" height="90" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.semanticarchitecture.net/calculate-sunrise-sunset-and-maximum-solar-radiation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

