<?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>Innovatian Software &#187; Programming</title>
	<atom:link href="http://innovatian.com/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://innovatian.com</link>
	<description></description>
	<lastBuildDate>Tue, 01 Jun 2010 04:48:25 +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>Using Ninject with TopShelf and Quartz</title>
		<link>http://innovatian.com/2010/05/using-ninject-with-topshelf-and-quartz/</link>
		<comments>http://innovatian.com/2010/05/using-ninject-with-topshelf-and-quartz/#comments</comments>
		<pubDate>Sat, 22 May 2010 18:58:05 +0000</pubDate>
		<dc:creator>Ian Davis</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Ninject]]></category>
		<category><![CDATA[Quartz]]></category>
		<category><![CDATA[TopShelf]]></category>

		<guid isPermaLink="false">http://innovatian.com/?p=440</guid>
		<description><![CDATA[Disclaimer: I am neither an expert in TopShelf nor Quartz, this is just me trying to plug them together with Ninject. The fist thing we need to have in order to use Quartz is to create a job that will be executed. We will call ours the VerifyEmailServerJob. public class VerifyEmailServerJob : IJob { #region [...]]]></description>
			<content:encoded><![CDATA[<p></p><pre><code>Disclaimer: I am neither an expert in TopShelf nor Quartz, this is just me trying to plug them together with Ninject.</code></pre>
<p>The fist thing we need to have in order to use Quartz is to create a job that will be executed. We will call ours the <code>VerifyEmailServerJob</code>.</p>
<pre class="brush: csharp;">public class VerifyEmailServerJob : IJob
{
    #region Implementation of IJob

    public void Execute( JobExecutionContext context )
    {
        // TODO: Verify the email server is working correctly...
    }

    #endregion
}</pre>
<p>Now that we have a job to run, we will create a windows service that will create the job details and schedule the job. The windows service essentially acts as a host for the jobs.</p>
<pre class="brush: csharp;">public interface IWindowsService
{
    void Start();
    void Stop();
}

public partial class MonitoringService : ServiceBase, IWindowsService
{
    private readonly JobManager _jobManager;
    private readonly List&lt;IScheduler&gt; _schedulers = new List&lt;IScheduler&gt;();

    public MonitoringService( JobManager jobManager )
    {
        _jobManager = jobManager;
        InitializeComponent();
    }

    public void Start()
    {
        // TODO: Pull from config file.
        var trigger = new CronTrigger( &quot;name&quot;, &quot;group&quot;, &quot;0 0 4/8 * * MON-FRI&quot; );
        IScheduler scheduler = _jobManager.Add&lt;VerifyEmailServerJob&gt;( trigger );
        _schedulers.Add( scheduler );
    }

    protected override void OnStop()
    {
        _schedulers.ForEach( scheduler =&gt; scheduler.Shutdown( false ) );
        _schedulers.Clear();
    }
}</pre>
<p>In order to inject our services into the jobs, we need to take control of the job activation pipeline. Quartz allows us to do this by using a implementation of <code>IJobFactory</code>. In my example I am injecting a creation callback function that will use the Ninject kernel to activate the job and add any dependencies without the <code>IJobFactory</code> knowing of the kernel. I am also throwing in my own <code>JobManager</code> to cut down on the amount of code I need to write to add a job. But note that we have to tell the scheduler which <code>JobFactory</code> to use when activating.</p>
<pre class="brush: csharp;">public class JobFactory : IJobFactory
{
    private readonly Func&lt;Type, IJob&gt; _creationCallback;

    public JobFactory( Func&lt;Type, IJob&gt; creationCallback )
    {
        _creationCallback = creationCallback;
    }

    #region Implementation of IJobFactory

    public IJob NewJob( TriggerFiredBundle bundle )
    {
        JobDetail jobDetail = bundle.JobDetail;
        Type jobType = jobDetail.JobType;
        var job = _creationCallback( jobType );
        return job;
    }

    #endregion
}

public class JobManager
{
    private readonly IJobFactory _jobFactory;
    private readonly ISchedulerFactory _schedulerFactory;

    public JobManager( ISchedulerFactory schedulerFactory, IJobFactory jobFactory )
    {
        _schedulerFactory = schedulerFactory;
        _jobFactory = jobFactory;
    }

    public IScheduler Add&lt;T&gt;( Trigger trigger ) where T : IJob
    {
        IScheduler scheduler = _schedulerFactory.GetScheduler();
        scheduler.JobFactory = _jobFactory;
        scheduler.Start();
        var jobDetail = new JobDetail( typeof (T).Name, typeof (T) );
        scheduler.ScheduleJob( jobDetail, trigger );
        return scheduler;
    }
}</pre>
<p>Now with out jobs, triggers, and service foundation, all we need to do is configure TopShelf to run our service and configure our kernel to inject our dependencies.</p>
<pre class="brush: csharp;">
internal static class Program
{
    private static void Main( string[] args )
    {
        using ( IKernel kernel = CreateKernel() )
        {
            RunConfiguration cfg =
                RunnerConfigurator.New(
                    x =&gt;
                    {
                        x.SetDisplayName( &quot;Monitoring Service&quot; );
                        x.SetServiceName( &quot;Monitor&quot; );
                        x.SetDescription( &quot;Monitoring Service&quot; );
                        x.ConfigureService&lt;MonitoringService&gt;( kernel );
                        x.RunAsLocalSystem();
                    } );

            Runner.Host( cfg, args );
        }
    }

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind&lt;IJobFactory&gt;().To&lt;JobFactory&gt;();
        kernel.Bind&lt;Func&lt;Type, IJob&gt;&gt;().ToConstant( type =&gt; (IJob) kernel.Get( type ) );
        kernel.Bind&lt;ISchedulerFactory&gt;().To&lt;StdSchedulerFactory&gt;();
        kernel.Bind&lt;JobManager&gt;().ToSelf().InSingletonScope();
        kernel.Bind&lt;IWindowsService&gt;().To&lt;MonitoringService&gt;();
        return kernel;
    }
}

public static class SyntaxExtensions
{
    public static void ConfigureService&lt;T&gt;( this IRunnerConfigurator runnerConfigurator, IKernel kernel )
        where T : ServiceBase, IWindowsService
    {
        runnerConfigurator.ConfigureService&lt;T&gt;(
            c =&gt;
            {
                c.HowToBuildService( serviceName =&gt; kernel.Get&lt;T&gt;() );
                c.Named( typeof (T).Name );
                c.WhenStopped( s =&gt; s.Stop() );
                c.WhenStarted( s =&gt; s.Start() );
            } );
    }
}</pre>
<p>That about does it! We have a service configured and controlled by TopShelf, running scheduled jobs using Quartz, and dependencies and jobs created by Ninject.</p>
]]></content:encoded>
			<wfw:commentRss>http://innovatian.com/2010/05/using-ninject-with-topshelf-and-quartz/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Windows Services with Ninject and TopShelf</title>
		<link>http://innovatian.com/2010/05/windows-services-with-ninject-and-topshelf/</link>
		<comments>http://innovatian.com/2010/05/windows-services-with-ninject-and-topshelf/#comments</comments>
		<pubDate>Wed, 19 May 2010 00:06:26 +0000</pubDate>
		<dc:creator>Ian Davis</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Ninject]]></category>
		<category><![CDATA[TopShelf]]></category>

		<guid isPermaLink="false">http://innovatian.com/?p=445</guid>
		<description><![CDATA[I was testing out TopShelf and here is an example I put together in order to have Ninject activate the services and their dependencies: #region Using Directives using System; using System.ServiceProcess; using YourCorp.Services; using Ninject; using Topshelf; using Topshelf.Configuration; using Topshelf.Configuration.Dsl; #endregion namespace YourCorp { internal static class Program { private static void Main( string[] [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I was testing out TopShelf and here is an example I put together in order to have Ninject activate the services and their dependencies:</p>
<pre class="brush: csharp;">#region Using Directives

using System;
using System.ServiceProcess;
using YourCorp.Services;
using Ninject;
using Topshelf;
using Topshelf.Configuration;
using Topshelf.Configuration.Dsl;

#endregion

namespace YourCorp
{
    internal static class Program
    {
        private static void Main( string[] args )
        {
            using ( IKernel kernel = CreateKernel() )
            {
                RunConfiguration cfg =
                    RunnerConfigurator.New(
                        x =&gt;
                        {
                            x.SetDisplayName( &quot;Your Service&quot; );
                            x.SetServiceName( &quot;YourService&quot; );
                            x.SetDescription( &quot;Your Service&quot; );
                            x.ConfigureService&lt;MonitoringService&gt;( kernel );
                            x.ConfigureService&lt;ReportingService&gt;( kernel );
                            x.RunAsLocalSystem();
                        } );

                Runner.Host( cfg, args );
            }
        }

        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            kernel.Bind&lt;IWindowsService&gt;().To&lt;MonitoringService&gt;();
            kernel.Bind&lt;IWindowsService&gt;().To&lt;ReportingService&gt;();
            return kernel;
        }
    }

    public static class SyntaxExtensions
    {
        public static void ConfigureService&lt;T&gt;( this IRunnerConfigurator runnerConfigurator, IKernel kernel )
            where T : ServiceBase, IWindowsService
        {
            runnerConfigurator.ConfigureService&lt;T&gt;(
                c =&gt;
                {
                    c.HowToBuildService( serviceName =&gt; kernel.Get&lt;T&gt;() );
                    c.Named( typeof (T).Name );
                    c.WhenStopped( s =&gt; s.Stop() );
                    c.WhenStarted( s =&gt; s.Start() );
                } );
        }
    }

    public interface IWindowsService
    {
        void Start();
        void Stop();
    }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://innovatian.com/2010/05/windows-services-with-ninject-and-topshelf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Build Systems</title>
		<link>http://innovatian.com/2010/05/build-systems/</link>
		<comments>http://innovatian.com/2010/05/build-systems/#comments</comments>
		<pubDate>Sun, 09 May 2010 20:27:15 +0000</pubDate>
		<dc:creator>Ian Davis</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[build systems]]></category>
		<category><![CDATA[rant]]></category>

		<guid isPermaLink="false">http://innovatian.com/?p=396</guid>
		<description><![CDATA[$:&#62;call begin-rant I am impeded and embittered by the current state of builds systems. I need to get ready to make Windows Phone 7 and Silverlight 4 builds, but the tooling doesn&#8217;t have support for them. On a side note, why the heck did I have to install VS2010 Express in order to get the [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>
<pre>$:&gt;call begin-rant</pre>
<blockquote><p>I am impeded and embittered by the current state of builds systems. I need to get ready to make Windows Phone 7 and Silverlight 4 builds, but the tooling doesn&#8217;t have support for them. On a side note, why the heck did I have to install VS2010 Express in order to get the WP7 SDK? #MSFAIL! It is hard to justify staying with builds systems based in XML that are manually edited and impossible to debug. In the short term, I am probably going to create my WP7 and SL4 builds by hand &#8211; I do not say this lightly, I feel sick doing so, but the level of effort to get something working properly is too high for the amount of time I have at the moment.</p></blockquote>
<pre>Disclaimer, below is still a rant, but less so than above.</pre>
<p><p>The state of build systems is incredibly sad at the moment. Open source projects have no choice but to use some open source build tool adding friction to the development of the project &#8211; not because they are open source, but rather because they are poor tools. What choices do we really have &#8211; XML, Ruby, PowerShell, and a UI wrapping one of them; you can name others, but there is no traction on them so far as I can tell. Along with each is a constant ridicule by a particular group touting the magnificence of their own choice in tooling. The UI tools have the added hatred in that they are not free and the disdain of point and click.</p>
<p>Just to make it clear, I am biased, I love FinalBuilder &#8211; a non free UI build tool; but I can&#8217;t use it for open source and the extension model is a pain. I do not want to learn yet another language in order to write my builds scripts, and I absolutely do not want to write XML. This eliminates all of my needs, so I have to sacrifice one of my requirements in order to get the job done.</p>
<p>Below is a list of the major tools available as I currently see them. I know there are many others, but they aren&#8217;t important to me.</p>
<ul>
<li>Language based
<ul>
<li>psake (PowerShell Build Automation Tool)</li>
<li>Rake (Ruby Make)</li>
<li>Fake (F# Make)</li>
<li>BooBs (Boo Build System)</li>
</ul>
</li>
<li>XML Based
<ul>
<li>NAnt  (.NET Build Tool)</li>
<li>MSBuild</li>
</ul>
</li>
<li>Visual Editor
<ul>
<li>FinalBuilder</li>
<li>VisualBuild</li>
</ul>
</li>
</ul>
<p>PowerShell, I wanted to love you, but found you just frustrating to use. I love that you can access .NET libraries, but your debugging and editing sucks. In discussions I have had with others, Ruby&#8217;s niche seems to be rails and DSLs. With PowerShell and Ruby, you have to have their runtime on your machine. Many developers I know won&#8217;t install Ruby on their computers, and I really don&#8217;t want to force users of my open source software to install PowerShell or Ruby &#8211; it feels like a significant failure on my part were I to do so. On the other hand, do users really need to be making builds? Can they just use VS? MSBuild and NAnt, you are dead to me. The nightmares of past attempts to &#8216;debug&#8217; XML haunt me.</p>
<p>I am still in a lose-lose situation. I realize that I am trying to deal with two separate issues that seem to be the root of the problem. First, trying to stay in a .NET environment and not requiring yet another external dependency. Second, the poor tooling. I have been very tempted to write an open source version of FinalBuilder, but most .NET developers I have mentioned it to have asked &#8220;What is FinalBuilder?&#8221; &#8211; which doesn&#8217;t inspire me to invest my time.</p>
<p>Right now, I see two front runners that will emerge: Visual Tools (FinalBuilder, VisualBuild), and Ruby (IronRuby). I think that the aversion to Ruby will push .NET developers to use IronRuby specifically (but this is still an extra install <img src='http://innovatian.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  ). If I am going to use something other than FinalBuilder, I want it to be a real part of my product. I don&#8217;t want a second class build tool. I want something that goes under the same scrutiny as my production code. I want to make my scripts a full part of my work: to refactor, test, debug, review, and version control my build scripts.</p>
<p>Right now, I think I need to learn Ruby, in-depth, and see what can be done. The Albacore rake tasks seem to be a good start, so I will have to see where it leads to. One interesting thing I picked up when evaluating current systems and looking to build my own is that they are really all just consumers of a common data model. If you could create a detailed model of the options available for a particular task, you should theoretically be able to generate psake, rake, fake, build files from the data model.</p>
]]></content:encoded>
			<wfw:commentRss>http://innovatian.com/2010/05/build-systems/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Fibonacci LINQ Sequence Generator Revisited</title>
		<link>http://innovatian.com/2010/05/fibonacci-linq-sequence-generator-revisited/</link>
		<comments>http://innovatian.com/2010/05/fibonacci-linq-sequence-generator-revisited/#comments</comments>
		<pubDate>Tue, 04 May 2010 13:50:19 +0000</pubDate>
		<dc:creator>Ian Davis</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[linq]]></category>

		<guid isPermaLink="false">http://innovatian.com/?p=429</guid>
		<description><![CDATA[It was pointed out that the sequence generator could be written as an infinite sequence to allow .Skip(), .Take(), .ElementAt(), etc. Here is the infinite sequence version. public static class Fibonacci { public static IEnumerable&#60;BigInteger&#62; Generate() { yield return 1; yield return 1; BigInteger n1 = 1, n2 = 1; while(true) { BigInteger n3 = [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>It was pointed out that the sequence generator could be written as an infinite sequence to allow .Skip(), .Take(), .ElementAt(), etc. Here is the infinite sequence version.</p>
<pre class="brush: csharp;">public static class Fibonacci
{
	public static IEnumerable&lt;BigInteger&gt; Generate()
	{
		yield return 1;
		yield return 1;

		BigInteger n1 = 1, n2 = 1;
		while(true)
		{
			BigInteger n3 = n1 + n2;
			n1 = n2;
			n2 = n3;
			yield return n3;
		}
	}
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://innovatian.com/2010/05/fibonacci-linq-sequence-generator-revisited/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WinDgb script when debugging drivers</title>
		<link>http://innovatian.com/2010/05/windgb-script-when-debugging-drivers/</link>
		<comments>http://innovatian.com/2010/05/windgb-script-when-debugging-drivers/#comments</comments>
		<pubDate>Sat, 01 May 2010 18:16:29 +0000</pubDate>
		<dc:creator>Ian Davis</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[windbg]]></category>

		<guid isPermaLink="false">http://innovatian.com/?p=423</guid>
		<description><![CDATA[If you ever happen to be writing a device driver and you want to have WinDbg configured to run a set of scripts, this configuration for WINDBG.INI may be of help. If it doesn&#8217;t mean anything to you, don&#8217;t worry, nothing to see here other than pain. Replace anything in {} with your own paths [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>If you ever happen to be writing a device driver and you want to have WinDbg configured to run a set of scripts, this configuration for <code>WINDBG.INI</code> may be of help. If it doesn&#8217;t mean anything to you, don&#8217;t worry, nothing to see here other than pain. Replace anything in <code>{}</code> with your own paths and file names. This is configured for kernel debugging over 1394.</p>
<p><code>[WinDbg Location]<br />
C:\Program Files\Debugging Tools for Windows (x86)\windbg.exe<br />
[WinDbg CmdLines]<br />
-T "Initial WinDbg Line" -c "SQE;BL"<br />
-T "Default" -Q -QY -y http://msdl.microsoft.com/download/symbols;C:\{PathToBinFiles} -k 1394:channel=44,symlink=Channel -c "SQE;BL;.kdfiles -m \Systemroot\system32\DRIVERS\{YourDriver1}.sys  C:\{PathToBinFiles}\{YourDriver1}.sys;.kdfiles -m \Systemroot\system32\DRIVERS\{YourDriver2}.sys C:\{PathToBinFiles}\{YourDriver2}.sys;.kdfiles"</code></p>
]]></content:encoded>
			<wfw:commentRss>http://innovatian.com/2010/05/windgb-script-when-debugging-drivers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parallel Matrix Multiplication with the Task Parallel Library (TPL)</title>
		<link>http://innovatian.com/2010/03/parallel-matrix-multiplication-with-the-task-parallel-library-tpl/</link>
		<comments>http://innovatian.com/2010/03/parallel-matrix-multiplication-with-the-task-parallel-library-tpl/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 16:17:08 +0000</pubDate>
		<dc:creator>Ian Davis</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[parallel]]></category>
		<category><![CDATA[Threading]]></category>
		<category><![CDATA[TPL]]></category>

		<guid isPermaLink="false">http://innovatian.com/?p=362</guid>
		<description><![CDATA[About I brushed off some old benchmarking code used in my clustering application and decided to see what I can do using today&#8217;s multi-core hardware. When writing computationally intensive algorithms, we have a number of considerations to evaluate. The best (IMHO) algorithms to parallelize are data parallel algorithms without loop carried dependencies. You may think [...]]]></description>
			<content:encoded><![CDATA[<p></p><h2>About</h2>
<p>I brushed off some old benchmarking code used in my clustering application and decided to see what I can do using today&#8217;s multi-core hardware. When writing computationally intensive algorithms, we have a number of considerations to evaluate. The best (IMHO) algorithms to parallelize are <a href="http://en.wikipedia.org/wiki/Data_parallelism">data parallel</a> algorithms without loop carried dependencies.</p>
<p>You may think nothing is special about matrix multiplication, but it actually points out a couple of performance implications when writing CLR applications. I originally wrote seven different implementations of matrix multiplication in C# &#8211; that&#8217;s right, <em>seven</em>.</p>
<ul>
<li>Dumb</li>
<li>Standard</li>
<li>Single</li>
<li>Unsafe Single</li>
<li>Jagged</li>
<li>Jagged from C++</li>
<li>Stack Allocated</li>
</ul>
<h3>Dumb: double[N,N], real type: float64[0...,0...]</h3>
<p>The easiest way to do matrix multiplication is with a .NET multidimensional array with i,j,k ordering in the loops. The problems are twofold. First, the i,j.k ordering accesses memory in a hectic fashion causing data in varied locations to be pulled in. Second, it is using a multidimensional array. Yes, the .NET multidimensional array is convenient, but <em>it is very slow</em>. Let&#8217;s look at the C# and IL</p>
<p>C#:</p>
<pre class="brush: csharp;">C[i, j] += A[i, k] * B[k, j];</pre>
<p>IL of C#:</p>
<pre class="brush: plain;">ldloc.s i
ldloc.s jcall instance float64&amp;amp; float64[0...,0...]::Address(int32, int32)
dup
ldobj float64
ldloc.1
ldloc.s i
ldloc.s k
call instance float64 float64[0...,0...]::Get(int32, int32)
ldloc.2
ldloc.s k
ldloc.s j
call instance float64 float64[0...,0...]::Get(int32, int32)
mul
add
stobj float64</pre>
<p>If you notice the ::Address and ::Get parts, these are method calls! Yes, when you use a multidimensional array, you are using a class instance. So every access, assignment, and read incurs the cost of a method call. When you are dealing with and N^3 algorithm, that is N^3 method calls making this implementation much slower than other methods.</p>
<h3>Standard: double[N,N], real type float64[0...,0...]</h3>
<p>This implementation rearranges the loop ordering to i,k,j in order to optimize memory access to the arrays. No other changes are made from the dumb implementation. The Standard implementation is what is used for the base of all other multidimensional implementations.</p>
<h3>Single: double[N * N], real type float64[]</h3>
<p>Instead of creating a multidimensional array, we create a single block of memory. The float64[] type is a block of memory instead of a class. Downside here is that we have to calculate all offsets manually.</p>
<h3>Unsafe Single, real type float64[]</h3>
<p>This method is the same as the single dimensional array, except that the pointers to the arrays are fixed and pointers are used in unsafe C#.</p>
<h3>Jagged, double[N][N], real type float64[][]</h3>
<p>This is the same implementation as standard, except that we use arrays of arrays instead of a multidimensional array. It takes an extra step to initialize, but it is a series of blocks to raw memory eliminating the method call overhead. It is typically 30% faster that the multidimensional array.</p>
<h3>Jagged from C++, double[N][N], real type float64[][]</h3>
<p>This is a bit more difficult. When writing these algorithms, we let the JIT compiler optimize for us. The C++ compiler is unfortunately a lot better, but it isn&#8217;t real-time. I ported the code from the jagged implementation to C++/CLI and enabled heavy optimization. Once compiled, I disassembled the dll and converted the IL to C#. The result is this implementation which is harder to read, but it is really fast.</p>
<h3>Stack Allocated, stackalloc double[N * N], real type float64*</h3>
<p>This implementation utilizes the rarely used stackalloc keyword. Using this implementation is very problematic as you may get a StackOverflowException depending on your current stack usage.</p>
<h2>Enough, what does it mean?!</h2>
<p>Because of the way matrix multiplication works, we can multiply a row without impacting the result of other row multiplications. That&#8217;s right, we have a data parallel algorithm! We need to identify the chucks of work to parallelize.</p>
<p>We can go about this in a couple different ways. First, manual threading. Second, using the ThreadPool. Third, using the new task parallel library. In this post I am going to use the third option as it makes things very nice for us. We don&#8217;t want to deal with scheduling or synchronization ourselves.</p>
<h2>Partitioning</h2>
<p>We can do a couple of different schemes. We can use ParallelFor and add each rows multiplication to the list of work to be done. This is very easy</p>
<pre class="brush: csharp;">for ( int i = 0; i &lt; N; i++ )
{
	for ( int k = 0; k &lt; N; k++ )
	{
		for ( int j = 0; j &lt; N; j++ )
		{
			double[] Ci = C[i];
			Ci[j] = ( A[i][k] * B[k][j] ) + Ci[j];
		}
	}
}</pre>
<p>Becomes:</p>
<pre class="brush: csharp;">Parallel.For( 0, N, i =&gt;
					{
						for ( int k = 0; k &lt; N; k++ )
						{
							for ( int j = 0; j &lt; N; j++ )
							{
								double[] Ci = C[i];
								Ci[j] = ( A[i][k] * B[k][j] ) + Ci[j];
							}
						}
					} );</pre>
<p>The bad news is that this can be too granular. Another way to look at it is over parallelization. The overhead of scheduling and threading hurts our performance. This  method does give us the smallest synchronization time. In the worst case, all rows are calculated except for one, which is started at the completion of the penultimate calculation. So the worst case is we wait for a single row.</p>
<p>If we are willing to put in more work, we can optimize the row striping to group the calculations into groups of rows in order to minimize synchronization and threading overhead. Looking at the number of processors available, we can make the number of chunks relative to the number of processors.</p>
<pre class="brush: csharp;">IEnumerable&lt;Tuple&lt;int, double[][]&gt;&gt; PartitionData( int N, double[][] A )
{
	int pieces = ( ( N % ChunkFactor ) == 0 )
					 ? N / ChunkFactor
					 : ( (int) ( ( N ) / ( (float) ChunkFactor ) ) + 1 );

	int remaining = N;
	int currentRow = 0;

	while ( remaining &gt; 0 )
	{
		if ( remaining &lt; ChunkFactor )
		{
			ChunkFactor = remaining;
		}

		remaining = remaining - ChunkFactor;
		var ai = new double[ChunkFactor][];
		for ( int i = 0; i &lt; ChunkFactor; i++ )
		{
			ai[i] = A[currentRow + i];
		}

		int oldRow = currentRow;
		currentRow += ChunkFactor;
		yield return new Tuple&lt;int, double[][]&gt;( oldRow, ai );
	}
}</pre>
<p>Here we partner the row to start on in the result matrix C with the pointer to the head of the row of A to start on. We could use the jagged implementation, but for pure speed, I am sticking with the fastest implementation I have:</p>
<pre class="brush: csharp;">void Multiply( Tuple&lt;int, double[][]&gt; A, double[][] B, double[][] C )
{
	int size = A.Item2.GetLength( 0 );
	int cols = B[0].Length;
	double[][] ai = A.Item2;

	int i = 0;
	int offset = A.Item1;
	do
	{
		int k = 0;
		do
		{
			int j = 0;
			do
			{
				double[] ci = C[offset];
				ci[j] = ( ai[i][k] * B[k][j] ) + ci[j];
				j++;
			} while ( j &lt; cols );
			k++;
		} while ( k &lt; cols );
		i++;
		offset++;
	} while ( i &lt; size );
}</pre>
<p>It is a little more complicated to write this heavily optimized version, but it pays off. To actually do the multiplication is very simple now using the TPL:</p>
<pre class="brush: csharp;">Parallel.ForEach( PartitionData( N, A ), item =&gt; Multiply( item, B, C ) );</pre>
<h2>Enough! Show me the numbers!</h2>
<p>OK. You have patiently waited and I will give you the results. The parallel numbers are for my quad core machine with 4GB RAM. The Y-Axis is millions of algorithmic steps per second. The X-Axis is the matrix size.</p>
<p>First, we can look at the performance of the various single-threaded implementations. As you can see, there is a 5x difference between the easiest way and my most optimized implementation that does not use unsafe code. So if you need to multiply matrices &#8211; use jagged arrays!</p>
<div id="attachment_379" class="wp-caption alignnone" style="width: 658px">
	<a href="http://innovatian.com/wp-content/uploads/2010/03/SingleThreaded_All.png"><img class="size-full wp-image-379" title="SingleThreaded_All" src="http://innovatian.com/wp-content/uploads/2010/03/SingleThreaded_All.png" alt="Single Threaded Matrix Multiplication Performance" width="658" height="418" /></a>
	<p class="wp-caption-text">Single Threaded Matrix Multiplication Performance</p>
</div>
<p>The bulge you see on the left when the matrix size is small is the result of the Cache Memory Swap Die (CMSD) envelope. When the data size is small, the system leverages cache which is the fastest. When the data becomes to large, it has to store the data in main memory which is still pretty fast. What you don&#8217;t see is the swap and die levels. When the data set becomes very large, the system must use the swap file and store data on disk which is levels of magnitude slower than memory. When the data set becomes too large, the hard drive thrashes and you are constantly paging data in. At this point, your performance dies.</p>
<p>There is a problem with the chunking. Depending on how many pieces, the load of the processors, and the worst case job completion, the performance can vary for the chunking implementation. Below you can see the relative performance of the optimized chunking implementation against the simple parallelization and my heuristic.</p>
<p>I ran the chunking algorithm with many different granule sizes and recorded the best and worst values to give a performance range. The overlap between actual and max is the CPU being used by other processes out of my control &#8211; one of the issues with granule calculation is that you can&#8217;t predict the future. One possible thing we could do is to utilize coroutines to adjust the granule size as time goes on in oder to adjust to machine load.</p>
<div id="attachment_386" class="wp-caption alignnone" style="width: 636px">
	<a href="http://innovatian.com/wp-content/uploads/2010/03/Parallel_All.png"><img class="size-full wp-image-386" title="Parallel_All" src="http://innovatian.com/wp-content/uploads/2010/03/Parallel_All.png" alt="Parallel Matrix Multiplication Performance Comparison" width="636" height="357" /></a>
	<p class="wp-caption-text">Parallel Matrix Multiplication Performance Comparison</p>
</div>
<p>At best, we are calculating over 4x faster than the best single-threaded implementation. Yes, better than 4x with 4 cores. We are taking advantage of caching when we row stripe the data. This performance becomes even more significant when running this code across a cluster &#8211; you can get over 5x with 4 machines. Unfortunately, I never had the chance to work with four quad core machines in a cluster to test out a massively parallel implementation.</p>
<div id="attachment_387" class="wp-caption alignnone" style="width: 660px">
	<a href="http://innovatian.com/wp-content/uploads/2010/03/All_Compared.png"><img class="size-full wp-image-387" title="All_Compared" src="http://innovatian.com/wp-content/uploads/2010/03/All_Compared.png" alt="Parallel vs Single Threaded Matrix Multiplication" width="660" height="418" /></a>
	<p class="wp-caption-text">Parallel vs Single Threaded Matrix Multiplication</p>
</div>
<h2>Summary</h2>
<p>As you can see, small changes in algorithm implementation can have quite adverse effects on performance. Also, parallelizing data parallel algorithms can be incredibly simple and provide a great performance boost with very little effort.</p>
<p>I would love to do some work showing the parallelization of wavefront, four square, and other data dependency schemes and their effect on performance and the effort needed to parallelize them, but we will see how much time I have. Another fun problem might be a massively parallel N-queens or Knights tour solver.</p>
<p>You can find all of the source code for these benchmarks on my <a href="http://github.com/innovatian/innovatian.blog/tree/master/source/MatrixMultipplication/">blog&#8217;s GitHub page</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://innovatian.com/2010/03/parallel-matrix-multiplication-with-the-task-parallel-library-tpl/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Ninject.Extensions.Interception 2.0.1 Released</title>
		<link>http://innovatian.com/2010/03/ninject-extensions-interception-2-0-1-released/</link>
		<comments>http://innovatian.com/2010/03/ninject-extensions-interception-2-0-1-released/#comments</comments>
		<pubDate>Fri, 19 Mar 2010 14:22:15 +0000</pubDate>
		<dc:creator>Ian Davis</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[interception]]></category>
		<category><![CDATA[Ninject]]></category>

		<guid isPermaLink="false">http://innovatian.com/?p=345</guid>
		<description><![CDATA[I have just pushed new binaries and tagged the release on GitHub. There was confusion on how to deal with automatic module loading with the release that contained both proxy modules &#8211; every mailing list question pertained to this confusion, so it needed to be resolved. I have removed this release in favor of having [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I have just pushed new binaries and tagged the release on GitHub. There <a href="http://github.com/idavis/ninject.extensions.interception/issues/closed#issue/1">was confusion</a> on how to deal with automatic module loading with the release that contained both proxy modules &#8211; every mailing list question pertained to this confusion, so it needed to be resolved. I have removed this release in favor of having the user download the extension with the dynamic proxy implementation of their choice.</p>
<p>There are two new projects: Ninject.Extensions.Interception.LinFu and Ninject.Extensions.Interception.DynamicProxy2 that contain the necessary classes for each dynamic proxy implementation.</p>
<p>This update also introduces LinFu.DynamicProxy for Silverlight 3.0 support.</p>
<p>You can download the latest release 2.0.1.0 from the GitHub <a href="http://github.com/idavis/ninject.extensions.interception/downloads">project downloads page</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://innovatian.com/2010/03/ninject-extensions-interception-2-0-1-released/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Ninject.Extensions.Interception Part 2 : Working with Interceptors</title>
		<link>http://innovatian.com/2010/03/using-ninject-extensions-interception-part-2-working-with-interceptors/</link>
		<comments>http://innovatian.com/2010/03/using-ninject-extensions-interception-part-2-working-with-interceptors/#comments</comments>
		<pubDate>Sat, 13 Mar 2010 02:59:56 +0000</pubDate>
		<dc:creator>Ian Davis</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[interception]]></category>
		<category><![CDATA[Ninject]]></category>

		<guid isPermaLink="false">http://innovatian.com/?p=312</guid>
		<description><![CDATA[Overview In Part 1 we covered the basics of the extension and introduced the IInterceptor interface. Now we can move more in depth and look at the interceptor system composed of Custom Interceptors Interception via Attributes With these, we can define a rich set of interception capabilities in our applications. Custom Interceptors The base of [...]]]></description>
			<content:encoded><![CDATA[<p></p><h2>Overview</h2>
<p>In <a href="http://innovatian.com/2010/03/using-ninject-extensions-interception-part-1-the-basics">Part 1</a> we covered the basics of the extension and introduced the <a href="http://github.com/idavis/ninject.extensions.interception/blob/master/source/Ninject.Extensions.Interception/IInterceptor.cs">IInterceptor</a> interface. Now we can move more in depth and look at the interceptor system composed of</p>
<ul>
<li>Custom Interceptors</li>
<li>Interception via Attributes</li>
</ul>
<p>With these, we can define a rich set of interception capabilities in our applications.</p>
<h3>Custom Interceptors</h3>
<p>The base of the binding interception is the very simple IInterceptor interface:</p>
<pre class="brush: csharp;">public interface IInterceptor
{
	/// &lt;summary&gt;
	/// Intercepts the specified invocation.
	/// &lt;/summary&gt;
	/// &lt;param name=&quot;invocation&quot;&gt;The invocation to intercept.&lt;/param&gt;
	void Intercept( IInvocation invocation );
}</pre>
<p>The idea behind and IInterceptor is to take the place of some kind of action. This is very simple and makes creating an custom interceptor very easy. In order to do it properly, however, you must use the IInvocation object you are given. Below is the most basic interceptor that you can create which resumes execution of the real method.</p>
<pre class="brush: csharp;">public class MinimalInterceptor : IInterceptor
{
    public void Intercept( IInvocation invocation )
    {
        invocation.Proceed();
    }
}</pre>
<p>The invocation.Proceed() call is crucial! Since a call can have multiple interceptors, we need a way to hand off execution to the next downstream interceptor. The Proceed() call will either invoke the next interceptor in the chain, or invoke the target intercepted method if their are no more interceptors.</p>
<p>The extension currently ships with three interceptors</p>
<ul>
<li><a href="http://github.com/idavis/ninject.extensions.interception/blob/master/source/Ninject.Extensions.Interception/SimpleInterceptor.cs">SimpleInterceptor</a></li>
<li><a href="http://github.com/idavis/ninject.extensions.interception/blob/master/source/Ninject.Extensions.Interception/ActionInterceptor.cs">ActionInterceptor</a></li>
<li><a href="http://github.com/idavis/ninject.extensions.interception/blob/master/source/Ninject.Extensions.Interception/AutoNotifyPropertyChangedInterceptor.cs">AutoNotifyPropertyChangedInterceptor</a> (covered in <a href="http://innovatian.com/2010/01/ninject-extensions-interception-and-iautonotifypropertychanged-ianpc/">IANPC post</a>)</li>
</ul>
<h4>SimpleInterceptor</h4>
<p>The SimpleInterceptor provides before and after execution hooks that you can override. We can create a simple timing interceptor by overriding the hooks and writing to the Trace object:</p>
<pre class="brush: csharp;">public class TimingInterceptor : SimpleInterceptor
{
	readonly Stopwatch _stopwatch = new Stopwatch();

	protected override void BeforeInvoke(IInvocation invocation)
	{
		_stopwatch.Start();
	}

	protected override void AfterInvoke(IInvocation invocation)
	{
		_stopwatch.Stop();
		string message = string.Format( &quot;Execution of {0} took {1}.&quot;,
										invocation.Request.Method,
										_stopwatch.Elapsed );
		Trace.WriteLine(message);
		_stopwatch.Reset();
	}
}</pre>
<p>There is a lot more that can be done with the IInvocation object. You should really take a minute to look over the interface and see some of the information available. I have also included IProxyRequest as there is a lot of good information there accessible from IInvocation:</p>
<pre class="brush: csharp;">public interface IInvocation
{
    /// &lt;summary&gt;
    /// Gets the request, which describes the method call.
    /// &lt;/summary&gt;
    IProxyRequest Request { get; }

    /// &lt;summary&gt;
    /// Gets the chain of interceptors that will be executed before the target method is called.
    /// &lt;/summary&gt;
    IEnumerable&lt;IInterceptor&gt; Interceptors { get; }

    /// &lt;summary&gt;
    /// Gets or sets the return value for the method.
    /// &lt;/summary&gt;
    object ReturnValue { get; set; }

    /// &lt;summary&gt;
    /// Continues the invocation, either by invoking the next interceptor in the chain, or
    /// if there are no more interceptors, calling the target method.
    /// &lt;/summary&gt;
    void Proceed();
}</pre>
<pre class="brush: csharp;">public interface IProxyRequest
{
    /// &lt;summary&gt;
    /// Gets the kernel that created the target instance.
    /// &lt;/summary&gt;
    IKernel Kernel { get; }

    /// &lt;summary&gt;
    /// Gets the context in which the target instance was activated.
    /// &lt;/summary&gt;
    IContext Context { get; }

    /// &lt;summary&gt;
    /// Gets or sets the proxy instance.
    /// &lt;/summary&gt;
    object Proxy { get; set; }

    /// &lt;summary&gt;
    /// Gets the target instance.
    /// &lt;/summary&gt;
    object Target { get; }

    /// &lt;summary&gt;
    /// Gets the method that will be called on the target instance.
    /// &lt;/summary&gt;
    MethodInfo Method { get; }

    /// &lt;summary&gt;
    /// Gets the arguments to the method.
    /// &lt;/summary&gt;
    object[] Arguments { get; }

    /// &lt;summary&gt;
    /// Gets the generic type arguments for the method.
    /// &lt;/summary&gt;
    Type[] GenericArguments { get; }

    /// &lt;summary&gt;
    /// Gets a value indicating whether the request has generic arguments.
    /// &lt;/summary&gt;
    bool HasGenericArguments { get; }
}</pre>
<p>Given this information you can implement <a href="http://github.com/idavis/ninject.extensions.interception/blob/master/source/Ninject.Extensions.Interception/SimpleInterceptor.cs">simple</a> or more <a href="http://github.com/idavis/ninject.extensions.interception/blob/master/source/Ninject.Extensions.Interception/AutoNotifyPropertyChangedInterceptor.cs">complex</a> interceptors capable of utilizing a large amount of information to do the job.</p>
<h4>ActionInterceptor</h4>
<p>The ActionInterceptor takes an Action&lt;IInvocation&gt; in its .ctor</p>
<pre class="brush: csharp;">ActionInterceptor interceptor =
    new ActionInterceptor( invocation =&gt; Console.WriteLine(&quot;Executing {0}.&quot;, invocation.Request.Method) );</pre>
<p>If you want a quick spike and don&#8217;t want to define a full interceptor, the ActionInterceptor is very handy.</p>
<h3>Multiple Interceptors</h3>
<p>You have seen how to attach interceptors via a static registry (IKernel extensions for specific methods) and attaching them using bindings. Now, what may have not been obvious, is that you can attach multiple interceptors to a given binding.</p>
<pre class="brush: csharp;">[Fact]
public void CanAttachMultipleInterceptors()
{
    using (StandardKernel kernel = CreateDefaultInterceptionKernel())
    {
        var binding = kernel.Bind&lt;FooImpl&gt;().ToSelf();
        binding.Intercept().With&lt;FlagInterceptor&gt;();
        binding.Intercept().With&lt;CountInterceptor&gt;();

        var foo = kernel.Get&lt;FooImpl&gt;();

        Assert.False(FlagInterceptor.WasCalled);
        Assert.Equal(0, CountInterceptor.Count);

        foo.Foo(); // call method to invoke interceptors

        Assert.True(FlagInterceptor.WasCalled);
        Assert.Equal(1, CountInterceptor.Count);
    }
}</pre>
<p>We can also change the order in which the interceptors are executed:</p>
<pre class="brush: csharp;">[Fact]
public void CanAttachMultipleInterceptors()
{
    using (StandardKernel kernel = CreateDefaultInterceptionKernel())
    {
        var binding = kernel.Bind&lt;FooImpl&gt;().ToSelf();
        binding.Intercept().With&lt;FlagInterceptor&gt;().InOrder(2);
        binding.Intercept().With&lt;CountInterceptor&gt;().InOrder(1);
        binding.Intercept().With&lt;TimingInterceptor&gt;().InOrder(3);
        // ...
    }
}</pre>
<h3>Interception via Attributes</h3>
<p>If you do not want to use the binding syntax to specify interceptors, you can use attributes to mark specific classes for interception. The <a href="http://github.com/idavis/ninject.extensions.interception/blob/master/source/Ninject.Extensions.Interception/Attributes/InterceptAttribute.cs">[Intercept]</a> attribute is an abstract attribute for you to extend and use on classes and methods. When a derived attribute is applied on a class, it will register interception on all virtual methods of that class. If you wish to disable interception for a particular method, you can apply the <a href="http://github.com/idavis/ninject.extensions.interception/blob/master/source/Ninject.Extensions.Interception/Attributes/DoNotInterceptAttribute.cs">[DoNotIntercept]</a> attribute. If you only want to intercept a particular method in a class, just apply the derived attribute to that single method.</p>
<p>You must extend the base <a href="http://github.com/idavis/ninject.extensions.interception/blob/master/source/Ninject.Extensions.Interception/Attributes/InterceptAttribute.cs">[Intercept]</a> attribute as it needs to know what interceptor to attach. You specify this by overriding the CreateInterceptor method. We can use the TimingInterceptor used previously to create a  attribute and apply it to a simple class.</p>
<pre class="brush: csharp;">public class TimeAttribute : InterceptAttribute
{
    public override IInterceptor CreateInterceptor( IProxyRequest request )
    {
        return request.Context.Kernel.Get&lt;TimingInterceptor&gt;();
    }
}

public class ObjectWithMethodInterceptor
{
    [Time] // intercepted
    public virtual void Foo()
    {
    }

    // not intercepted
    public virtual void Bar()
    {
    }
}

[Time]
public class ObjectWithClassInterceptor
{
    // intercepted
    public virtual void Foo()
    {
    }

    [DoNotIntercept] // not intercepted
    public virtual void Bar()
    {
    }

    // not intercepted - method is not virtual
    public void Baz()
    {
    }
}</pre>
<p>There is one other part of the interception attributes that is also supported from the binding configuration: Order. When you attach interception attributes, you can specify the order of the interceptor. You do not need to specify this in your custom attributes; it is handled by the injection system. All you have to do is specify the order in the attribute usage.</p>
<pre class="brush: csharp;">[Count(Order = 1)]
public class ObjectWithOrderedInterceptors
{
    [Flag(Order = 0)]
    public virtual void Foo()
    {
    }

    public virtual void Baz()
    {
    }
}</pre>
<p>One thing you may have noticed is that I used two different interceptor types. This is perfectly valid. All virtual calls of ObjectWithOrderedInterceptors will be counted. In addition, calls to Foo will also set a flag and the flag will be set before the count interceptor has a chance to run.</p>
<p>This can be important if you are trying to time calls with an interceptor; yes, the interception system is going to skew your results either way, but the amount you are over can vary drastically if your timing interceptor is first or last in the chain.</p>
<h2>Conclusion</h2>
<p>That pretty much covers the Ninject.Extensions.Interception interceptors. Using this foundation, you can create just about any type of interception scheme you can think of.</p>
]]></content:encoded>
			<wfw:commentRss>http://innovatian.com/2010/03/using-ninject-extensions-interception-part-2-working-with-interceptors/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Using Ninject.Extensions.Interception Part 1 : The Basics</title>
		<link>http://innovatian.com/2010/03/using-ninject-extensions-interception-part-1-the-basics/</link>
		<comments>http://innovatian.com/2010/03/using-ninject-extensions-interception-part-1-the-basics/#comments</comments>
		<pubDate>Thu, 11 Mar 2010 06:45:07 +0000</pubDate>
		<dc:creator>Ian Davis</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[interception]]></category>
		<category><![CDATA[Ninject]]></category>

		<guid isPermaLink="false">http://innovatian.com/?p=278</guid>
		<description><![CDATA[About the Extension The Ninject interception extension relies on the DynamicProxy implementations of Castle and LinFu to generate proxy instances. The interception extension is essentially an abstraction of the proxying components leveraging Ninject&#8217;s feature set along with interception utilities. Enabling the Extension There are two ways to enable the extension. The easiest way is to [...]]]></description>
			<content:encoded><![CDATA[<p></p><h2>About the Extension</h2>
<p>The Ninject interception extension relies on the DynamicProxy implementations of Castle and LinFu to generate proxy instances. The interception extension is essentially an abstraction of the proxying components leveraging Ninject&#8217;s feature set along with interception utilities.</p>
<h2>Enabling the Extension</h2>
<p>There are two ways to enable the extension. The easiest way is to use Ninject&#8217;s automatic extension loading mechanism. By default Ninject will load all modules from assemblies that match the pattern Ninject.Extensions.*.dll in the same directory as the Ninject assembly. This works fine except that we have multiple options for the DynamicProxy implementation.</p>
<p>The .NET 3.5 release contains both the LinFuModule and the DynamicProxy2Module. If you have automatic extension loading enabled, it will load both modules. To make it easier, there are two other .NET 3.5 releases that either contain the LinFuModule, or the DynamicProxy2Module. All other platform releases only have one module: Mono-&gt;LinFu, Silverlight 3-&gt;Castle.</p>
<p>If you have automatic extension loading disabled, there is no need to worry, you can simply pass one of the modules into the kernel .ctor as usual. Now that we have the extension loaded, it is time to start using the extension.</p>
<h2>Extensibility Provided</h2>
<p>There are three main ways that that you can use the extension:</p>
<ol>
<li>Interception on the Binding</li>
<li>Method Interception</li>
<li>Facilities Provided by the Extension</li>
</ol>
<p>All of the binding capability of the extension are based on extension methods on IKernel and IBindingSyntax. The extensions for IKernel provide method interception where you can intercept very specific calls when instances of a type are requested. The IBindingSyntax extensions provide class level interception using a specific IInterceptor implementation.</p>
<h3><span style="color: #ff0000;">*** Important Note ***</span></h3>
<p>Your methods/properties to be intercepted must be virtual! The DynamicProxy implementations are still bound by inheritance rules. If you look at all examples in this series, all intercepted members are virtual.</p>
<h3>Interception on the Binding</h3>
<p>The base of the binding interception is the very simple IInterceptor interface:</p>
<pre class="brush: csharp;">    public interface IInterceptor
    {
        /// &lt;summary&gt;
        /// Intercepts the specified invocation.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;invocation&quot;&gt;The invocation to intercept.&lt;/param&gt;
        void Intercept( IInvocation invocation );
    }</pre>
<p>In order to provide class level interception, you must create a binding.</p>
<pre class="brush: csharp;">kernel.Bind&lt;ViewModel&gt;().ToSelf().Intercept().With&lt;FlagInterceptor&gt;();</pre>
<p>The Intercept() extension creates a hint inside the kernel that when this binding is used, that we need to look into the proxying strategies. The With&lt;T&gt;() call declares the IInterceptor to apply with this binding. You can also supply an instance in the With&lt;T&gt;() call in order to pass it a configured interceptor.</p>
<pre class="brush: csharp;">ActionInterceptor interceptor =
    new ActionInterceptor( invocation =&gt; Console.WriteLine(&quot;Executing!&quot;) );
kernel.Bind&lt;ViewModel&gt;().ToSelf().Intercept().With( interceptor );</pre>
<h3>Method Interception</h3>
<p>Using method interception, for a given method or property, you can replace, wrap, prepend, or append functionality. Remember, these are provided as extension methods on IKernel giving you the following calls from an IKernel instance:</p>
<pre class="brush: csharp;">IAdviceTargetSyntax Intercept( Predicate&lt;IProxyRequest&gt; predicate )

void AddMethodInterceptor( MethodInfo method, Action&lt;IInvocation&gt; action )

void InterceptReplace&lt;T&gt;( Expression&lt;Action&lt;T&gt;&gt; methodExpr,
        Action&lt;IInvocation&gt; action )

void InterceptAround&lt;T&gt;( Expression&lt;Action&lt;T&gt;&gt; methodExpr,
       Action&lt;IInvocation&gt; beforeAction,
       Action&lt;IInvocation&gt; afterAction )

void InterceptBefore&lt;T&gt;( Expression&lt;Action&lt;T&gt;&gt; methodExpr,
       Action&lt;IInvocation&gt; action )

void InterceptAfter&lt;T&gt;( Expression&lt;Action&lt;T&gt;&gt; methodExpr,
       Action&lt;IInvocation&gt; action )

void InterceptReplaceGet&lt;T&gt;( Expression&lt;Func&lt;T, object&gt;&gt; propertyExpr,
       Action&lt;IInvocation&gt; action )

void InterceptAroundGet&lt;T&gt;( Expression&lt;Func&lt;T, object&gt;&gt; propertyExpr,
       Action&lt;IInvocation&gt; beforeAction,
       Action&lt;IInvocation&gt; afterAction )

void InterceptBeforeGet&lt;T&gt;( Expression&lt;Func&lt;T, object&gt;&gt; propertyExpr,
        Action&lt;IInvocation&gt; action )

void InterceptAfterGet&lt;T&gt;( Expression&lt;Func&lt;T, object&gt;&gt; propertyExpr,
        Action&lt;IInvocation&gt; action )

void InterceptReplaceSet&lt;T&gt;( Expression&lt;Func&lt;T, object&gt;&gt; propertyExpr,
        Action&lt;IInvocation&gt; action )

void InterceptAroundSet&lt;T&gt;( Expression&lt;Func&lt;T, object&gt;&gt; propertyExpr,
        Action&lt;IInvocation&gt; beforeAction,
        Action&lt;IInvocation&gt; afterAction )

void InterceptBeforeSet&lt;T&gt;( Expression&lt;Func&lt;T, object&gt;&gt; propertyExpr,
        Action&lt;IInvocation&gt; action )

void InterceptAfterSet&lt;T&gt;( Expression&lt;Func&lt;T, object&gt;&gt; propertyExpr,
        Action&lt;IInvocation&gt; action )</pre>
<p>For example:</p>
<pre class="brush: csharp;">public class Foo : IFoo
{
    public virtual void ThrowsAnError()
    {
        throw new Exception();
    }
}

public class MethodTests
{
    public void NoOpASingleMethod()
    {
        Kernel.Bind&lt;Foo&gt;().ToSelf();
        Kernel.InterceptReplace&lt;Foo&gt;(foo =&gt; foo.ThrowsAnError(), invocation =&gt; {} );
        var foo = Kernel.Get&lt;Foo&gt;();
        foo.ThrowsAnError(); // Nothing happens
    }
}</pre>
<p>One key to note is that the interception is for the implementing type, not for the service that the bindings are configured for. For example, there will be no interceptor attached when we configure the interception on the interface:</p>
<pre class="brush: csharp;">public void NoInterceptionPerformed()
{
    Kernel.Bind&lt;IFoo&gt;().To&lt;Foo&gt;();
    Kernel.InterceptReplace&lt;IFoo&gt;(foo =&gt; foo.ThrowsAnError(), invocation =&gt; {} );
    var foo = Kernel.Get&lt;IFoo&gt;();
    foo.ThrowsAnError(); // exception is thrown as usual
}
</pre>
<h3>Facilities Provided by the Extension</h3>
<p>The extension provides a couple of utility mechanisms to aid programmers. As mention the a <a href="http://innovatian.com/2010/01/ninject-extensions-interception-and-iautonotifypropertychanged-ianpc/">previous blog post</a>, the extension supplies an automatic INotifyPropertyChanged implementation for your view model classes.</p>
<p>If you also take a look back to the block posts on <a href="http://innovatian.com/2009/07/weak-proxies-2/">weak proxies</a> and <a href="http://innovatian.com/2009/08/weak-proxy-factory-2/">weak proxy factories</a>, this functionality is currently being worked into the extension and will be presented in a future blog post.</p>
<h2>Conclusion</h2>
<p>Now that we have covered the basics with the interception extension, we can move into more advanced topics such at attaching multiple proxies, proxy ordering, and writing custom interceptors in the next post.</p>
]]></content:encoded>
			<wfw:commentRss>http://innovatian.com/2010/03/using-ninject-extensions-interception-part-1-the-basics/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Ninject.Extensions.Conventions Preview</title>
		<link>http://innovatian.com/2010/02/ninject-extensions-conventions-preview/</link>
		<comments>http://innovatian.com/2010/02/ninject-extensions-conventions-preview/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 19:26:09 +0000</pubDate>
		<dc:creator>Ian Davis</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Conventions]]></category>
		<category><![CDATA[Ninject]]></category>

		<guid isPermaLink="false">http://innovatian.com/?p=262</guid>
		<description><![CDATA[I have been playing with the Ninject conventions binding extension syntax and usage model. It was originally based on the StructureMap assembly scanner, but I want to use the API in a different fashion. I have been working on making the API more like LINQ in the way you think and use it. Here is [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I have been playing with the <a href="http://ninject.org">Ninject</a> <a href="http://github.com/idavis/ninject.extensions.conventions">conventions binding extension</a> syntax and usage model. It was originally based on the <a href="http://structuremap.sourceforge.net/">StructureMap</a> assembly scanner, but I want to use the API in a different fashion.</p>
<p>I have been working on making the API more like LINQ in the way you think and use it. Here is a sampling of the new API that I am testing. Remember, you would never bind like this, ideally you would set up a few different scans to bind everything the way you want it.</p>
<pre class="brush: csharp;">IKernel kernel = new StandardKernel();
kernel.Scan(
	x =&gt;
	{
		// set up the source collection of types to process
		x.FromCallingAssembly();
		x.From( from assembly in AppDomain.CurrentDomain.GetAssemblies()
				from type in assembly.GetExportedTypes()
				select type );
		x.FromAssemblyContaining&lt;IGenericView&gt;();
		x.FromAssembliesInPath( &quot;.&quot; );
		x.FomAssembliesMatching( &quot;*.Model.dll&quot; );
		x.FromAssemblyContaining(new[] {typeof (IGenericView), typeof (StringView)});

		// Filter out what you want
		x.Where( type =&gt; !type.IsAbstract );
		x.WhereTypeIsInNamespace( &quot;Base.Model&quot; );
		x.WhereTypeIsInNamespaceOf&lt;StringView&gt;();
		x.WhereTypeIsNotInNamespace( &quot;Base.Test&quot; );
		x.WhereTypeIsNotInNamespaceOf&lt;StandardKernel&gt;();
		x.WhereTypeInheritsFrom&lt;IGenericView&gt;();

		// Exclude items even if they match your Where criteria
		x.Excluding&lt;INinjectSettings&gt;();
		x.Excluding( new[] {typeof (IServiceProvider), typeof (IInitializable)} );

		// Include items whether or not they match your Where criteria
		x.Including&lt;DefaultView&gt;();

		// Tell the scanner how to determine bindings
		x.BindWithDefaultConventions();

		// Declare the binding scope for scanned members
		x.InTransientScope();
	} );</pre>
<p>Some API calls will not be available on all platforms due to security restrictions of course.</p>
]]></content:encoded>
			<wfw:commentRss>http://innovatian.com/2010/02/ninject-extensions-conventions-preview/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
