<?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>Ian Mercer&#187; .NET</title>
	<atom:link href="http://blog.abodit.com/category/programming/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.abodit.com</link>
	<description>Living in the World&#039;s Smartest House</description>
	<lastBuildDate>Tue, 07 Sep 2010 19:50:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Constrained parallelism for the Task Parallel Library</title>
		<link>http://blog.abodit.com/2010/09/constrained-parallelism-for-the-task-parallel-library/</link>
		<comments>http://blog.abodit.com/2010/09/constrained-parallelism-for-the-task-parallel-library/#comments</comments>
		<pubDate>Wed, 01 Sep 2010 19:29:07 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Parallel processing]]></category>
		<category><![CDATA[Task]]></category>
		<category><![CDATA[TaskParallel]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1108</guid>
		<description><![CDATA[When developing .NET applications there is often the need to execute multiple background processes, for example, fetching and rendering different size thumbnails for images. Typically you queue actions like these onto the thread pool. But in the case of thumbnail generation you typically want to fetch a base image first and then perform the resize <a href="http://blog.abodit.com/2010/09/constrained-parallelism-for-the-task-parallel-library/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>When developing .NET applications there is often the need to execute multiple background processes, for example, fetching and rendering different size thumbnails for images.  Typically you queue actions like these onto the thread pool. But in the case of thumbnail generation you typically want to fetch a base image first and then perform the resize operations on it.  If five web pages each request a different thumbnail size simultaneously you may end up fetching the same image five times before processing it.  Of course, you can add file based locking around this to ensure that only the first once gets to fetch the data but it would be much better if you could instead instruct the Task Parallel Library to execute co-dependent tasks sequentially.</p>
<p>The new Task parallel library has continuations that allow one task to chain onto the end of a previous task but you still a way to track all the tasks currently active so you can find the other task to chain onto it.  In a multi-threaded asp.net environment that&#8217;s not so easy.</p>
<p>Below is a TaskFactory that gives you constrained parallelism allowing you to queue up tasks in such a way that no two tasks with the same key will execute in parallel. To use it you simply create a new TaskFactorySequentiallyByKey and then call StartNewChainByKey() with a suitable key, e.g. “RENDERimage12345.jpg”. This method returns a normal Task object that you can Wait on or add more continuations. All the usual TaskFactory constructor options are provided so you can have a different TaskScheduler, common cancellation token, and other options.</p>
<p>Note also that it expects an Action&lt;CancellationToken&gt; not just a plain Action. This is so your Action can be polite and monitor the cancellation token to know when to stop early. If you don’t need that you can always pass in a closure that tosses the CancellationToken, i.e. (token) => MyAction().</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;

namespace Utility
{
    /// &lt;summary&gt;
    /// The TaskFactorySequentiallyByKey factory limits concurrency when actions are passed with the same key.  Those actions are executed sequentially
    /// and never in parallel.
    /// &lt;/summary&gt;
    /// &lt;remarks&gt;
    /// For example, you have an action to fetch an image from the web to a local hard drive and then render a specific size of thumbnail for it.
    ///   The action includes code to check if the original image is already on disk, if not it fetches it.
    ///   It then checks if the correct size thumbnail has been rendered, if not it renders it.
    /// You want to be able to fire off requests for thumbnails from multiple different asp.net web pages and ensure that any two requests for the
    /// same original image are executed sequentially so that the image is only fetched once from the web before both thumbnail renders run.
    /// &lt;/remarks&gt;
    public class TaskFactorySequentiallyByKey : TaskFactory
    {
        /// &lt;summary&gt;
        /// Tasks currently queued based on key
        /// &lt;/summary&gt;
        Dictionary&lt;string, Task&gt; inUse = new Dictionary&lt;string, Task&gt;();

        public TaskFactorySequentiallyByKey()
            : base()
        {
        }

        public TaskFactorySequentiallyByKey(CancellationToken cancellationToken)
            : base(cancellationToken)
        { }

        public TaskFactorySequentiallyByKey(TaskScheduler scheduler)
            : base(scheduler)
        { }

        public TaskFactorySequentiallyByKey(TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions)
            : base(creationOptions, continuationOptions)
        { }

        public TaskFactorySequentiallyByKey(CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
            : base(cancellationToken, creationOptions, continuationOptions, scheduler)
        { }

        protected virtual void FinishedUsing(string key, Task taskThatJustCompleted)
        {
            lock (this.inUse)
            {
                // If the key is present AND it point to the task that just finished THEN we are done
                // and can clear the key for the next task that comes in ...
                if (this.inUse.ContainsKey(key))
                    if (this.inUse[key] == taskThatJustCompleted)
                    {
                        this.inUse.Remove(key);
                        Debug.WriteLine(&quot;Finished using &quot; + key + &quot; completely&quot;);
                    }
                    else
                    {
                        Debug.WriteLine(&quot;Finished an item for &quot; + key);
                    }

            }
        }

        /// &lt;summary&gt;
        /// Queue an action but prevent parallel execution of items having the same key.  Instead, run them sequentially.
        /// &lt;/summary&gt;
        /// &lt;remarks&gt;
        /// This allows you to, for example, queue up tasks to fetch an image from the web to a cache and render a thumbnail for it at different sizes
        /// while ensuring that the image is only fetched to the cache once before each different size thumbnail is generated
        /// &lt;/remarks&gt;
        public Task StartNewChainByKey(string key, Action&lt;CancellationToken&gt; action)
        {
            return StartNewChainByKey(key, action, base.CancellationToken);
        }

        /// &lt;summary&gt;
        /// Queue an action but prevent parallel execution of items having the same key.  Instead, run them sequentially.
        /// &lt;/summary&gt;
        /// &lt;remarks&gt;
        /// This allows you to, for example, queue up tasks to fetch an image from the web to a cache and render a thumbnail for it at different sizes
        /// while ensuring that the image is only fetched to the cache once before each different size thumbnail is generated
        /// &lt;/remarks&gt;
        public Task StartNewChainByKey(string key, Action&lt;CancellationToken&gt; action, CancellationToken cancellationToken)
        {
            CancellationToken combined = cancellationToken == base.CancellationToken ? base.CancellationToken :
                                CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, base.CancellationToken).Token;

            lock (inUse)
            {
                Task result;
                if (inUse.TryGetValue(key, out result))
                {
                    // chain the supplied action after it ...
                    result = result.ContinueWith((task) =&gt; action(combined), combined);

                    // And then schedule a completion check after that
                    result.ContinueWith((task) =&gt; FinishedUsing(key, task));

                    // Update the dictionary so that it tracks the new LAST task in line, not any of the earlier ones
                    inUse[key] = result;

                    Debug.WriteLine(&quot;Chained onto &quot; + key);

                    return result;
                }

                // otherwise simply create it and start it after remembering that the key is in use
                result = new Task(() =&gt; action(combined), combined);

                inUse.Add(key, result);

                // queue up the check after it
                result.ContinueWith((task) =&gt; FinishedUsing(key, task));

                Debug.WriteLine(&quot;Starting a new action for &quot; + key);

                // And finally start it
                result.Start(this.Scheduler);

                return result;
            }
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2010/09/constrained-parallelism-for-the-task-parallel-library/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Singleton tasks: A TaskFactory for the Task Parallel Library with &#8216;run-only-one&#8217; semantics</title>
		<link>http://blog.abodit.com/2010/09/singleton-tasks-a-taskfactory-for-the-task-parallel-library-with-run-only-one-semantics/</link>
		<comments>http://blog.abodit.com/2010/09/singleton-tasks-a-taskfactory-for-the-task-parallel-library-with-run-only-one-semantics/#comments</comments>
		<pubDate>Wed, 01 Sep 2010 19:11:37 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Parallel processing]]></category>
		<category><![CDATA[Task]]></category>
		<category><![CDATA[TaskParallel]]></category>
		<category><![CDATA[tpl]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1102</guid>
		<description><![CDATA[When developing .NET applications there is often the need to execute some slow background process repeatedly. For example, fetching a feed from a remote site, updating a user&#8217;s last logged in time, &#8230; etc. Typically you queue actions like these onto the thread pool. But under load that becomes problematic as requests may be coming <a href="http://blog.abodit.com/2010/09/singleton-tasks-a-taskfactory-for-the-task-parallel-library-with-run-only-one-semantics/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>When developing .NET applications there is often the need to execute some slow background process repeatedly.  For example, fetching a feed from a remote site, updating a user&#8217;s last logged in time, &#8230;  etc.  Typically you queue actions like these onto the thread pool.  But under load that becomes problematic as requests may be coming in faster than you can service them, the queue builds up and you are now executing multiple requests for the same action when you only really needed to do one.   Even when not under load, if two users request a web page that requires the same image to be loaded and resized for display you only want to fetch it and resize it once.  What you really want is an intelligent work queue that can coalesce multiple requests for the same action into a single action that gets executed just once.</p>
<p>The new Task parallel library doesn&#8217;t have anything that can handle these &#8216;run-only-one&#8217; actions directly but it does have all the necessary building blocks to build one by creating a new TaskFactory and using Task continuations.</p>
<p>Below is a TaskFactory that gives you &#8216;run-only-one&#8217; actions.  To use it you simply create a new TaskFactoryLimitOneByKey and then call StartNewOrUseExisting() with a suitable key, e.g. &#8220;FETCH/cache/image12345.jpg&#8221;.  This method returns a normal Task object that you can Wait on or add more continuations.  All the usual TaskFactory constructor options are provided so you can have a different TaskScheduler, common cancellation token,  and other options.</p>
<p>Note also that it expects an Action&lt;CancellationToken&gt; not just a plain Action.  This is so your Action can be polite and monitor the cancellation token to know when to stop early.  If you don&#8217;t need that you can always pass in a closure that tosses the CancellationToken, i.e. (token) => MyAction().</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;

namespace Utility
{
    /// &lt;summary&gt;
    /// A task factory where Tasks are queued up with a key and only one of that key is allowed to exist either in the queue or executing
    /// &lt;/summary&gt;
    /// &lt;remarks&gt;
    /// This is useful for tasks like fetching a file from backing store, or updating local information from a remote service
    /// You want to be able to queue up a Task to go do the work but you don't want it to happen 5 times in quick succession
    /// NB: This does not absolve you from using file locking and other techniques in your method to handle simultaneous requests,
    /// it just greatly reduces the chances of it happening.  Another example would be updating a user's last logged in data in a
    /// database.  Under heavy load the queue to write to the database may be getting long and you don't want to update it for the same
    /// user repeatedly if you can avoid it with a single write.
    /// &lt;/remarks&gt;
    public class TaskFactoryLimitOneByKey : TaskFactory
    {
        /// &lt;summary&gt;
        /// Tasks currently queued based on key
        /// &lt;/summary&gt;
        Dictionary&lt;string, Task&gt; inUse = new Dictionary&lt;string, Task&gt;();

        public TaskFactoryLimitOneByKey()
            : base()
        {
        }

        public TaskFactoryLimitOneByKey(CancellationToken cancellationToken)
            : base(cancellationToken)
        { }

        public TaskFactoryLimitOneByKey(TaskScheduler scheduler)
            : base(scheduler)
        { }

        public TaskFactoryLimitOneByKey(TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions)
            : base(creationOptions, continuationOptions)
        { }

        public TaskFactoryLimitOneByKey(CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
            : base(cancellationToken, creationOptions, continuationOptions, scheduler)
        { }

        protected virtual void FinishedUsing(string key, Task taskThatJustCompleted)
        {
            lock (this.inUse)
            {
                // If the key is present AND it point to the task that just finished THEN we are done
                // and can clear the key so that the next task coming in using it will get to execute ...
                if (this.inUse.ContainsKey(key))
                    if (this.inUse[key] == taskThatJustCompleted)
                    {
                        this.inUse.Remove(key);
                        Debug.WriteLine(&quot;Finished using &quot; + key + &quot; completely&quot;);
                    }
                    else
                    {
                        Debug.WriteLine(&quot;Finished an item for &quot; + key);
                    }

            }
        }

        /// &lt;summary&gt;
        /// Queue only one of a given action based on a key.  A singleton pattern for Tasks with the same key.
        /// &lt;/summary&gt;
        /// &lt;remarks&gt;
        /// This allows you to queue up a request to, for example, render a file based on the file name
        /// Even if multiple users all request the file at the same time, only one render will ever run
        /// and they can all wait on that Task to complete.
        /// &lt;/remarks&gt;
        public Task StartNewOrUseExisting(string key, Action&lt;CancellationToken&gt; action)
        {
            return StartNewOrUseExisting(key, action, base.CancellationToken);
        }

        /// &lt;summary&gt;
        /// Queue only one of a given action based on a key.  A singleton pattern for Tasks with the same key.
        /// &lt;/summary&gt;
        /// &lt;remarks&gt;
        /// This allows you to queue up a request to, for example, render a file based on the file name
        /// Even if multiple users all request the file at the same time, only one render will ever run
        /// and they can all wait on that Task to complete.
        /// &lt;/remarks&gt;
        public Task StartNewOrUseExisting (string key, Action&lt;CancellationToken&gt; action, CancellationToken cancellationToken)
        {
            CancellationToken combined = cancellationToken == base.CancellationToken ?  base.CancellationToken :
                                            CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, base.CancellationToken).Token;
            lock (inUse)
            {
                if (inUse.ContainsKey(key))
                {
                    Debug.WriteLine(&quot;Reusing existing action for &quot; + key);
                    return inUse[key];  // and toss the new action away
                }

                // otherwise, make a new one and add it ... with a continuation on the end to pull it off ...
                Task result = new Task(() =&gt; action(combined), combined);
                inUse.Add(key, result);

                // queue up the check after it
                result.ContinueWith((finished) =&gt; this.FinishedUsing(key, result));

                Debug.WriteLine(&quot;Starting a new action for &quot; + key);

                // and finally start it
                result.Start(this.Scheduler);
                return result;
            }
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2010/09/singleton-tasks-a-taskfactory-for-the-task-parallel-library-with-run-only-one-semantics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GDI+ Image.FromFile has a problem &#8211; here&#8217;s how to fix it</title>
		<link>http://blog.abodit.com/2010/07/gdi-image-fromfile-problem/</link>
		<comments>http://blog.abodit.com/2010/07/gdi-image-fromfile-problem/#comments</comments>
		<pubDate>Fri, 30 Jul 2010 20:38:49 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[GDI+]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1081</guid>
		<description><![CDATA[In GDI+ you can call Image.FromFile to load an image from a file. BUT there are several issues with this call, the biggest being that GDI+ will keep the file open long after you are done with it. Here is an image loader that gets around this issue. If you are running a high volume <a href="http://blog.abodit.com/2010/07/gdi-image-fromfile-problem/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>In GDI+ you can call Image.FromFile to load an image from a file.  BUT there are several issues with this call, the biggest being that GDI+ will keep the file open long after you are done with it.  Here is an image loader that gets around this issue.</p>
<p>If you are running a high volume web site, and your images are on a SAN you&#8217;ll find this technique necessary to prevent an eventual exhaustion of filehandles.</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using System.Data;

namespace Utility
{
public static class ImageLoader
{
// This isn’t going to help much – you’ll run out of memory anyway on very large images – but if you are keeping several in memory it might …
public const int MaximumImageDimension = 10000;

///
/// Method to safely load an image from a file without leaving the file open,
/// also gets the size down to a manageable size in the case of HUGE images
///
/// An Image – don’t forget to dispose of it later
public static Image LoadImage (string filePath)
{
try
{
FileInfo fi = new FileInfo(filePath);

if (!fi.Exists) throw new FileNotFoundException(“Cannot find image”);
if (fi.Length == 0) throw new FileNotFoundException(“Zero length image file “);

// Image.FromFile is known to leave files open, so we use a stream instead to read it
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
if (!fs.CanRead) throw new FileLoadException (“Cannot read file stream”);

if (fs.Length == 0) throw new FileLoadException(“File stream zero length”);

using (Image original = Image.FromStream(fs))
{
// Make a copy of the file in memory, then release the one GDI+ gave us
// thus ensuring that all file handles are closed properly (which GDI+ doesn’t do for us in a timely fashion)
int width = original.Width;
int height = original.Height;
if (width == 0) throw new DataException(“Bad image dimension width=0″);
if (height == 0) throw new DataException(“Bad image dimension height=0″);

// Now shrink it to Max size to control memory consumption
if (width &gt; MaximumImageDimension)
{
height = height * MaximumImageDimension / width;
width = MaximumImageDimension;
}
if (height &gt; MaximumImageDimension)
{
width = width * MaximumImageDimension / height;
height = MaximumImageDimension;
}

Bitmap copy = new Bitmap(width, height);
using (Graphics graphics = Graphics.FromImage(copy))
{
graphics.DrawImage(original, 0, 0, copy.Width, copy.Height);
}
return copy;
}
}
}
catch (Exception ex)
{
ex.Data.Add(“FileName”, filePath);
throw;
}
}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2010/07/gdi-image-fromfile-problem/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Weather Forecasting for Home Automation</title>
		<link>http://blog.abodit.com/2010/07/weather-forecasting-for-home-automation/</link>
		<comments>http://blog.abodit.com/2010/07/weather-forecasting-for-home-automation/#comments</comments>
		<pubDate>Mon, 26 Jul 2010 03:38:20 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Home Automation]]></category>
		<category><![CDATA[Smartest House]]></category>
		<category><![CDATA[Chart control]]></category>
		<category><![CDATA[Weather forecast]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1043</guid>
		<description><![CDATA[In the USA we are lucky to have the NOAA and their excellent web service that can provide a detailed weather forecast for any location (specified by latitude and longitude). Using this service my home automation system maintains a detailed, regularly updated local weather forecast object which can be queried easily by any other object <a href="http://blog.abodit.com/2010/07/weather-forecasting-for-home-automation/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>In the USA we are lucky to have the <a href="http://www.nws.noaa.gov/xml/">NOAA and their excellent web service</a> that can provide a detailed weather forecast for any location (specified by latitude and longitude).  Using this service my home automation system maintains a detailed, regularly updated local weather forecast object which can be queried easily by any other object in the home.  </p>
<div id="attachment_1042" class="wp-caption alignright" style="width: 310px"><a href="http://blog.abodit.com/wp-content/uploads/2010/07/HomeAutomationWeather2.png"><img src="http://blog.abodit.com/wp-content/uploads/2010/07/HomeAutomationWeather2-300x170.png" alt="Home Automation Weather Forecasting" title="Home Automation Weather Forecasting" width="300" height="170" class="size-medium wp-image-1042" /></a><p class="wp-caption-text">Click to enlarge</p></div>
<p>On the weather page you can view all of the forecast information it collects.  Of interest the graph in the lower right compares the forecast from NOAA with the actual recorded temperature.  In this case you can see just how accurate the forecast has been for the last 24 hours.  Normally it runs almost this close but with occasionally there is a significant discrepancy caused by the bizarre &#8216;convergence zone&#8217; we live in where Pacific weather patterns split around the Olympic mountains and then recombine over Seattle in somewhat unpredictable ways.</p>
<p>Unlike most home automation systems that have fairly limited if-the-else or table-driven approaches to defining the home logic (often limited to only the current value of any variable), my system has control structures that include statistical functions over temporal data allowing analysis of past data (e.g. average temperature in the last day), or in the case of the weather forecast, future values, e.g. expected temperature one hour from now found using interpolation. </p>
<pre class="brush: csharp;">
                var oneHourForNow = DateTime.Now.AddHours(1);
                double outsideForecastOneHourFromNow = weatherService.ApparentTemperatureHourly.ValueAtTimeWithLinearInterpolation(oneHourForNow);
</pre>
<p>This forward looking view at the weather allows for features like garden sprinklers that don&#8217;t turn on when it&#8217;s going to rain or HVAC that skips heating cycles when the forecast predicts warm weather later today.  </p>
<p>In addition the house is able to issue a detailed local forecast over the speakers when it wakes you up in the morning.  Somewhat uniquely the forecast it generates is a <em>relative weather forecast</em> comparing yesterday with today, or today with tomorrow.  It might for example say &#8220;Today will be much warmer that yesterday&#8221; which is a whole lot less words than a normal weather forecast!</p>
<p>The house also has Natural Language Generation (NLG) features which are able to summarize a group of temporal series into distinct ranges allowing it for instance to highlight which the best times of the day are to be outside:-</p>
<blockquote><p>Monday : excellent from dawn at 5:34 AM until 11:36 AM; hot from 11:36 AM to 2:00 PM; too hot from 2:00 PM to 7:00 PM; hot until sunset at 8:53 PM.
</p></blockquote>
<h4>ASP.NET Charts</h4>
<p>Incidentally, all of the graphs are rendered using the <a href="http://weblogs.asp.net/scottgu/archive/2008/11/24/new-asp-net-charting-control-lt-asp-chart-runat-quot-server-quot-gt.aspx">.NET Charting Control</a>.  The graph object is instantiated on the server, all the lines and axes are added to it, then it is serialized and sent over TCP to the web server using WCF.  On the web server it is rendered as a PNG file using an Action method that takes size parameters allowing any size graph to be shown on any page.  Here&#8217;s the MVC code that takes the stream from WCF, loads the Chart and then delivers it as a PNG.</p>
<pre class="brush: csharp;">
            Chart chart = new Chart();
            chart.Serializer.Load(ms);

            MemoryStream ms2 = new MemoryStream();
            chart.SaveImage(ms2);

            return File(ms2.GetBuffer(), @&quot;image/png&quot;);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2010/07/weather-forecasting-for-home-automation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sequential Logic Blocks &#8211; compared to the Reactive Framework</title>
		<link>http://blog.abodit.com/2010/07/sequential-logic-blocks-my-answer-to-the-reactive-framework/</link>
		<comments>http://blog.abodit.com/2010/07/sequential-logic-blocks-my-answer-to-the-reactive-framework/#comments</comments>
		<pubDate>Tue, 20 Jul 2010 01:22:48 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Home Automation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Logic blocks]]></category>
		<category><![CDATA[Reactive framework]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=1031</guid>
		<description><![CDATA[One of the features of my home automation system is extensions to the C# language that make it easy to define complex logical and temporal behaviors. These behave somewhat like the new Reactive Extensions in .NET but with some key differences which I will explain below. I developed these extensions before Reactive Framework was released <a href="http://blog.abodit.com/2010/07/sequential-logic-blocks-my-answer-to-the-reactive-framework/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>One of the features of my home automation system is extensions to the C# language that make it easy to define complex logical and temporal behaviors.  These behave somewhat like the new <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">Reactive Extensions in .NET</a> but with some key differences which I will explain below.  I developed these extensions before Reactive Framework was released and have recently been looking at Rx to see if I could combine my ideas with Rx but because of the differences explained below I haven&#8217;t been able to do that.</p>
<p>But, before explaining why, let&#8217;s first look at an example:-</p>
<pre class="brush: csharp;">
            FirstFloor.Kitchen.GoesOff.Provided((dt) =&gt; Entrance.VisitorCountThisEvening.Count &lt; 2).TurnOff(Aquarium.Light);
</pre>
<p>This means that if the kitchen goes not occupied (off) provided we have less than two visitors this evening, then turn off the aquarium lights.</p>
<p>Here&#8217;s a more complex example where we create an intermediate logic element called &#8216;activityInKitchen&#8217; using the <strong>.Or</strong> method, and then based on that activity we decide whether to announce that the fish have not been fed.  The decision uses a combination of pulse stretching, repeats (Every) and <strong>Then</strong> which fires only if a particular sequence is followed within a given time window.  Finally it uses the <strong>Do</strong> method which fires off an <strong>Action</strong>.</p>
<pre class="brush: csharp;">
            SensorDevice activityInKitchen =
                Kitchen.KitchenFloor.Or(Kitchen.MotionSensor, Kitchen.BackDoorToGarage, Kitchen.BreakfastBarFloor, Kitchen.Phone);

            activityInKitchen
                .ProvidedNot(Home.DinnerGuests)
                .PulseStretch(16 * 60)       // Make it continuous
                .Every(60 * 60)              // Once every 1 hour
                .Then(activityInKitchen, 15*60)
                .Do(&quot;Announce fish are hungry&quot;, (sender) =&gt;
                {
                    Kitchen.Aquarium.AnnounceFishHungry(Kitchen.MediaZone);
                });
</pre>
<p>As you can see the use of a fluent syntax allows for a very natural, almost english-like definition of complex temporal expressions.  But that&#8217;s not all it allows&#8230;</p>
<p>The sequential logic blocks created when you call one of the many methods like .Then, .Or, .Every, &#8230; are actual objects created within the hierarchical structure of the house and the objects used to represent it.  This means that they take part (automatically) in all of the features provided by a base house object including logging, browsing, and most importantly persistence.</p>
<p>Because these sequential logic blocks are persistent you can have very long running events like <strong>.EveryDays(2)</strong> and even if the entire system is shut down and restarted it will come back in the correct state and all the necessary delays and timers will still be working.</p>
<p>Another key benefit of these sequential logic blocks compared to, say, the .NET Reactive Framwork is that they form a chain that can be traversed in either direction: forward as an event propagates through, or in reverse to determine <i>why</i> a particular action was taken.  This means that my home automation system is able to explain <i>why</i> it turned the lights on or off.  Currently all of these decisions are logged on the per-object logging system which means you can inspect any room, appliance, light, etc. and see everything that happened to it and the reasons why.</p>
<blockquote><p>
                          Hallway became occupied, caused by Motion sensor<br />
                          Set brightness on Aisle lights in Kitchen to 20% because Leaving office late at night
</p></blockquote>
<p>Compare this to other home automation systems from major vendors.  They contain fairly simple logic, often expressed in a tabular or grid format with limited if-the-else type logic and when something happens there is often no record as to what happened and, worse, there is absolutely no record as to why it happened.</p>
<p>Any sufficiently complex system will have unexpected behavior, the difference here is that when it does something odd I can easily look at the logging and see the explanation as to why it happened.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2010/07/sequential-logic-blocks-my-answer-to-the-reactive-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lengthening short Urls in C#</title>
		<link>http://blog.abodit.com/2010/07/lengthening-short-urls-in-csharp/</link>
		<comments>http://blog.abodit.com/2010/07/lengthening-short-urls-in-csharp/#comments</comments>
		<pubDate>Mon, 05 Jul 2010 22:08:00 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[URL]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=977</guid>
		<description><![CDATA[If you deal with Twitter APIs, sooner or later, you&#8217;ll probably want to lengthen those short URLs back to long URLs. There&#8217;s a couple of services you can use to do this but it&#8217;s really quite easy so you might as well do it yourself. The code below follows each redirect until it reaches a <a href="http://blog.abodit.com/2010/07/lengthening-short-urls-in-csharp/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>If you deal with Twitter APIs, sooner or later, you&#8217;ll probably want to lengthen those short URLs back to long URLs.  There&#8217;s a couple of services you can use to do this but it&#8217;s really quite easy so you might as well do it yourself.  The code below follows each redirect until it reaches a real page (or an error), it then returns the last URL it finds.  </p>
<pre class="brush: csharp;">
        private string UrlLengthen(string url)
        {
            string newurl = url;

            bool redirecting = true;

            while (redirecting)
            {

                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newurl);
                    request.AllowAutoRedirect = false;
                    request.UserAgent = &quot;Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)&quot;;
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    if ((int)response.StatusCode == 301 || (int)response.StatusCode == 302)
                    {
                        string uriString = response.Headers[&quot;Location&quot;];
                        Log.Debug(&quot;Redirecting &quot; + newurl + &quot; to &quot; + uriString + &quot; because &quot; + response.StatusCode);
                        newurl = uriString;
                        // and keep going
                    }
                    else
                    {
                        Log.Debug(&quot;Not redirecting &quot; + url + &quot; because &quot; + response.StatusCode);
                        redirecting = false;
                    }
                }
                catch (Exception ex)
                {
                    ex.Data.Add(&quot;url&quot;, newurl);
                    Exceptions.ExceptionRecord.ReportCritical(ex);
                    redirecting = false;
                }
            }
            return newurl;
        }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2010/07/lengthening-short-urls-in-csharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Recent reading material on .NET and software development in general</title>
		<link>http://blog.abodit.com/2010/05/recent-reading-material-on-net-and-software-development-in-general/</link>
		<comments>http://blog.abodit.com/2010/05/recent-reading-material-on-net-and-software-development-in-general/#comments</comments>
		<pubDate>Sat, 22 May 2010 17:39:37 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=873</guid>
		<description><![CDATA[Links I&#8217;m reading up on at the moment: Memory Mapped Files in .NET 4.0]]></description>
			<content:encoded><![CDATA[<p>Links I&#8217;m reading up on at the moment: <a href="http://blogs.msdn.com/salvapatuel/archive/2009/06/08/working-with-memory-mapped-files-in-net-4.aspx">Memory Mapped Files in .NET 4.0</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2010/05/recent-reading-material-on-net-and-software-development-in-general/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An ontology triple (quad) store for RDF/OWL using Entity Framework 4</title>
		<link>http://blog.abodit.com/2010/05/an-ontology-triple-quad-store-for-rdfowl-using-entity-framework-4/</link>
		<comments>http://blog.abodit.com/2010/05/an-ontology-triple-quad-store-for-rdfowl-using-entity-framework-4/#comments</comments>
		<pubDate>Wed, 12 May 2010 22:34:21 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[NLP]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Semantic Web]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Ontology]]></category>
		<category><![CDATA[OWL]]></category>
		<category><![CDATA[RDF]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=859</guid>
		<description><![CDATA[This weeks side-project was the creation of an ontology store using Entity Framework 4. An ontology store stores axioms consisting of Subject, Predicate, Object which are usually serialized as RDF, OWL, N3, &#8230; Whereas there&#8217;s lots of details about these serialization formats, the actual mechanics of how to store and manipulate them was somewhat harder <a href="http://blog.abodit.com/2010/05/an-ontology-triple-quad-store-for-rdfowl-using-entity-framework-4/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>This weeks side-project was the creation of an ontology store using Entity Framework 4.  An ontology store stores axioms consisting of Subject, Predicate, Object which are usually serialized as RDF, OWL, N3, &#8230;  Whereas there&#8217;s lots of details about these serialization formats, the actual mechanics of how to store and manipulate them was somewhat harder to come by.  Nevertheless, after much experimentation I came up with an Entity Model that can store Quads (Subject, Predicate, Object and Meta) or Quins (Subject, Predicate, Object, Meta, Graph).  The addition of Meta allows one Axiom to reference another.  The addition of Graph allows the store to be segmented making it easy to import some N3 or RDF into a graph, then flush that graph if it is no longer needed or if a newer version becomes available.</p>
<p>The store is currently hooked up to an Euler reasoner that can reason against it, lazily fetching just the necessary records from the SQL database that backs the Entity Model.</p>
<p>Here&#8217;s the EDMX showing how I modeled the Ontology Store:</p>
<p><a href="http://blog.abodit.com/wp-content/uploads/2010/05/OntologyEDMX.png"><img src="http://blog.abodit.com/wp-content/uploads/2010/05/OntologyEDMX.png" alt="Ontology Store Entity Model" title="Ontology Store Entity Model" width="841" height="528" class="aligncenter size-full wp-image-858" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2010/05/an-ontology-triple-quad-store-for-rdfowl-using-entity-framework-4/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The relationship could not be changed because one or more of the foreign-key properties is non-nullable</title>
		<link>http://blog.abodit.com/2010/05/the-relationship-could-not-be-changed-because-one-or-more-of-the-foreign-key-properties-is-non-nullable/</link>
		<comments>http://blog.abodit.com/2010/05/the-relationship-could-not-be-changed-because-one-or-more-of-the-foreign-key-properties-is-non-nullable/#comments</comments>
		<pubDate>Mon, 10 May 2010 06:35:24 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=830</guid>
		<description><![CDATA[Today&#8217;s cryptic Entity Framework message &#8230; The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must <a href="http://blog.abodit.com/2010/05/the-relationship-could-not-be-changed-because-one-or-more-of-the-foreign-key-properties-is-non-nullable/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>Today&#8217;s cryptic Entity Framework message &#8230;</p>
<p><em>The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.</em></p>
<p>The reason for this was a simple override to GetHashCode().  Entity Framework seems somewhat pedantic about how hash codes work.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2010/05/the-relationship-could-not-be-changed-because-one-or-more-of-the-foreign-key-properties-is-non-nullable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A simple redirect route handler for ASP.NET 3.5 routing</title>
		<link>http://blog.abodit.com/2010/04/a-simple-redirect-route-handler-for-asp-net-3-5-routing/</link>
		<comments>http://blog.abodit.com/2010/04/a-simple-redirect-route-handler-for-asp-net-3-5-routing/#comments</comments>
		<pubDate>Wed, 21 Apr 2010 05:22:43 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Routing]]></category>

		<guid isPermaLink="false">http://blog.abodit.com/?p=739</guid>
		<description><![CDATA[ASP.NET 3.5 Routing is a very powerful tool not just for registering routes for newer ASP.NET MVC applications but also for adding SEO friendly routes to older Webforms (ASPX) applications, or for routing multiple URLs to a single page. But that&#8217;s not all it can do. You can create your own IRouteHandler and then have <a href="http://blog.abodit.com/2010/04/a-simple-redirect-route-handler-for-asp-net-3-5-routing/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>ASP.NET 3.5 Routing is a very powerful tool not just for registering routes for newer ASP.NET MVC applications but also for adding SEO friendly routes to older Webforms (ASPX) applications, or for routing multiple URLs to a single page.  But that&#8217;s not all it can do.  You can create your own IRouteHandler and then have complete control over what to do with any incoming HttpRequest.</p>
<p>Here for example is a way to do a permanent redirect when a given route is matched.  To use it you might, for example, do:-</p>
<pre class="brush: csharp;">
            routes.Add(new Route(&quot;sample.aspx&quot;, new RedirectRouteHandler(&quot;/home/start&quot;)));
</pre>
<p>Here is the RedirectRouteHandler that can turn any request into a 301 redirect for you:-</p>
<pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// Redirect Route Handler
    /// &lt;/summary&gt;
    public class RedirectRouteHandler : IRouteHandler
    {
        private string newUrl;

        public RedirectRouteHandler(string newUrl)
        {
            this.newUrl = newUrl;
        }

        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new RedirectHandler(newUrl);
        }
    }

    /// &lt;summary&gt;
    /// &lt;para&gt;Redirecting MVC handler&lt;/para&gt;
    /// &lt;/summary&gt;
    public class RedirectHandler : IHttpHandler
    {
        private string newUrl;

        public RedirectHandler(string newUrl)
        {
            this.newUrl = newUrl;
        }

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext httpContext)
        {
            httpContext.Response.Status = &quot;301 Moved Permanently&quot;;
            httpContext.Response.StatusCode = 301;
            httpContext.Response.AppendHeader(&quot;Location&quot;, newUrl);
            return;
        }
    }
</pre>
<p><strong>Note:</strong> I&#8217;m not saying this is the best or only way to handle this.  You&#8217;ll want to look at Url Rewriting and the Application and Request Routing module for IIS7 in particular.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.abodit.com/2010/04/a-simple-redirect-route-handler-for-asp-net-3-5-routing/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
