<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Andrew Rea</title>
    <link>http://www.andrewrea.co.uk/blog/</link>
    <description>A Developer On A Few Platforms (C#, JAVA, ASP.NET, C++, ACTION SCRIPT)</description>
    <language>en-us</language>
    <copyright>Andrew Rea</copyright>
    <lastBuildDate>Mon, 15 Mar 2010 22:15:47 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>email@andrewrea.co.uk</managingEditor>
    <webMaster>email@andrewrea.co.uk</webMaster>
    <item>
      <trackback:ping>http://www.andrewrea.co.uk/blog/Trackback.aspx?guid=f0342a2a-75f2-4576-bdc8-8dfc801125f1</trackback:ping>
      <pingback:server>http://www.andrewrea.co.uk/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.andrewrea.co.uk/blog/PermaLink,guid,f0342a2a-75f2-4576-bdc8-8dfc801125f1.aspx</pingback:target>
      <dc:creator>Andrew Rea</dc:creator>
      <wfw:comment>http://www.andrewrea.co.uk/blog/CommentView,guid,f0342a2a-75f2-4576-bdc8-8dfc801125f1.aspx</wfw:comment>
      <wfw:commentRss>http://www.andrewrea.co.uk/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=f0342a2a-75f2-4576-bdc8-8dfc801125f1</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I have been wanting to have a play with Object Databases for a while now, and today
I have done just that.  One of the obvious choices I had to make was which one
to use.  My criteria for choosing one today was simple, I wanted one which I
could literally wack in and start using, which means I wanted one which either had
a .NET API or was designed/ported to .NET.  My decision was between two being:
</p>
        <ul>
          <li>
            <a href="http://www.db4o.com/">db4o</a>
          </li>
          <li>
            <a href="http://www.mongodb.org/display/DOCS/Home">MongoDb</a>
          </li>
        </ul>
        <p>
I went for <a href="http://www.db4o.com/">db4o</a> for the single reason that it looked
like I could get it running and integrated the quickest.  I am making a Blogging
application and front end as a project with which I can test and learn with these
object databases.  Another requirement which I thought I would mention is that
I also want to be able to use the said database in a shared hosting environment where
I cannot install, run and maintain a server instance of said object database. 
I can do exactly this with <a href="http://www.db4o.com/">db4o</a>. I have not tried
to do this with <a href="http://www.mongodb.org/display/DOCS/Home">MongoDb</a> at
time of writing.  There are quite a few in the industry now and you read an interesting
post about different ones and how they are used with some of the heavy weights in
the industry here : <a href="http://blog.marcua.net/post/442594842/notes-from-nosql-live-boston-2010">http://blog.marcua.net/post/442594842/notes-from-nosql-live-boston-2010</a></p>
        <p>
In the example which I am building I am using StructureMap as my IOC.  To inject
the object for db4o I went with a Singleton instance scope as I am using a single
file and I need this to be available to any thread on in the process as opposed to
using the server implementation where I could open and close client connections with
the server handling each one respectively.  Again I want to point out that I
have chosen to stick with the non server implementation of db4o as I wanted to use
this in a shared hosting environment where I cannot have such servers installed and
run.
</p>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">    public static class Bootstrapper
    {
        public static void ConfigureStructureMap()
        {
            ObjectFactory.Initialize(x =&gt; x.AddRegistry(new MyApplicationRegistry()));
        }
    }

    public class MyApplicationRegistry : Registry
    {
        public const string DB4O_FILENAME = "blog123";

        public string DbPath
        {
            get
            {
                return Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(IBlogRepository)).Location), DB4O_FILENAME);
            }
        }

        public MyApplicationRegistry()
        {
            For&lt;IObjectContainer&gt;().Singleton().Use(
                () =&gt; Db4oEmbedded.OpenFile(Db4oEmbedded.NewConfiguration(), DbPath));

            Scan(assemblyScanner =&gt;
            {
                assemblyScanner.TheCallingAssembly();
                assemblyScanner.WithDefaultConventions();
            });
        }
    }</pre>
        <p>
          <a href="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/FirsttoeinthewaterwithObjectDatabasesDB4_10121/image_2.png">
            <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" align="right" src="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/FirsttoeinthewaterwithObjectDatabasesDB4_10121/image_thumb.png" width="322" height="325" />
          </a>
        </p>
        <p>
So my code above is the structure map plumbing which I use for the application. 
I am doing this simply as a quick scratch pad to play around with different things
so I am simply segregating logical layers with folder structure as opposed to different
assemblies.  It will be easy if I want to do this with any segment but for the
purposes of example I have literally just wacked everything in the one assembly. 
You can see an example file structure I have on the right.  I am planning on
testing out a few implementations of the object databases out there so I can program
to an interface of IBlogRepository
</p>
        <p>
One of the things which I was unsure about was how it performed under a multi threaded
environment which it will undoubtedly be used 9 times out of 10, and for the reason
that I am using the db context as a singleton, I assumed that the library was of course
thread safe but I did not know as I have not read any where in the documentation,
again this is probably me not reading things correctly.  In short though I threw
together a simple test where I simply iterate to a limit each time kicking a common
task off with a thread from a thread pool.  This task simply created and added
an random <strong>Post</strong> and added it to the storage.
</p>
        <p>
The execution of the threads I put inside the Setup of the Test and then simply ensure
the number of posts committed to the database is equal to the number of iterations
I made; here is the code I used to do the multi thread jobs:
</p>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">        [TestInitialize]
        public void Setup()
        {
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            var resetEvent = new ManualResetEvent(false);
            ThreadPool.SetMaxThreads(20, 20);
            for (var i = 0; i &lt; MAX_ITERATIONS; i++)
            {
                ThreadPool.QueueUserWorkItem(delegate(object state)
                                                 {
                                                     var eventToReset = (ManualResetEvent)state;
                                                     var post = new Post
                                                                    {
                                                                        Author = MockUser,
                                                                        Content = "Mock Content",
                                                                        Title = "Title"
                                                                    };
                                                     Repository.Put(post);

                                                     var counter = Interlocked.Decrement(ref _threadCounter);
                                                     if (counter == 0)
                                                         eventToReset.Set();

                                                 }, resetEvent);
            }

            WaitHandle.WaitAll(new[] { resetEvent });
            sw.Stop();
            Console.WriteLine("{0:00}.{1:00} seconds", sw.Elapsed.Seconds, sw.Elapsed.Milliseconds);
        }</pre>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"> </pre>
        <p>
 
</p>
        <p>
          <a href="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/FirsttoeinthewaterwithObjectDatabasesDB4_10121/image_4.png">
            <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/FirsttoeinthewaterwithObjectDatabasesDB4_10121/image_thumb_1.png" width="600" height="290" />
          </a>
        </p>
        <p>
 
</p>
        <p>
I was not doing this to test out the speed performance of db4o but while I was doing
this I could not help but put in a StopWatch and see out of sheer interest how fast
it would take to insert a number of Posts.  I tested it out in this case with
10000 inserts of a small, simple POCO and it resulted in an average of:
</p>
        <blockquote>
          <p>
 <strong>899.36 object inserts / second.  </strong></p>
        </blockquote>
        <p>
Again<strong></strong>this is just  simple crude test which came out of my curiosity
at how it performed under many threads when using the non server implementation of
db4o. The spec summary of the computer I used is as follows:
</p>
        <p>
          <a href="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/FirsttoeinthewaterwithObjectDatabasesDB4_10121/image_6.png">
            <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/FirsttoeinthewaterwithObjectDatabasesDB4_10121/image_thumb_2.png" width="622" height="164" />
          </a>
        </p>
        <p>
With regards to the actual Repository implementation itself, it really is quite straight
forward and I have to say I am very surprised at how easy it was to integrate and
get up and running.  One thing I have noticed in the exposure I have had so far
is that the Query returns IList&lt;T&gt; as opposed to IQueryable&lt;T&gt; but again
I have not looked into this in depth and this could be there already and if not they
have provided everything one needs to make there own repository.  An example
of a couple of methods from by db4o implementation of the BlogRepository is below:
</p>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">    public class BlogRepository : IBlogRepository
    {
        private readonly IObjectContainer _db;

        public BlogRepository(IObjectContainer db)
        {
            _db = db;
        }

        public void Put(DomainObject obj)
        {
            _db.Store(obj);
        }

        public void Delete(DomainObject obj)
        {
           _db.Delete(obj);
        }

        public Post GetByKey(object key)
        {
            return _db.Query&lt;Post&gt;(post =&gt; post.Key == key).FirstOrDefault();
        }</pre>
        <p>
…
</p>
        <p>
Anyways I hope to get a few more implementations going of the object databases and
literally just get familiarized with them and the concept of no sql databases.
</p>
        <p>
Cheers for now,
</p>
        <p>
Andrew 
</p>
        <img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=f0342a2a-75f2-4576-bdc8-8dfc801125f1" />
      </body>
      <title>First toe in the water with Object Databases : DB4O</title>
      <guid isPermaLink="false">http://www.andrewrea.co.uk/blog/PermaLink,guid,f0342a2a-75f2-4576-bdc8-8dfc801125f1.aspx</guid>
      <link>http://www.andrewrea.co.uk/blog/2010/03/15/FirstToeInTheWaterWithObjectDatabasesDB4O.aspx</link>
      <pubDate>Mon, 15 Mar 2010 22:15:47 GMT</pubDate>
      <description>&lt;p&gt;
I have been wanting to have a play with Object Databases for a while now, and today
I have done just that.&amp;#160; One of the obvious choices I had to make was which one
to use.&amp;#160; My criteria for choosing one today was simple, I wanted one which I
could literally wack in and start using, which means I wanted one which either had
a .NET API or was designed/ported to .NET.&amp;#160; My decision was between two being:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;a href="http://www.db4o.com/"&gt;db4o&lt;/a&gt; 
&lt;/li&gt;
&lt;li&gt;
&lt;a href="http://www.mongodb.org/display/DOCS/Home"&gt;MongoDb&lt;/a&gt; 
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
I went for &lt;a href="http://www.db4o.com/"&gt;db4o&lt;/a&gt; for the single reason that it looked
like I could get it running and integrated the quickest.&amp;#160; I am making a Blogging
application and front end as a project with which I can test and learn with these
object databases.&amp;#160; Another requirement which I thought I would mention is that
I also want to be able to use the said database in a shared hosting environment where
I cannot install, run and maintain a server instance of said object database.&amp;#160;
I can do exactly this with &lt;a href="http://www.db4o.com/"&gt;db4o&lt;/a&gt;. I have not tried
to do this with &lt;a href="http://www.mongodb.org/display/DOCS/Home"&gt;MongoDb&lt;/a&gt; at
time of writing.&amp;#160; There are quite a few in the industry now and you read an interesting
post about different ones and how they are used with some of the heavy weights in
the industry here : &lt;a href="http://blog.marcua.net/post/442594842/notes-from-nosql-live-boston-2010"&gt;http://blog.marcua.net/post/442594842/notes-from-nosql-live-boston-2010&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
In the example which I am building I am using StructureMap as my IOC.&amp;#160; To inject
the object for db4o I went with a Singleton instance scope as I am using a single
file and I need this to be available to any thread on in the process as opposed to
using the server implementation where I could open and close client connections with
the server handling each one respectively.&amp;#160; Again I want to point out that I
have chosen to stick with the non server implementation of db4o as I wanted to use
this in a shared hosting environment where I cannot have such servers installed and
run.
&lt;/p&gt;
&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;    public static class Bootstrapper
    {
        public static void ConfigureStructureMap()
        {
            ObjectFactory.Initialize(x =&amp;gt; x.AddRegistry(new MyApplicationRegistry()));
        }
    }

    public class MyApplicationRegistry : Registry
    {
        public const string DB4O_FILENAME = &amp;quot;blog123&amp;quot;;

        public string DbPath
        {
            get
            {
                return Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(IBlogRepository)).Location), DB4O_FILENAME);
            }
        }

        public MyApplicationRegistry()
        {
            For&amp;lt;IObjectContainer&amp;gt;().Singleton().Use(
                () =&amp;gt; Db4oEmbedded.OpenFile(Db4oEmbedded.NewConfiguration(), DbPath));

            Scan(assemblyScanner =&amp;gt;
            {
                assemblyScanner.TheCallingAssembly();
                assemblyScanner.WithDefaultConventions();
            });
        }
    }&lt;/pre&gt;
&lt;p&gt;
&lt;a href="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/FirsttoeinthewaterwithObjectDatabasesDB4_10121/image_2.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" align="right" src="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/FirsttoeinthewaterwithObjectDatabasesDB4_10121/image_thumb.png" width="322" height="325" /&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
So my code above is the structure map plumbing which I use for the application.&amp;#160;
I am doing this simply as a quick scratch pad to play around with different things
so I am simply segregating logical layers with folder structure as opposed to different
assemblies.&amp;#160; It will be easy if I want to do this with any segment but for the
purposes of example I have literally just wacked everything in the one assembly.&amp;#160;
You can see an example file structure I have on the right.&amp;#160; I am planning on
testing out a few implementations of the object databases out there so I can program
to an interface of IBlogRepository
&lt;/p&gt;
&lt;p&gt;
One of the things which I was unsure about was how it performed under a multi threaded
environment which it will undoubtedly be used 9 times out of 10, and for the reason
that I am using the db context as a singleton, I assumed that the library was of course
thread safe but I did not know as I have not read any where in the documentation,
again this is probably me not reading things correctly.&amp;#160; In short though I threw
together a simple test where I simply iterate to a limit each time kicking a common
task off with a thread from a thread pool.&amp;#160; This task simply created and added
an random &lt;strong&gt;Post&lt;/strong&gt; and added it to the storage.
&lt;/p&gt;
&lt;p&gt;
The execution of the threads I put inside the Setup of the Test and then simply ensure
the number of posts committed to the database is equal to the number of iterations
I made; here is the code I used to do the multi thread jobs:
&lt;/p&gt;
&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;        [TestInitialize]
        public void Setup()
        {
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            var resetEvent = new ManualResetEvent(false);
            ThreadPool.SetMaxThreads(20, 20);
            for (var i = 0; i &amp;lt; MAX_ITERATIONS; i++)
            {
                ThreadPool.QueueUserWorkItem(delegate(object state)
                                                 {
                                                     var eventToReset = (ManualResetEvent)state;
                                                     var post = new Post
                                                                    {
                                                                        Author = MockUser,
                                                                        Content = &amp;quot;Mock Content&amp;quot;,
                                                                        Title = &amp;quot;Title&amp;quot;
                                                                    };
                                                     Repository.Put(post);

                                                     var counter = Interlocked.Decrement(ref _threadCounter);
                                                     if (counter == 0)
                                                         eventToReset.Set();

                                                 }, resetEvent);
            }

            WaitHandle.WaitAll(new[] { resetEvent });
            sw.Stop();
            Console.WriteLine(&amp;quot;{0:00}.{1:00} seconds&amp;quot;, sw.Elapsed.Seconds, sw.Elapsed.Milliseconds);
        }&lt;/pre&gt;
&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;&amp;#160;&lt;/pre&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/FirsttoeinthewaterwithObjectDatabasesDB4_10121/image_4.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/FirsttoeinthewaterwithObjectDatabasesDB4_10121/image_thumb_1.png" width="600" height="290" /&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
I was not doing this to test out the speed performance of db4o but while I was doing
this I could not help but put in a StopWatch and see out of sheer interest how fast
it would take to insert a number of Posts.&amp;#160; I tested it out in this case with
10000 inserts of a small, simple POCO and it resulted in an average of:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
&amp;#160;&lt;strong&gt;899.36 object inserts / second.&amp;#160; &lt;/strong&gt;
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Again&lt;strong&gt; &lt;/strong&gt;this is just&amp;#160; simple crude test which came out of my curiosity
at how it performed under many threads when using the non server implementation of
db4o. The spec summary of the computer I used is as follows:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/FirsttoeinthewaterwithObjectDatabasesDB4_10121/image_6.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/FirsttoeinthewaterwithObjectDatabasesDB4_10121/image_thumb_2.png" width="622" height="164" /&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
With regards to the actual Repository implementation itself, it really is quite straight
forward and I have to say I am very surprised at how easy it was to integrate and
get up and running.&amp;#160; One thing I have noticed in the exposure I have had so far
is that the Query returns IList&amp;lt;T&amp;gt; as opposed to IQueryable&amp;lt;T&amp;gt; but again
I have not looked into this in depth and this could be there already and if not they
have provided everything one needs to make there own repository.&amp;#160; An example
of a couple of methods from by db4o implementation of the BlogRepository is below:
&lt;/p&gt;
&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;    public class BlogRepository : IBlogRepository
    {
        private readonly IObjectContainer _db;

        public BlogRepository(IObjectContainer db)
        {
            _db = db;
        }

        public void Put(DomainObject obj)
        {
            _db.Store(obj);
        }

        public void Delete(DomainObject obj)
        {
           _db.Delete(obj);
        }

        public Post GetByKey(object key)
        {
            return _db.Query&amp;lt;Post&amp;gt;(post =&amp;gt; post.Key == key).FirstOrDefault();
        }&lt;/pre&gt;
&lt;p&gt;
…
&lt;/p&gt;
&lt;p&gt;
Anyways I hope to get a few more implementations going of the object databases and
literally just get familiarized with them and the concept of no sql databases.
&lt;/p&gt;
&lt;p&gt;
Cheers for now,
&lt;/p&gt;
&lt;p&gt;
Andrew 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=f0342a2a-75f2-4576-bdc8-8dfc801125f1" /&gt;</description>
      <comments>http://www.andrewrea.co.uk/blog/CommentView,guid,f0342a2a-75f2-4576-bdc8-8dfc801125f1.aspx</comments>
      <category>.NET</category>
      <category>ASP.NET MVC</category>
      <category>C#</category>
      <category>db4o</category>
      <category>Multi Threading</category>
    </item>
    <item>
      <trackback:ping>http://www.andrewrea.co.uk/blog/Trackback.aspx?guid=7d13ae96-1a7d-4006-982d-4ff886b57bf4</trackback:ping>
      <pingback:server>http://www.andrewrea.co.uk/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.andrewrea.co.uk/blog/PermaLink,guid,7d13ae96-1a7d-4006-982d-4ff886b57bf4.aspx</pingback:target>
      <dc:creator>Andrew Rea</dc:creator>
      <wfw:comment>http://www.andrewrea.co.uk/blog/CommentView,guid,7d13ae96-1a7d-4006-982d-4ff886b57bf4.aspx</wfw:comment>
      <wfw:commentRss>http://www.andrewrea.co.uk/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=7d13ae96-1a7d-4006-982d-4ff886b57bf4</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I was literally setting a new project yesterday to have a play with the released version
of ASP.NET MVC 2 and came across a subtle couple of things which when you know, like
everything, is easy.
</p>
        <p>
I am creating a small test application which is another blog one, but this time I
also want to use an Object DB or many, the first being MONGO, but anyway.  I
added a new Area to my project being the Blog area, added the controller and a view
and hit F5.
</p>
        <p>
          <a href="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/ASP.NETMVC2TheviewIndexoritsmasterwasnot_A66B/image_2.png">
            <img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="The view 'Index' or its master was not found.  The following locations were searched:" border="0" alt="The view 'Index' or its master was not found.  The following locations were searched:" src="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/ASP.NETMVC2TheviewIndexoritsmasterwasnot_A66B/image_thumb.png" width="600" height="135" />
          </a>
        </p>
        <p>
Because my area was called <strong>Blog</strong>, naturally I want the controller
to be called <strong>BlogController</strong>.  The cause and the solution are
inside the <strong>AreaRegistration</strong> file.  When you create your new
area you should notice your default route inside this registration file and notice
there is no default controller specified, which is correct because at time of creation
you will not have a controller inside the area.
</p>
        <pre class="brush: xml; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Blog_default",
                "Blog/{controller}/{action}/{id}",
                new { action = "Index", id = "" }
            );
        }</pre>
        <p>
 
</p>
        <p>
So add in the default controller and everything is back to normal.  Also, if
you do not add this controller and for example add a break point to the return View()
of the Index Action on your controller, you will see that it does get hit, it is just
the locating of the View which fails.  I am sure there is more plumbing that
can be done to enable the location of these views without explicitly stating the default
controller but at time of writing I do not know.  
</p>
        <pre class="brush: xml; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Blog_default",
                "Blog/{controller}/{action}/{id}",
                new {controller="Blog", action = "Index", id = "" }
            );
        }</pre>
        <p>
Cheers for now,
</p>
        <p>
Andrew
</p>
        <img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=7d13ae96-1a7d-4006-982d-4ff886b57bf4" />
      </body>
      <title>ASP.NET MVC 2 : The view 'Index' or its master was not found</title>
      <guid isPermaLink="false">http://www.andrewrea.co.uk/blog/PermaLink,guid,7d13ae96-1a7d-4006-982d-4ff886b57bf4.aspx</guid>
      <link>http://www.andrewrea.co.uk/blog/2010/03/14/ASPNETMVC2TheViewIndexOrItsMasterWasNotFound.aspx</link>
      <pubDate>Sun, 14 Mar 2010 11:48:31 GMT</pubDate>
      <description>&lt;p&gt;
I was literally setting a new project yesterday to have a play with the released version
of ASP.NET MVC 2 and came across a subtle couple of things which when you know, like
everything, is easy.
&lt;/p&gt;
&lt;p&gt;
I am creating a small test application which is another blog one, but this time I
also want to use an Object DB or many, the first being MONGO, but anyway.&amp;#160; I
added a new Area to my project being the Blog area, added the controller and a view
and hit F5.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/ASP.NETMVC2TheviewIndexoritsmasterwasnot_A66B/image_2.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="The view &amp;#39;Index&amp;#39; or its master was not found.  The following locations were searched:" border="0" alt="The view &amp;#39;Index&amp;#39; or its master was not found.  The following locations were searched:" src="http://www.andrewrea.co.uk/blog/content/binary/WindowsLiveWriter/ASP.NETMVC2TheviewIndexoritsmasterwasnot_A66B/image_thumb.png" width="600" height="135" /&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
Because my area was called &lt;strong&gt;Blog&lt;/strong&gt;, naturally I want the controller
to be called &lt;strong&gt;BlogController&lt;/strong&gt;.&amp;#160; The cause and the solution are
inside the &lt;strong&gt;AreaRegistration&lt;/strong&gt; file.&amp;#160; When you create your new
area you should notice your default route inside this registration file and notice
there is no default controller specified, which is correct because at time of creation
you will not have a controller inside the area.
&lt;/p&gt;
&lt;pre class="brush: xml; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                &amp;quot;Blog_default&amp;quot;,
                &amp;quot;Blog/{controller}/{action}/{id}&amp;quot;,
                new { action = &amp;quot;Index&amp;quot;, id = &amp;quot;&amp;quot; }
            );
        }&lt;/pre&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
So add in the default controller and everything is back to normal.&amp;#160; Also, if
you do not add this controller and for example add a break point to the return View()
of the Index Action on your controller, you will see that it does get hit, it is just
the locating of the View which fails.&amp;#160; I am sure there is more plumbing that
can be done to enable the location of these views without explicitly stating the default
controller but at time of writing I do not know.&amp;#160; 
&lt;/p&gt;
&lt;pre class="brush: xml; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                &amp;quot;Blog_default&amp;quot;,
                &amp;quot;Blog/{controller}/{action}/{id}&amp;quot;,
                new {controller=&amp;quot;Blog&amp;quot;, action = &amp;quot;Index&amp;quot;, id = &amp;quot;&amp;quot; }
            );
        }&lt;/pre&gt;
&lt;p&gt;
Cheers for now,
&lt;/p&gt;
&lt;p&gt;
Andrew
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=7d13ae96-1a7d-4006-982d-4ff886b57bf4" /&gt;</description>
      <comments>http://www.andrewrea.co.uk/blog/CommentView,guid,7d13ae96-1a7d-4006-982d-4ff886b57bf4.aspx</comments>
      <category>.NET</category>
      <category>ASP.NET MVC</category>
      <category>C#</category>
    </item>
    <item>
      <trackback:ping>http://www.andrewrea.co.uk/blog/Trackback.aspx?guid=524a7e3c-3bd5-4b79-99b2-4c607e2f2584</trackback:ping>
      <pingback:server>http://www.andrewrea.co.uk/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.andrewrea.co.uk/blog/PermaLink,guid,524a7e3c-3bd5-4b79-99b2-4c607e2f2584.aspx</pingback:target>
      <dc:creator>Andrew Rea</dc:creator>
      <wfw:comment>http://www.andrewrea.co.uk/blog/CommentView,guid,524a7e3c-3bd5-4b79-99b2-4c607e2f2584.aspx</wfw:comment>
      <wfw:commentRss>http://www.andrewrea.co.uk/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=524a7e3c-3bd5-4b79-99b2-4c607e2f2584</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I recently made two contributions to the <strong><a href="http://code.google.com/p/agatha-rrsl/">Agatha
Project</a></strong> by <strong><a href="http://davybrion.com/blog/">Davy Brion</a></strong> over
on Google Code, and one of the things I wanted to follow up with was a post showing
examples and some, seemingly required tid bits.  The contributions which I made
where:
</p>
        <ul>
          <li>
To support StructureMap 
</li>
          <li>
To include <strong>REST (JSON and XML)</strong> support for the service contract 
</li>
        </ul>
        <p>
The examples which I have made, I want to format them so they fit in with the current
format of examples over on <strong>Agatha</strong> and hopefully create and submit
a third patch which will include these examples to help others who wish to use these
additions.
</p>
        <p>
Whilst building these examples for both XML and JSON I have learnt a couple of things
which I feel are not really well documented, but are extremely good practice and once
known make perfect sense.  I have chosen a real basic e-commerce context for
my example Requests and Responses, and have also made use of the excellent tool <a href="http://code.google.com/p/automapperhome/">AutoMapper</a>,
again on Google Code.
</p>
        <h2>Setting the scene
</h2>
        <p>
I have followed the <strong>Pipes and Filters Pattern</strong> with the <strong>IQueryable</strong> interface
on my Repository and exposed the following methods to query Products:
</p>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">IQueryable&lt;Product&gt; GetProducts();</pre>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">IQueryable&lt;Product&gt; ByCategoryName(this IQueryable&lt;Product&gt; products, string categoryName)</pre>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">Product ByProductCode(this IQueryable&lt;Product&gt; products, String productCode)</pre>
        <p>
I have an interface for the <strong>IProductRepository</strong> but for the concrete
implementation I have simply created a protected getter which populates a private <strong>List&lt;Product&gt;</strong> with
100 test products with random data.  Another good reason for following an interface
based approach is that it will demonstrate usage of my first contribution which is
the StructureMap support.  Finally the two Domain Objects I have made are Product
and Category as shown below:
</p>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">    public class Product
    {
        public String ProductCode { get; set; }
        public String Name { get; set; }
        public Decimal Price { get; set; }
        public Decimal Rrp { get; set; }
        public Category Category { get; set; }
    }</pre>
        <p>
 
</p>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">    public class Category
    {
        public String Name { get; set; }
    }</pre>
        <p>
 
</p>
        <h2>Requirements for the REST Support
</h2>
        <p>
One of the things which you will notice with Agatha is that you do not have to decorate
your Request and Response objects with the WCF Service Model Attributes like DataContract,
DataMember etc… Unfortunately from what I have seen, these are required if you want
the same types to work with your REST endpoint.  I have not tried but I assume
the same result can be achieved by simply decorating the same classes with the<strong> Serializable
Attribute</strong>.  Without this the operation will fail.
</p>
        <p>
Another surprising thing I have found is that it did not work until I used the following
Attribute parameters:
</p>
        <ul>
          <li>
Name 
</li>
          <li>
Namespace 
</li>
        </ul>
        <p>
e.g.
</p>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">    [DataContract(Name = "GetProductsRequest", Namespace = "AgathaRestExample.Service.Requests")]
    public class GetProductsRequest : Request
    {
    }</pre>
        <p>
 
</p>
        <p>
Although I was surprised by this, things kind of explained themselves when I got round
to figuring out the exact construct required for both the XML and the REST. 
One of the things which you already know and are then reminded of is that each of
your Requests and Responses ultimately inherit from an abstract base class respectively.
This information needs to be represented in a way native to the format being used. 
I have seen this in XML but I have not seen the format which is required for the JSON.
</p>
        <h2>JSON Consumer Example
</h2>
        <p>
I have used JQuery to create the example and I simply want to make two requests to
the server which as you will know with Agatha are transmitted inside an array to reduce
the service calls.  I have also used a tool called json2 which is again over
at Google Code simply to convert my JSON expression into its string format for transmission. 
You will notice that I specify the type of Request I am using and the relevant Namespace
it belongs to.  Also notice that the second request has a parameter so each of
these two object are representing an abstract Request and the parameters of the object
describe it.
</p>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">    &lt;script type="text/javascript"&gt;
        var bodyContent = $.ajax({
        url: "http://localhost:50348/service.svc/json/processjsonrequests",
            global: false,
            contentType: "application/json; charset=utf-8",
            type: "POST",
            processData: true,
            data: JSON.stringify([
            { __type: "GetProductsRequest:AgathaRestExample.Service.Requests" },
            { __type: "GetProductsByCategoryRequest:AgathaRestExample.Service.Requests", CategoryName: "Category1" }
            ]),
            dataType: "json",
            success: function(msg) {
                alert(msg);
            }
        }).responseText;

    &lt;/script&gt;</pre>
        <p>
 
</p>
        <h2>XML Consumer Example
</h2>
        <p>
For the XML Consumer example I have chosen to use a simple Console Application and
make a WebRequest to the service using the XML as a request.  I have made a crude
static method which simply reads from an XML File, replaces some value with a parameter
and returns the formatted XML.  I say crude but it simply shows how XML Templates
for each type of Request could be made and then have a wrapper utility in whatever
language you use to combine the requests which are required.  The following XML
is the same Request array as shown above but simply in the XML Format.
</p>
        <pre class="brush: xml; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;ArrayOfRequest xmlns="http://schemas.datacontract.org/2004/07/Agatha.Common" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt;
  &lt;Request i:type="a:GetProductsRequest" xmlns:a="AgathaRestExample.Service.Requests"/&gt;
  &lt;Request i:type="a:GetProductsByCategoryRequest" xmlns:a="AgathaRestExample.Service.Requests"&gt;
    &lt;a:CategoryName&gt;{CategoryName}&lt;/a:CategoryName&gt;
  &lt;/Request&gt;
&lt;/ArrayOfRequest&gt;</pre>
        <p>
 
</p>
        <p>
It is funny because I remember submitting a question to <strong>StackOverflow</strong> asking
whether there was a REST Client Generation tool similar to what Microsoft used for
their <strong>RestStarterKit</strong> but which could be applied to existing services
which have REST endpoints attached.  I could not find any but this is now definitely
something which I am going to build, as I think it is extremely useful to have but
also it should not be too difficult based on the information I now know about the
above.  Finally I thought that the Strategy Pattern would lend itself really
well to this type of thing so it can accommodate for different languages.
</p>
        <p>
I think that is about it, I have included the code for the example Console app which
I made below incase anyone wants to have a mooch at the code.  As I said above
I want to reformat these to fit in with the current examples over on the Agatha project,
but also now thinking about it, make a Documentation Web method…{brain ticking} :-)
</p>
        <p>
Cheers for now and here is the final bit of code:
</p>
        <pre class="brush: xml; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">        static void Main(string[] args)
        {
            var request = WebRequest.Create("http://localhost:50348/service.svc/xml/processxmlrequests");
            request.Method = "POST";
            request.ContentType = "text/xml";
            using(var writer = new StreamWriter(request.GetRequestStream()))
            {
                writer.WriteLine(GetExampleRequestsString("Category1"));
            }
            var response = request.GetResponse();
            using(var reader = new StreamReader(response.GetResponseStream()))
            {
                Console.WriteLine(reader.ReadToEnd());
            }
            Console.ReadLine();
        }

        static string GetExampleRequestsString(string categoryName)
        {
            var data = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ExampleRequests.xml"));
            data = data.Replace("{CategoryName}", categoryName);
            return data;
        }
    }</pre>
        <img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=524a7e3c-3bd5-4b79-99b2-4c607e2f2584" />
      </body>
      <title>Compiling examples for consuming the REST Endpoints for WCF Service using Agatha</title>
      <guid isPermaLink="false">http://www.andrewrea.co.uk/blog/PermaLink,guid,524a7e3c-3bd5-4b79-99b2-4c607e2f2584.aspx</guid>
      <link>http://www.andrewrea.co.uk/blog/2010/03/09/CompilingExamplesForConsumingTheRESTEndpointsForWCFServiceUsingAgatha.aspx</link>
      <pubDate>Tue, 09 Mar 2010 22:43:30 GMT</pubDate>
      <description>&lt;p&gt;
I recently made two contributions to the &lt;strong&gt;&lt;a href="http://code.google.com/p/agatha-rrsl/"&gt;Agatha
Project&lt;/a&gt;&lt;/strong&gt; by &lt;strong&gt;&lt;a href="http://davybrion.com/blog/"&gt;Davy Brion&lt;/a&gt;&lt;/strong&gt; over
on Google Code, and one of the things I wanted to follow up with was a post showing
examples and some, seemingly required tid bits.&amp;#160; The contributions which I made
where:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
To support StructureMap 
&lt;/li&gt;
&lt;li&gt;
To include &lt;strong&gt;REST (JSON and XML)&lt;/strong&gt; support for the service contract 
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
The examples which I have made, I want to format them so they fit in with the current
format of examples over on &lt;strong&gt;Agatha&lt;/strong&gt; and hopefully create and submit
a third patch which will include these examples to help others who wish to use these
additions.
&lt;/p&gt;
&lt;p&gt;
Whilst building these examples for both XML and JSON I have learnt a couple of things
which I feel are not really well documented, but are extremely good practice and once
known make perfect sense.&amp;#160; I have chosen a real basic e-commerce context for
my example Requests and Responses, and have also made use of the excellent tool &lt;a href="http://code.google.com/p/automapperhome/"&gt;AutoMapper&lt;/a&gt;,
again on Google Code.
&lt;/p&gt;
&lt;h2&gt;Setting the scene
&lt;/h2&gt;
&lt;p&gt;
I have followed the &lt;strong&gt;Pipes and Filters Pattern&lt;/strong&gt; with the &lt;strong&gt;IQueryable&lt;/strong&gt; interface
on my Repository and exposed the following methods to query Products:
&lt;/p&gt;
&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;IQueryable&amp;lt;Product&amp;gt; GetProducts();&lt;/pre&gt;
&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;IQueryable&amp;lt;Product&amp;gt; ByCategoryName(this IQueryable&amp;lt;Product&amp;gt; products, string categoryName)&lt;/pre&gt;
&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;Product ByProductCode(this IQueryable&amp;lt;Product&amp;gt; products, String productCode)&lt;/pre&gt;
&lt;p&gt;
I have an interface for the &lt;strong&gt;IProductRepository&lt;/strong&gt; but for the concrete
implementation I have simply created a protected getter which populates a private &lt;strong&gt;List&amp;lt;Product&amp;gt;&lt;/strong&gt; with
100 test products with random data.&amp;#160; Another good reason for following an interface
based approach is that it will demonstrate usage of my first contribution which is
the StructureMap support.&amp;#160; Finally the two Domain Objects I have made are Product
and Category as shown below:
&lt;/p&gt;
&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;    public class Product
    {
        public String ProductCode { get; set; }
        public String Name { get; set; }
        public Decimal Price { get; set; }
        public Decimal Rrp { get; set; }
        public Category Category { get; set; }
    }&lt;/pre&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;    public class Category
    {
        public String Name { get; set; }
    }&lt;/pre&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;h2&gt;Requirements for the REST Support
&lt;/h2&gt;
&lt;p&gt;
One of the things which you will notice with Agatha is that you do not have to decorate
your Request and Response objects with the WCF Service Model Attributes like DataContract,
DataMember etc… Unfortunately from what I have seen, these are required if you want
the same types to work with your REST endpoint.&amp;#160; I have not tried but I assume
the same result can be achieved by simply decorating the same classes with the&lt;strong&gt; Serializable
Attribute&lt;/strong&gt;.&amp;#160; Without this the operation will fail.
&lt;/p&gt;
&lt;p&gt;
Another surprising thing I have found is that it did not work until I used the following
Attribute parameters:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
Name 
&lt;/li&gt;
&lt;li&gt;
Namespace 
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
e.g.
&lt;/p&gt;
&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;    [DataContract(Name = &amp;quot;GetProductsRequest&amp;quot;, Namespace = &amp;quot;AgathaRestExample.Service.Requests&amp;quot;)]
    public class GetProductsRequest : Request
    {
    }&lt;/pre&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
Although I was surprised by this, things kind of explained themselves when I got round
to figuring out the exact construct required for both the XML and the REST.&amp;#160;
One of the things which you already know and are then reminded of is that each of
your Requests and Responses ultimately inherit from an abstract base class respectively.
This information needs to be represented in a way native to the format being used.&amp;#160;
I have seen this in XML but I have not seen the format which is required for the JSON.
&lt;/p&gt;
&lt;h2&gt;JSON Consumer Example
&lt;/h2&gt;
&lt;p&gt;
I have used JQuery to create the example and I simply want to make two requests to
the server which as you will know with Agatha are transmitted inside an array to reduce
the service calls.&amp;#160; I have also used a tool called json2 which is again over
at Google Code simply to convert my JSON expression into its string format for transmission.&amp;#160;
You will notice that I specify the type of Request I am using and the relevant Namespace
it belongs to.&amp;#160; Also notice that the second request has a parameter so each of
these two object are representing an abstract Request and the parameters of the object
describe it.
&lt;/p&gt;
&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;    &amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;
        var bodyContent = $.ajax({
        url: &amp;quot;http://localhost:50348/service.svc/json/processjsonrequests&amp;quot;,
            global: false,
            contentType: &amp;quot;application/json; charset=utf-8&amp;quot;,
            type: &amp;quot;POST&amp;quot;,
            processData: true,
            data: JSON.stringify([
            { __type: &amp;quot;GetProductsRequest:AgathaRestExample.Service.Requests&amp;quot; },
            { __type: &amp;quot;GetProductsByCategoryRequest:AgathaRestExample.Service.Requests&amp;quot;, CategoryName: &amp;quot;Category1&amp;quot; }
            ]),
            dataType: &amp;quot;json&amp;quot;,
            success: function(msg) {
                alert(msg);
            }
        }).responseText;

    &amp;lt;/script&amp;gt;&lt;/pre&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;h2&gt;XML Consumer Example
&lt;/h2&gt;
&lt;p&gt;
For the XML Consumer example I have chosen to use a simple Console Application and
make a WebRequest to the service using the XML as a request.&amp;#160; I have made a crude
static method which simply reads from an XML File, replaces some value with a parameter
and returns the formatted XML.&amp;#160; I say crude but it simply shows how XML Templates
for each type of Request could be made and then have a wrapper utility in whatever
language you use to combine the requests which are required.&amp;#160; The following XML
is the same Request array as shown above but simply in the XML Format.
&lt;/p&gt;
&lt;pre class="brush: xml; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;
&amp;lt;ArrayOfRequest xmlns=&amp;quot;http://schemas.datacontract.org/2004/07/Agatha.Common&amp;quot; xmlns:i=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&amp;gt;
  &amp;lt;Request i:type=&amp;quot;a:GetProductsRequest&amp;quot; xmlns:a=&amp;quot;AgathaRestExample.Service.Requests&amp;quot;/&amp;gt;
  &amp;lt;Request i:type=&amp;quot;a:GetProductsByCategoryRequest&amp;quot; xmlns:a=&amp;quot;AgathaRestExample.Service.Requests&amp;quot;&amp;gt;
    &amp;lt;a:CategoryName&amp;gt;{CategoryName}&amp;lt;/a:CategoryName&amp;gt;
  &amp;lt;/Request&amp;gt;
&amp;lt;/ArrayOfRequest&amp;gt;&lt;/pre&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
It is funny because I remember submitting a question to &lt;strong&gt;StackOverflow&lt;/strong&gt; asking
whether there was a REST Client Generation tool similar to what Microsoft used for
their &lt;strong&gt;RestStarterKit&lt;/strong&gt; but which could be applied to existing services
which have REST endpoints attached.&amp;#160; I could not find any but this is now definitely
something which I am going to build, as I think it is extremely useful to have but
also it should not be too difficult based on the information I now know about the
above.&amp;#160; Finally I thought that the Strategy Pattern would lend itself really
well to this type of thing so it can accommodate for different languages.
&lt;/p&gt;
&lt;p&gt;
I think that is about it, I have included the code for the example Console app which
I made below incase anyone wants to have a mooch at the code.&amp;#160; As I said above
I want to reformat these to fit in with the current examples over on the Agatha project,
but also now thinking about it, make a Documentation Web method…{brain ticking} :-)
&lt;/p&gt;
&lt;p&gt;
Cheers for now and here is the final bit of code:
&lt;/p&gt;
&lt;pre class="brush: xml; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;        static void Main(string[] args)
        {
            var request = WebRequest.Create(&amp;quot;http://localhost:50348/service.svc/xml/processxmlrequests&amp;quot;);
            request.Method = &amp;quot;POST&amp;quot;;
            request.ContentType = &amp;quot;text/xml&amp;quot;;
            using(var writer = new StreamWriter(request.GetRequestStream()))
            {
                writer.WriteLine(GetExampleRequestsString(&amp;quot;Category1&amp;quot;));
            }
            var response = request.GetResponse();
            using(var reader = new StreamReader(response.GetResponseStream()))
            {
                Console.WriteLine(reader.ReadToEnd());
            }
            Console.ReadLine();
        }

        static string GetExampleRequestsString(string categoryName)
        {
            var data = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), &amp;quot;ExampleRequests.xml&amp;quot;));
            data = data.Replace(&amp;quot;{CategoryName}&amp;quot;, categoryName);
            return data;
        }
    }&lt;/pre&gt;&lt;img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=524a7e3c-3bd5-4b79-99b2-4c607e2f2584" /&gt;</description>
      <comments>http://www.andrewrea.co.uk/blog/CommentView,guid,524a7e3c-3bd5-4b79-99b2-4c607e2f2584.aspx</comments>
    </item>
    <item>
      <trackback:ping>http://www.andrewrea.co.uk/blog/Trackback.aspx?guid=05fb9609-6886-4d2b-b2b1-09e610346795</trackback:ping>
      <pingback:server>http://www.andrewrea.co.uk/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.andrewrea.co.uk/blog/PermaLink,guid,05fb9609-6886-4d2b-b2b1-09e610346795.aspx</pingback:target>
      <dc:creator>Andrew Rea</dc:creator>
      <wfw:comment>http://www.andrewrea.co.uk/blog/CommentView,guid,05fb9609-6886-4d2b-b2b1-09e610346795.aspx</wfw:comment>
      <wfw:commentRss>http://www.andrewrea.co.uk/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=05fb9609-6886-4d2b-b2b1-09e610346795</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Today in work I had a requirement where I wanted to output binary content to the response
output stream.  I also want to stay with the MVC Controller for serving this
content and so wanted a result I could add my data to and return it.  To my knowledge
there is a <strong>ContentResult</strong>, but with this the Content property is of
type string, and is not what I wanted.  I this particular case, I am physically <strong>GZipping</strong> content
and then writing out to the <strong>Response.OutputStream</strong>.  
</p>
        <p>
Previous to this I have been seeing and using examples where you assign a <strong>GZipOutputStream</strong> as
a Filter on the Response dynamically.  For some strange reason on the Live environment
the header and filter where being ignored on the response yet on the test, builds
and sandbox everything worked as expected and the dynamic resources got <strong>GZipped</strong>.
</p>
        <p>
So I had to go another way and what I came up with was to physically <strong>GZip</strong> the
output content and send it to the response with the accompanying header.  I cannot
see why this would not work on the server as the content is physically being served
already <strong>GZipped</strong> opposed to applying a filter which can obviously
be removed somewhere in the pipeline.  Any way after some reading I found some
evidence that a library, <a href="http://www.icsharpcode.net/OpenSource/SharpZipLib/">http://www.icsharpcode.net/OpenSource/SharpZipLib/</a> ,
yields far better results than the out of the box one from .NET, so for this example
I have a dependency on this assembly.  Apart from that I have added a couple
of properties which allow for the conditional Compression and also a list of headers
to give a little more flexibility.  So here is the code:
</p>
        <blockquote>
          <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">    /// &lt;summary&gt;
    /// A content result which can accept binart data and will write to the output
    /// stream.  If GZip is set to true the content will be GZipped and the relevant
    /// header added to the response HTTP Headers
    /// &lt;/summary&gt;
    public class BinaryContentResult : ActionResult
    {
        public byte[] Data { get; set; }
        public NameValueCollection Headers { get; set; }
        public bool Gzip { get; set; }


        public override void ExecuteResult(ControllerContext context)
        {
            foreach (string s in Headers.Keys)
            {
                context.HttpContext.Response.AddHeader(s, Headers[s]);
            }

            if (Gzip)
            {
                using (var os = new GZipOutputStream(context.HttpContext.Response.OutputStream))
                {
                    os.Write(Data, 0, Data.Length);
                }
                context.HttpContext.Response.AddHeader("Content-Encoding", "gzip");
                context.HttpContext.Response.AddHeader("X-Compressed-By", "Custom-Compressor");
            }
            else
            {
                context.HttpContext.Response.BinaryWrite(Data);
            }

            context.HttpContext.Response.End();
        }
    }</pre>
        </blockquote>
        <img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=05fb9609-6886-4d2b-b2b1-09e610346795" />
      </body>
      <title>A BinaryContentResult for ASP.NET MVC</title>
      <guid isPermaLink="false">http://www.andrewrea.co.uk/blog/PermaLink,guid,05fb9609-6886-4d2b-b2b1-09e610346795.aspx</guid>
      <link>http://www.andrewrea.co.uk/blog/2010/02/16/ABinaryContentResultForASPNETMVC.aspx</link>
      <pubDate>Tue, 16 Feb 2010 19:29:48 GMT</pubDate>
      <description>&lt;p&gt;
Today in work I had a requirement where I wanted to output binary content to the response
output stream.&amp;#160; I also want to stay with the MVC Controller for serving this
content and so wanted a result I could add my data to and return it.&amp;#160; To my knowledge
there is a &lt;strong&gt;ContentResult&lt;/strong&gt;, but with this the Content property is of
type string, and is not what I wanted.&amp;#160; I this particular case, I am physically &lt;strong&gt;GZipping&lt;/strong&gt; content
and then writing out to the &lt;strong&gt;Response.OutputStream&lt;/strong&gt;.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
Previous to this I have been seeing and using examples where you assign a &lt;strong&gt;GZipOutputStream&lt;/strong&gt; as
a Filter on the Response dynamically.&amp;#160; For some strange reason on the Live environment
the header and filter where being ignored on the response yet on the test, builds
and sandbox everything worked as expected and the dynamic resources got &lt;strong&gt;GZipped&lt;/strong&gt;.
&lt;/p&gt;
&lt;p&gt;
So I had to go another way and what I came up with was to physically &lt;strong&gt;GZip&lt;/strong&gt; the
output content and send it to the response with the accompanying header.&amp;#160; I cannot
see why this would not work on the server as the content is physically being served
already &lt;strong&gt;GZipped&lt;/strong&gt; opposed to applying a filter which can obviously
be removed somewhere in the pipeline.&amp;#160; Any way after some reading I found some
evidence that a library, &lt;a href="http://www.icsharpcode.net/OpenSource/SharpZipLib/"&gt;http://www.icsharpcode.net/OpenSource/SharpZipLib/&lt;/a&gt; ,
yields far better results than the out of the box one from .NET, so for this example
I have a dependency on this assembly.&amp;#160; Apart from that I have added a couple
of properties which allow for the conditional Compression and also a list of headers
to give a little more flexibility.&amp;#160; So here is the code:
&lt;/p&gt;
&lt;blockquote&gt; &lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;    /// &amp;lt;summary&amp;gt;
    /// A content result which can accept binart data and will write to the output
    /// stream.  If GZip is set to true the content will be GZipped and the relevant
    /// header added to the response HTTP Headers
    /// &amp;lt;/summary&amp;gt;
    public class BinaryContentResult : ActionResult
    {
        public byte[] Data { get; set; }
        public NameValueCollection Headers { get; set; }
        public bool Gzip { get; set; }


        public override void ExecuteResult(ControllerContext context)
        {
            foreach (string s in Headers.Keys)
            {
                context.HttpContext.Response.AddHeader(s, Headers[s]);
            }

            if (Gzip)
            {
                using (var os = new GZipOutputStream(context.HttpContext.Response.OutputStream))
                {
                    os.Write(Data, 0, Data.Length);
                }
                context.HttpContext.Response.AddHeader(&amp;quot;Content-Encoding&amp;quot;, &amp;quot;gzip&amp;quot;);
                context.HttpContext.Response.AddHeader(&amp;quot;X-Compressed-By&amp;quot;, &amp;quot;Custom-Compressor&amp;quot;);
            }
            else
            {
                context.HttpContext.Response.BinaryWrite(Data);
            }

            context.HttpContext.Response.End();
        }
    }&lt;/pre&gt;&lt;/blockquote&gt;&lt;img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=05fb9609-6886-4d2b-b2b1-09e610346795" /&gt;</description>
      <comments>http://www.andrewrea.co.uk/blog/CommentView,guid,05fb9609-6886-4d2b-b2b1-09e610346795.aspx</comments>
      <category>.NET</category>
      <category>ASP.NET MVC</category>
      <category>C#</category>
    </item>
    <item>
      <trackback:ping>http://www.andrewrea.co.uk/blog/Trackback.aspx?guid=2e9b1059-1ffa-45e9-a961-07b117daf1cc</trackback:ping>
      <pingback:server>http://www.andrewrea.co.uk/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.andrewrea.co.uk/blog/PermaLink,guid,2e9b1059-1ffa-45e9-a961-07b117daf1cc.aspx</pingback:target>
      <dc:creator>Andrew Rea</dc:creator>
      <wfw:comment>http://www.andrewrea.co.uk/blog/CommentView,guid,2e9b1059-1ffa-45e9-a961-07b117daf1cc.aspx</wfw:comment>
      <wfw:commentRss>http://www.andrewrea.co.uk/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=2e9b1059-1ffa-45e9-a961-07b117daf1cc</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
If you have not read about it yet or seen it or used it, please visit <a href="http://davybrion.com/blog/2009/12/agatha-1-0/">Davy
Brion’s Blog here</a> and download the Agatha project.  Another link I need to
mention is the following, <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/07/29/integrating-structuremap-with-wcf.aspx">Integrating
Strcuture Map With WCF</a>.  Basically what I have attempted to do is create
an <strong>Agatha.Common.InversionOfControl.IContainer</strong> implementation for
Agatha which uses StrcutureMap as the IOC Container.  I am also not hosting the
WCF Service inside a Web Application but in an actual WCF Service Application which
I wanted to use the Service Host Factory as demoed in the above link.
</p>
        <p>
The implementation for the Container was relatively straight forward in most parts
and allowed me to use some newer features of StructureMap which I do not currently
use yet in my job; well I say <em>newer,</em> newer to me!!.  I have read on
Davy Brion’s blog that he is intending to write this Agatha IOC Container for Structure
Map, and I look forward to it, but in the mean time I thought I would have a crack
at it myself.
</p>
        <p>
While writing the Container for StructureMap I had to make a small change/addition
to the Agatha source code, on the interface for the IContainer to make sure that a
method had a generic type constraint.  The method:
</p>
        <p>
          <strong>void Register&lt;TComponent,TImplementation&gt;()</strong>
        </p>
        <p>
A compile time error was raised which stated that there was no information to allow
for boxing/unboxing.  To solve this I added the following constraint:
</p>
        <p>
          <strong>void Register&lt;TComponent,TImplementation&gt;() where TImplementation :
TComponent</strong>
        </p>
        <p>
Once added the compile time error went, but I was still left with another issue which
at this stage of writing this post I am of the opinion that I need to also make a
small addition to StructureMap.  I look forward to it, if it is not already available
but it would be good to find out that it is already accounted for.  The operation
which I am talking about is the removal of an instance from the IOC Container. 
The interface for the Agatha IOC IContainer has a method called Release which takes
an object instance as a parameter and with the Castle WInsor you <strong>can</strong> release
an instance.
</p>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">    public interface IContainer
    {
        void Register&lt;TComponent, TImplementation&gt;(Lifestyle lifestyle) where TImplementation : TComponent;
        void Register(Type componentType, Type implementationType, Lifestyle lifeStyle);
        void RegisterInstance&lt;TComponent&gt;(TComponent instance);
        void RegisterInstance(Type componentType, object instance);
        void Release(object component);
        TComponent Resolve&lt;TComponent&gt;();
        object Resolve(Type componentType);
    }</pre>
        <p>
…
</p>
        <p>
After doing a bit more searching I cannot find a function which fits this criteria
exactly.  There is the <strong>EjectAllInstancesOf&lt;T&gt;</strong> method,
but the one I ended up using is the following:
</p>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">        public void Release(object component)
        {
            //throw new NotImplementedException();
            _strcutureMapContainer.Model.EjectAndRemove(component.GetType());
        }</pre>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"> </pre>
        <p>
This is a method on the IContainer interface and I am using the component to get its
type and releasing all instances of it within the IOC Container.  I am not 100%
sure this is what other implementation of IOC are doing with this particular type
of function.  Never the less, this does work fine and I am now up and running
with the Agatha library inside a WCF Service Application Project using a ServiceHostFactory
and configuring a StructureMap IOC Container for use with Agatha.
</p>
        <p>
I have not made the most consistent approach to the StructureMap usage as I have mixed
preferred and deprecated methods.  This is because I am not 100% sure how to
map the new style of Lifeycle management between Castle Windsor and StructureMap.
I look forward to seeing the actual implementation which goes into the Agatha project
so I can see where I could have improved my attempt.  Here is the finished code
of my attempt.
</p>
        <p>
Hope this is of some help,
</p>
        <p>
Cheers,
</p>
        <p>
Andrew
</p>
        <pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using sm = StructureMap;
using Agatha.Common.InversionOfControl;

namespace Agatha.StructureMap
{
    public class Container : Agatha.Common.InversionOfControl.IContainer
    {
        private readonly sm.IContainer _strcutureMapContainer;

        private Dictionary&lt;Lifestyle, sm.InstanceScope&gt; _lifeStyleMappings = new Dictionary&lt;Lifestyle, sm.InstanceScope&gt;
        {
            {Lifestyle.Singleton, sm.InstanceScope.Singleton},
            {Lifestyle.Transient, sm.InstanceScope.Transient}
        };

        private Dictionary&lt;Lifestyle, sm.Pipeline.ILifecycle&gt; _lifeStyleLifeCycleMappings = new Dictionary&lt;Lifestyle, sm.Pipeline.ILifecycle&gt;
        {
             {Lifestyle.Singleton, new sm.Pipeline.SingletonLifecycle()},
            {Lifestyle.Transient, new sm.Pipeline.UniquePerRequestLifecycle()}
        };

        public Container() : this(new sm.Container()) { }

        public Container(sm.IContainer structureMapContainer)
        {
            _strcutureMapContainer = structureMapContainer;
        }

        public void Register(Type componentType, Type implementationType, Lifestyle lifeStyle)
        {
            _strcutureMapContainer.Configure(x =&gt; x.For(componentType).LifecycleIs(_lifeStyleMappings[lifeStyle]).Use(implementationType));
        }

        public void Register&lt;TComponent, TImplementation&gt;(Lifestyle lifestyle) where TImplementation:TComponent
        {
            _strcutureMapContainer.Configure(x =&gt; x.ForRequestedType&lt;TComponent&gt;()
                .CacheBy(_lifeStyleMappings[lifestyle])
                .TheDefaultIsConcreteType&lt;TImplementation&gt;());
        }

        public void RegisterInstance(Type componentType, object instance)
        {
            _strcutureMapContainer.Configure(x =&gt; x.ForRequestedType(componentType).Use(instance));
        }

        public void RegisterInstance&lt;TComponent&gt;(TComponent instance)
        {
            _strcutureMapContainer.Configure(x =&gt; x.For&lt;TComponent&gt;().Use(instance));
        }

        public TComponent Resolve&lt;TComponent&gt;()
        {
            return _strcutureMapContainer.GetInstance&lt;TComponent&gt;();
        }

        public object Resolve(Type componentType)
        {
            return _strcutureMapContainer.GetInstance(componentType);
        }

        public void Release(object component)
        {
            //throw new NotImplementedException();
            _strcutureMapContainer.Model.EjectAndRemove(component.GetType());
        }
        
    }
}</pre>
        <img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=2e9b1059-1ffa-45e9-a961-07b117daf1cc" />
      </body>
      <title>A StructureMap Container For Agatha</title>
      <guid isPermaLink="false">http://www.andrewrea.co.uk/blog/PermaLink,guid,2e9b1059-1ffa-45e9-a961-07b117daf1cc.aspx</guid>
      <link>http://www.andrewrea.co.uk/blog/2010/02/10/AStructureMapContainerForAgatha.aspx</link>
      <pubDate>Wed, 10 Feb 2010 22:16:44 GMT</pubDate>
      <description>&lt;p&gt;
If you have not read about it yet or seen it or used it, please visit &lt;a href="http://davybrion.com/blog/2009/12/agatha-1-0/"&gt;Davy
Brion’s Blog here&lt;/a&gt; and download the Agatha project.&amp;nbsp; Another link I need to
mention is the following, &lt;a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/07/29/integrating-structuremap-with-wcf.aspx"&gt;Integrating
Strcuture Map With WCF&lt;/a&gt;.&amp;nbsp; Basically what I have attempted to do is create
an &lt;strong&gt;Agatha.Common.InversionOfControl.IContainer&lt;/strong&gt; implementation for
Agatha which uses StrcutureMap as the IOC Container.&amp;nbsp; I am also not hosting the
WCF Service inside a Web Application but in an actual WCF Service Application which
I wanted to use the Service Host Factory as demoed in the above link.
&lt;/p&gt;
&lt;p&gt;
The implementation for the Container was relatively straight forward in most parts
and allowed me to use some newer features of StructureMap which I do not currently
use yet in my job; well I say &lt;em&gt;newer,&lt;/em&gt; newer to me!!.&amp;nbsp; I have read on
Davy Brion’s blog that he is intending to write this Agatha IOC Container for Structure
Map, and I look forward to it, but in the mean time I thought I would have a crack
at it myself.
&lt;/p&gt;
&lt;p&gt;
While writing the Container for StructureMap I had to make a small change/addition
to the Agatha source code, on the interface for the IContainer to make sure that a
method had a generic type constraint.&amp;nbsp; The method:
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;void Register&amp;lt;TComponent,TImplementation&amp;gt;()&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
A compile time error was raised which stated that there was no information to allow
for boxing/unboxing.&amp;nbsp; To solve this I added the following constraint:
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;void Register&amp;lt;TComponent,TImplementation&amp;gt;() where TImplementation :
TComponent&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Once added the compile time error went, but I was still left with another issue which
at this stage of writing this post I am of the opinion that I need to also make a
small addition to StructureMap.&amp;nbsp; I look forward to it, if it is not already available
but it would be good to find out that it is already accounted for.&amp;nbsp; The operation
which I am talking about is the removal of an instance from the IOC Container.&amp;nbsp;
The interface for the Agatha IOC IContainer has a method called Release which takes
an object instance as a parameter and with the Castle WInsor you &lt;strong&gt;can&lt;/strong&gt; release
an instance.
&lt;/p&gt;
&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;    public interface IContainer
    {
        void Register&amp;lt;TComponent, TImplementation&amp;gt;(Lifestyle lifestyle) where TImplementation : TComponent;
        void Register(Type componentType, Type implementationType, Lifestyle lifeStyle);
        void RegisterInstance&amp;lt;TComponent&amp;gt;(TComponent instance);
        void RegisterInstance(Type componentType, object instance);
        void Release(object component);
        TComponent Resolve&amp;lt;TComponent&amp;gt;();
        object Resolve(Type componentType);
    }&lt;/pre&gt;
&lt;p&gt;
…
&lt;/p&gt;
&lt;p&gt;
After doing a bit more searching I cannot find a function which fits this criteria
exactly.&amp;nbsp; There is the &lt;strong&gt;EjectAllInstancesOf&amp;lt;T&amp;gt;&lt;/strong&gt; method,
but the one I ended up using is the following:
&lt;/p&gt;
&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;        public void Release(object component)
        {
            //throw new NotImplementedException();
            _strcutureMapContainer.Model.EjectAndRemove(component.GetType());
        }&lt;/pre&gt;&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;&amp;nbsp;&lt;/pre&gt;
&lt;p&gt;
This is a method on the IContainer interface and I am using the component to get its
type and releasing all instances of it within the IOC Container.&amp;nbsp; I am not 100%
sure this is what other implementation of IOC are doing with this particular type
of function.&amp;nbsp; Never the less, this does work fine and I am now up and running
with the Agatha library inside a WCF Service Application Project using a ServiceHostFactory
and configuring a StructureMap IOC Container for use with Agatha.
&lt;/p&gt;
&lt;p&gt;
I have not made the most consistent approach to the StructureMap usage as I have mixed
preferred and deprecated methods.&amp;nbsp; This is because I am not 100% sure how to
map the new style of Lifeycle management between Castle Windsor and StructureMap.
I look forward to seeing the actual implementation which goes into the Agatha project
so I can see where I could have improved my attempt.&amp;nbsp; Here is the finished code
of my attempt.
&lt;/p&gt;
&lt;p&gt;
Hope this is of some help,
&lt;/p&gt;
&lt;p&gt;
Cheers,
&lt;/p&gt;
&lt;p&gt;
Andrew
&lt;/p&gt;
&lt;pre class="brush: csharp; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"&gt;using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using sm = StructureMap;
using Agatha.Common.InversionOfControl;

namespace Agatha.StructureMap
{
    public class Container : Agatha.Common.InversionOfControl.IContainer
    {
        private readonly sm.IContainer _strcutureMapContainer;

        private Dictionary&amp;lt;Lifestyle, sm.InstanceScope&amp;gt; _lifeStyleMappings = new Dictionary&amp;lt;Lifestyle, sm.InstanceScope&amp;gt;
        {
            {Lifestyle.Singleton, sm.InstanceScope.Singleton},
            {Lifestyle.Transient, sm.InstanceScope.Transient}
        };

        private Dictionary&amp;lt;Lifestyle, sm.Pipeline.ILifecycle&amp;gt; _lifeStyleLifeCycleMappings = new Dictionary&amp;lt;Lifestyle, sm.Pipeline.ILifecycle&amp;gt;
        {
             {Lifestyle.Singleton, new sm.Pipeline.SingletonLifecycle()},
            {Lifestyle.Transient, new sm.Pipeline.UniquePerRequestLifecycle()}
        };

        public Container() : this(new sm.Container()) { }

        public Container(sm.IContainer structureMapContainer)
        {
            _strcutureMapContainer = structureMapContainer;
        }

        public void Register(Type componentType, Type implementationType, Lifestyle lifeStyle)
        {
            _strcutureMapContainer.Configure(x =&amp;gt; x.For(componentType).LifecycleIs(_lifeStyleMappings[lifeStyle]).Use(implementationType));
        }

        public void Register&amp;lt;TComponent, TImplementation&amp;gt;(Lifestyle lifestyle) where TImplementation:TComponent
        {
            _strcutureMapContainer.Configure(x =&amp;gt; x.ForRequestedType&amp;lt;TComponent&amp;gt;()
                .CacheBy(_lifeStyleMappings[lifestyle])
                .TheDefaultIsConcreteType&amp;lt;TImplementation&amp;gt;());
        }

        public void RegisterInstance(Type componentType, object instance)
        {
            _strcutureMapContainer.Configure(x =&amp;gt; x.ForRequestedType(componentType).Use(instance));
        }

        public void RegisterInstance&amp;lt;TComponent&amp;gt;(TComponent instance)
        {
            _strcutureMapContainer.Configure(x =&amp;gt; x.For&amp;lt;TComponent&amp;gt;().Use(instance));
        }

        public TComponent Resolve&amp;lt;TComponent&amp;gt;()
        {
            return _strcutureMapContainer.GetInstance&amp;lt;TComponent&amp;gt;();
        }

        public object Resolve(Type componentType)
        {
            return _strcutureMapContainer.GetInstance(componentType);
        }

        public void Release(object component)
        {
            //throw new NotImplementedException();
            _strcutureMapContainer.Model.EjectAndRemove(component.GetType());
        }
        
    }
}&lt;/pre&gt;&lt;img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=2e9b1059-1ffa-45e9-a961-07b117daf1cc" /&gt;</description>
      <comments>http://www.andrewrea.co.uk/blog/CommentView,guid,2e9b1059-1ffa-45e9-a961-07b117daf1cc.aspx</comments>
      <category>.NET</category>
      <category>Architecture</category>
      <category>C#</category>
      <category>WCF</category>
    </item>
    <item>
      <trackback:ping>http://www.andrewrea.co.uk/blog/Trackback.aspx?guid=8d904ba2-c1cc-46dd-8b18-788a2b1cc837</trackback:ping>
      <pingback:server>http://www.andrewrea.co.uk/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.andrewrea.co.uk/blog/PermaLink,guid,8d904ba2-c1cc-46dd-8b18-788a2b1cc837.aspx</pingback:target>
      <dc:creator>Andrew Rea</dc:creator>
      <wfw:comment>http://www.andrewrea.co.uk/blog/CommentView,guid,8d904ba2-c1cc-46dd-8b18-788a2b1cc837.aspx</wfw:comment>
      <wfw:commentRss>http://www.andrewrea.co.uk/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=8d904ba2-c1cc-46dd-8b18-788a2b1cc837</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I want to get a few blog posts out of the way as I have left off blogging until I
had a suitable Syntax Highlighter plug-in for Windows Live Writer. 
</p>
        <p>
This morning whilst I am literally inside VS 2010 developing, the computer froze,
restarted and then informed me that it could not find a valid boot sector…joy! 
Once this happened following my other computer blowing up and the laptop being on
the fritz I thought I would finally take the plunge and get on with using Linux, more
than that I want to use Linux and Windows i.e. Duel Boot.  
</p>
        <p>
Before I started however I needed to backup the files that I had on the hard drive
which has just gone west, this hard drive is a PATA and all the external enclosures
I have are for SATA.  So one small purchase was an external enclosure for this
which only set me back 17.00GBP, bonus.  I have another of these PATA hard drive
which I had previously tried to install CENT OS onto and it went wrong, period; so
with this new hardware I was easily able to wire up and format, bang back into the
desktop and boot from CD.  
</p>
        <h3>Installing Ubuntu next to Windows 7
</h3>
        <p>
          <strong>IMPORTANT : Install Windows first.  I have been told this in person and
also read about it afterwards, please read up about the WHY? but either way, it is
better with Windows first.</strong>
        </p>
        <ol>
          <li>
Install Windows</li>
          <li>
Go to Computer Management inside Administrative Tools</li>
          <li>
Right click on your main volume which windows is installed on</li>
          <li>
Select, Shrink Volume.</li>
        </ol>
        <p>
After the process calculates how much space it can reduce the volume by, you can select
the size of the reduction and in turn giving the amount of space you will be left
with on the new partition.  
</p>
        <p>
Once complete, restart your computer.
</p>
        <p>
          <strong>NEXT:</strong>
        </p>
        <ol>
          <li>
Insert your Ubuntu disk which you download and burned the ISO to disk</li>
          <li>
Close any dialogue it raises for the Auto Run and then restart your machine again</li>
          <li>
This should now boot into Ubuntu automatically assuming you allow booting from CD/DVD
in the bios.</li>
          <li>
Select the second option which is to install Ubuntu and then follow through the steps
until you get to the partition manager.</li>
        </ol>
        <p>
The top line should inform you that it has found WIndows 7 already on your computer,
and beneath that it gives you an option to install Ubuntu side by side to this. 
This is the option you want and after selection continue and confirm all the changes
to be written to disk.  Continue through the confirmation dialogues until completion.
</p>
        <h3>On Restart
</h3>
        <p>
After the above is complete you get a really useful boot screen where you can select
to boot Ubuntu or Windows.  I am well impressed with this and cannot believe
I have not done this sooner.  
</p>
        <p>
I am a total newcomer to the Linux scene, but so far so good.  One small thing
which I would point out is the apparent lack of a desktop blog publishing tool with
equal capabilities and extensibility as Windows Live Writer.  But hey, reboot,
load windows and blog there… for now lol!!
</p>
        <p>
Cheers for now,
</p>
        <p>
Andrew
</p>
        <img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=8d904ba2-c1cc-46dd-8b18-788a2b1cc837" />
      </body>
      <title>Duel Booting Linux and Windows 7</title>
      <guid isPermaLink="false">http://www.andrewrea.co.uk/blog/PermaLink,guid,8d904ba2-c1cc-46dd-8b18-788a2b1cc837.aspx</guid>
      <link>http://www.andrewrea.co.uk/blog/2010/01/25/DuelBootingLinuxAndWindows7.aspx</link>
      <pubDate>Mon, 25 Jan 2010 19:28:30 GMT</pubDate>
      <description>&lt;p&gt;
I want to get a few blog posts out of the way as I have left off blogging until I
had a suitable Syntax Highlighter plug-in for Windows Live Writer. 
&lt;/p&gt;
&lt;p&gt;
This morning whilst I am literally inside VS 2010 developing, the computer froze,
restarted and then informed me that it could not find a valid boot sector…joy!&amp;#160;
Once this happened following my other computer blowing up and the laptop being on
the fritz I thought I would finally take the plunge and get on with using Linux, more
than that I want to use Linux and Windows i.e. Duel Boot.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
Before I started however I needed to backup the files that I had on the hard drive
which has just gone west, this hard drive is a PATA and all the external enclosures
I have are for SATA.&amp;#160; So one small purchase was an external enclosure for this
which only set me back 17.00GBP, bonus.&amp;#160; I have another of these PATA hard drive
which I had previously tried to install CENT OS onto and it went wrong, period; so
with this new hardware I was easily able to wire up and format, bang back into the
desktop and boot from CD.&amp;#160; 
&lt;/p&gt;
&lt;h3&gt;Installing Ubuntu next to Windows 7
&lt;/h3&gt;
&lt;p&gt;
&lt;strong&gt;IMPORTANT : Install Windows first.&amp;#160; I have been told this in person and
also read about it afterwards, please read up about the WHY? but either way, it is
better with Windows first.&lt;/strong&gt;
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
Install Windows&lt;/li&gt;
&lt;li&gt;
Go to Computer Management inside Administrative Tools&lt;/li&gt;
&lt;li&gt;
Right click on your main volume which windows is installed on&lt;/li&gt;
&lt;li&gt;
Select, Shrink Volume.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
After the process calculates how much space it can reduce the volume by, you can select
the size of the reduction and in turn giving the amount of space you will be left
with on the new partition.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
Once complete, restart your computer.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;NEXT:&lt;/strong&gt;
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
Insert your Ubuntu disk which you download and burned the ISO to disk&lt;/li&gt;
&lt;li&gt;
Close any dialogue it raises for the Auto Run and then restart your machine again&lt;/li&gt;
&lt;li&gt;
This should now boot into Ubuntu automatically assuming you allow booting from CD/DVD
in the bios.&lt;/li&gt;
&lt;li&gt;
Select the second option which is to install Ubuntu and then follow through the steps
until you get to the partition manager.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
The top line should inform you that it has found WIndows 7 already on your computer,
and beneath that it gives you an option to install Ubuntu side by side to this.&amp;#160;
This is the option you want and after selection continue and confirm all the changes
to be written to disk.&amp;#160; Continue through the confirmation dialogues until completion.
&lt;/p&gt;
&lt;h3&gt;On Restart
&lt;/h3&gt;
&lt;p&gt;
After the above is complete you get a really useful boot screen where you can select
to boot Ubuntu or Windows.&amp;#160; I am well impressed with this and cannot believe
I have not done this sooner.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
I am a total newcomer to the Linux scene, but so far so good.&amp;#160; One small thing
which I would point out is the apparent lack of a desktop blog publishing tool with
equal capabilities and extensibility as Windows Live Writer.&amp;#160; But hey, reboot,
load windows and blog there… for now lol!!
&lt;/p&gt;
&lt;p&gt;
Cheers for now,
&lt;/p&gt;
&lt;p&gt;
Andrew
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=8d904ba2-c1cc-46dd-8b18-788a2b1cc837" /&gt;</description>
      <comments>http://www.andrewrea.co.uk/blog/CommentView,guid,8d904ba2-c1cc-46dd-8b18-788a2b1cc837.aspx</comments>
      <category>Linux</category>
      <category>Operating Systems</category>
      <category>Windows</category>
    </item>
    <item>
      <trackback:ping>http://www.andrewrea.co.uk/blog/Trackback.aspx?guid=a579aeb0-c123-4e28-b47e-3d2d04f465de</trackback:ping>
      <pingback:server>http://www.andrewrea.co.uk/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.andrewrea.co.uk/blog/PermaLink,guid,a579aeb0-c123-4e28-b47e-3d2d04f465de.aspx</pingback:target>
      <dc:creator>Andrew Rea</dc:creator>
      <wfw:comment>http://www.andrewrea.co.uk/blog/CommentView,guid,a579aeb0-c123-4e28-b47e-3d2d04f465de.aspx</wfw:comment>
      <wfw:commentRss>http://www.andrewrea.co.uk/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=a579aeb0-c123-4e28-b47e-3d2d04f465de</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Due to a home dev project I am currently involved in with another contributor, called <a href="http://twitter.com/byteface">byteface</a>,
it has lead me to using the Google AppEngine and specifically the Python flavour as
opposed to the Java flavour.  I chose Python as I am enjoying further exposure
to different programming languages.  The Django framework is nearly entirely
supported on the Google AppEngine with some modules omitted due to either security
considerations or conflict.  Both the DJango framework and the Google AppEngine
have their own ORM, so this is one of the module omissions where you have to use the
Google ORM, (wonder if they ever thought of doing GHibernate ;-)).
</p>
        <p>
          <a href="/content/binary/WindowsLiveWriter/Cre.0projecttemplatewithDjangoandtheGoog_2EC7/image_2.png">
            <img style="border-bottom: 0px; border-left: 0px; margin: 0px 0px 0px 10px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" align="right" src="/blog/content/binary/WindowsLiveWriter/Cre.0projecttemplatewithDjangoandtheGoog_2EC7/image_thumb.png" width="300" height="655" />
          </a>Another
point to make also is that you can choose to use the Google http handler functions
or DJango’s.  I have gone with Django’s so I can get a complete experience of
the framework and utilise all of the powerful utilities and features.
</p>
        <p>
In this post I want to show how you can emulate the project structure of a default
ASP.NET MVC 1.0 application, i.e. File –&gt; New –&gt; ASP.NET MVC Application inside
Visual Studio.  The image on the right is an example of one freshly created,
all I have done is remove any references to Account, as for the purposes of this example
I just want to emulate the core things like structure and behaviour.
</p>
        <p>
The following are considerations which I need to think about in order to emulate Microsoft’s
ASP.NET implementation of MVC including:
</p>
        <ul>
          <li>
Master page templates</li>
          <ul>
            <li>
i.e. Site.Master</li>
          </ul>
          <li>
Static content</li>
          <li>
Routing</li>
          <li>
Controller Actions</li>
          <ul>
            <li>
Including HTTP Verb restrictions</li>
          </ul>
          <li>
General layout</li>
        </ul>
        <p>
Off the top of my head one thing which will need to be an add in is the routing, as
this is due to one of the rules/principles of python:
</p>
        <blockquote>
          <p>
            <strong>Explicit is better than implicit</strong>
          </p>
        </blockquote>
        <p>
So basically in the context of routing, we would have to define all of our routes
as opposed to what we can do in ASP.NET MVC and have a route to match the {controller}/{action}/{id}
url pattern.  From a little research I did, Ruby on Rails also has this out of
the box.  So I am not sure if I will be able to manage this part of the project
in this post, so when I find a robust way of doing it inside Django I will again post
something about it.  It may be the case I stick with the explicit route and conform
to the <strong>Zen of Python(&gt;&gt;&gt; import this)</strong>.
</p>
        <h2>Google App Engine SDK Console
</h2>
        <p>
If you have not done already, you will need to download the SDK and create the application. 
I am using the GUI for this, so download and create an application.  The folder
structure should have been created for you.  In the case of this example I named
my application narbley and in return in created the following folder structure inside
my app engine source path:
</p>
        <ul>
          <li>
narbley</li>
          <ul>
            <li>
narbley</li>
          </ul>
        </ul>
        <p>
So it created a folder with the same name inside this folder with the relevant application
files for Google App Engine. Because I want to use the Django framework, I deleted
the nested narbley folder as I will create this using the django-admin utility.
</p>
        <p>
To create the base django app files I ran the following cmd from inside my application
folder:
</p>
        <blockquote>
          <p>
django-admin-py startproject narbley
</p>
        </blockquote>
        <blockquote>
          <p>
            <strong>What is narbley? </strong>Simply a code name for this project I am working
on with a fellow contributor.  It is a codename for many reasons including, we
are not 100% sure on what we are building yet, that and it is very difficult to find
a name for a Google AppEngine … App which is not taken, so we tried to be abstract,
and failing that we simply kept adding a letter to the end and trying it, hence <strong>narbley</strong> was
created.
</p>
        </blockquote>
        <p>
Also you will need to follow this short how to, to use the Django Framework completely
over the Google one, <a href="http://code.google.com/appengine/articles/django.html">http://code.google.com/appengine/articles/django.html</a></p>
        <h2>The Home Controller
</h2>
        <p>
From what I have seen, in Python and Django the views are actually a front controller. 
I would not class the function which handles the request the view, in the context
of DJango I would  regard the templates as the views, the controller as the front
controller with the different actions on and the model, the model.
</p>
        <p>
For the http verb restriction you find in the ASP.NET MVC 1.0 implementation, I did
some searching about and actually came back to finding that one has already been written
in DJango and its usage should very familiar to you.
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:74b11ec6-e235-411e-830f-be7f3e9a7bca" class="wlWriterEditableSmartContent">
          <pre name="code" class="brush: c#">from django.template import Context, loader
from django.http import HttpResponse
from django.views.decorators.http import require_http_methods
12
@require_http_methods(["GET"])
def index(request):
    t = loader.get_template('home/index.html')
    c = Context({
        'message': "Welcome to the Django Framework on the Google App Engine"
    })
    return HttpResponse(t.render(c))

@require_http_methods(["GET"])
def about(request):
    t = loader.get_template('home/about.html')
    c = Context({
        'message': "Narbley is the codename"
    })
    return HttpResponse(t.render(c))
</pre>
        </div>
        <p>
Great so that is the index and the about page sorted.  One thing I will point
out here is a point with regards to how python handles namespaces/file structure/packages
or how ever you want to call the equivalent.  I have created a folder called
controllers and inside I have a file called homecontroller.py.  I also need to
add the file __init__.py .  Unfortunately as of this moment I cannot tell you
why, only that I know it requires it, and subsequently I think for any other folder
nesting. 
</p>
        <h2>Master/Content Page Templates
</h2>
        <p>
These are self explanatory and their implementation quite similar, with a simple change
to the import and the syntax of course.  From my experience to date, the DJango
templates require the .html extension whether they are content or master.  You
need to add a reference to any folders which will be deemed as template folders inside
the settings.py file, i.e.:
</p>
        <p>
        </p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:1a7f8be1-1823-4d9d-885e-cab88095a7f9" class="wlWriterEditableSmartContent">
          <pre name="code" class="brush: c#">ROOT_PATH = os.path.dirname(__file__)
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    ROOT_PATH + '/views',
)</pre>
        </div>
        <p>
Inline with the project files from a default ASP.NET MVC Project I have simply copied
and changed the files to use the DJango templating syntax, notice how:
</p>
        <ul>
          <li>
The content placeholders are defined</li>
          <li>
The master page is defined and referenced</li>
        </ul>
        <h3>The master page (views/shared/master.html)
</h3>
        <p>
        </p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:e69e9f89-eb9d-4d41-b5cd-c4b6a76bdfa9" class="wlWriterEditableSmartContent">
          <pre name="code" class="brush: c#">&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head runat="server"&gt;
    &lt;title&gt;{% block title %}{% endblock %}&lt;/title&gt;
    &lt;link href="/content/site.css" rel="stylesheet" type="text/css" /&gt;
    {% block css_includes %}{% endblock %}
    {% block script_includes %}{% endblock %}
&lt;/head&gt;

&lt;body&gt;
    &lt;div class="page"&gt;

        &lt;div id="header"&gt;
            &lt;div id="title"&gt;
                &lt;h1&gt;My MVC Application&lt;/h1&gt;
            &lt;/div&gt;
            
            &lt;div id="menucontainer"&gt;
            
                &lt;ul id="menu"&gt;              
                    &lt;li&gt;&lt;a href="/home/"&gt;Home&lt;/a&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;a href="/home/about/"&gt;About&lt;/a&gt;&lt;/li&gt;
                &lt;/ul&gt;
            
            &lt;/div&gt;
	&lt;br style="clear:both"/&gt;
        &lt;/div&gt;

        &lt;div id="main"&gt;
            {% block content %}{% endblock %}

            &lt;div id="footer"&gt;
		{% block footer %}{% endblock %}
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
        </div>
        <h3>The homepage (views/home/index.html)
</h3>
        <p>
I am only attaching the code for the homepage as the about page is very similar.
</p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:afac7d25-ee72-467d-b05c-83db7090a77a" class="wlWriterEditableSmartContent">
          <pre name="code" class="brush: c#">{% extends "shared/master.html" %}

{% block title %}DJango Example{% endblock %}
{% block css_includes %}{% endblock %}
{% block script_includes %}{% endblock %}


{% block content %}
&lt;p&gt;{{ message }}.&lt;/p&gt;
{% endblock %}

{% block footer %}
Footer here
{% endblock %}</pre>
        </div>
        <p>
          <a href="/content/binary/WindowsLiveWriter/Cre.0projecttemplatewithDjangoandtheGoog_2EC7/image_4.png">
            <img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="image" border="0" alt="image" align="right" src="/blog/content/binary/WindowsLiveWriter/Cre.0projecttemplatewithDjangoandtheGoog_2EC7/image_thumb_1.png" width="304" height="647" />
          </a> Apart
from that there is just the default application files required by Python/DJango and
Google App Engine.  I am currently looking into:
</p>
        <ul>
          <li>
Routing</li>
          <li>
Extension less Urls</li>
          <li>
JSON support libraries in Python</li>
          <li>
The Message Queue of the Google App Engine</li>
        </ul>
        <p>
The resulting project structure for the base project is shown on the right. 
I opened the website inside Visual Studio to see the structure, not for editing lol.
</p>
        <p>
I should have deleted it but I have not, the http_methods file is not used, I forgot
to delete.
</p>
        <p>
Cheers,
</p>
        <p>
Andrew
</p>
        <img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=a579aeb0-c123-4e28-b47e-3d2d04f465de" />
      </body>
      <title>Creating a similar Microsoft ASP.NET MVC 1.0 project template with Django and the Google App Engine</title>
      <guid isPermaLink="false">http://www.andrewrea.co.uk/blog/PermaLink,guid,a579aeb0-c123-4e28-b47e-3d2d04f465de.aspx</guid>
      <link>http://www.andrewrea.co.uk/blog/2009/12/20/CreatingASimilarMicrosoftASPNETMVC10ProjectTemplateWithDjangoAndTheGoogleAppEngine.aspx</link>
      <pubDate>Sun, 20 Dec 2009 04:09:25 GMT</pubDate>
      <description>&lt;p&gt;
Due to a home dev project I am currently involved in with another contributor, called &lt;a href="http://twitter.com/byteface"&gt;byteface&lt;/a&gt;,
it has lead me to using the Google AppEngine and specifically the Python flavour as
opposed to the Java flavour.&amp;nbsp; I chose Python as I am enjoying further exposure
to different programming languages.&amp;nbsp; The Django framework is nearly entirely
supported on the Google AppEngine with some modules omitted due to either security
considerations or conflict.&amp;nbsp; Both the DJango framework and the Google AppEngine
have their own ORM, so this is one of the module omissions where you have to use the
Google ORM, (wonder if they ever thought of doing GHibernate ;-)).
&lt;/p&gt;
&lt;p&gt;
&lt;a href="/content/binary/WindowsLiveWriter/Cre.0projecttemplatewithDjangoandtheGoog_2EC7/image_2.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; margin: 0px 0px 0px 10px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" align="right" src="/blog/content/binary/WindowsLiveWriter/Cre.0projecttemplatewithDjangoandtheGoog_2EC7/image_thumb.png" width="300" height="655"&gt;&lt;/a&gt;Another
point to make also is that you can choose to use the Google http handler functions
or DJango’s.&amp;nbsp; I have gone with Django’s so I can get a complete experience of
the framework and utilise all of the powerful utilities and features.
&lt;/p&gt;
&lt;p&gt;
In this post I want to show how you can emulate the project structure of a default
ASP.NET MVC 1.0 application, i.e. File –&amp;gt; New –&amp;gt; ASP.NET MVC Application inside
Visual Studio.&amp;nbsp; The image on the right is an example of one freshly created,
all I have done is remove any references to Account, as for the purposes of this example
I just want to emulate the core things like structure and behaviour.
&lt;/p&gt;
&lt;p&gt;
The following are considerations which I need to think about in order to emulate Microsoft’s
ASP.NET implementation of MVC including:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
Master page templates&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;
i.e. Site.Master&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;
Static content&lt;/li&gt;
&lt;li&gt;
Routing&lt;/li&gt;
&lt;li&gt;
Controller Actions&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;
Including HTTP Verb restrictions&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;
General layout&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Off the top of my head one thing which will need to be an add in is the routing, as
this is due to one of the rules/principles of python:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
&lt;strong&gt;Explicit is better than implicit&lt;/strong&gt;
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
So basically in the context of routing, we would have to define all of our routes
as opposed to what we can do in ASP.NET MVC and have a route to match the {controller}/{action}/{id}
url pattern.&amp;nbsp; From a little research I did, Ruby on Rails also has this out of
the box.&amp;nbsp; So I am not sure if I will be able to manage this part of the project
in this post, so when I find a robust way of doing it inside Django I will again post
something about it.&amp;nbsp; It may be the case I stick with the explicit route and conform
to the &lt;strong&gt;Zen of Python(&amp;gt;&amp;gt;&amp;gt; import this)&lt;/strong&gt;.
&lt;/p&gt;
&lt;h2&gt;Google App Engine SDK Console
&lt;/h2&gt;
&lt;p&gt;
If you have not done already, you will need to download the SDK and create the application.&amp;nbsp;
I am using the GUI for this, so download and create an application.&amp;nbsp; The folder
structure should have been created for you.&amp;nbsp; In the case of this example I named
my application narbley and in return in created the following folder structure inside
my app engine source path:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
narbley&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;
narbley&lt;/li&gt;
&lt;/ul&gt;
&lt;/ul&gt;
&lt;p&gt;
So it created a folder with the same name inside this folder with the relevant application
files for Google App Engine. Because I want to use the Django framework, I deleted
the nested narbley folder as I will create this using the django-admin utility.
&lt;/p&gt;
&lt;p&gt;
To create the base django app files I ran the following cmd from inside my application
folder:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
django-admin-py startproject narbley
&lt;/p&gt;
&lt;/blockquote&gt; &lt;blockquote&gt; 
&lt;p&gt;
&lt;strong&gt;What is narbley? &lt;/strong&gt;Simply a code name for this project I am working
on with a fellow contributor.&amp;nbsp; It is a codename for many reasons including, we
are not 100% sure on what we are building yet, that and it is very difficult to find
a name for a Google AppEngine … App which is not taken, so we tried to be abstract,
and failing that we simply kept adding a letter to the end and trying it, hence &lt;strong&gt;narbley&lt;/strong&gt; was
created.
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Also you will need to follow this short how to, to use the Django Framework completely
over the Google one, &lt;a href="http://code.google.com/appengine/articles/django.html"&gt;http://code.google.com/appengine/articles/django.html&lt;/a&gt;
&lt;/p&gt;
&lt;h2&gt;The Home Controller
&lt;/h2&gt;
&lt;p&gt;
From what I have seen, in Python and Django the views are actually a front controller.&amp;nbsp;
I would not class the function which handles the request the view, in the context
of DJango I would&amp;nbsp; regard the templates as the views, the controller as the front
controller with the different actions on and the model, the model.
&lt;/p&gt;
&lt;p&gt;
For the http verb restriction you find in the ASP.NET MVC 1.0 implementation, I did
some searching about and actually came back to finding that one has already been written
in DJango and its usage should very familiar to you.
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:74b11ec6-e235-411e-830f-be7f3e9a7bca" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="brush: c#"&gt;from django.template import Context, loader
from django.http import HttpResponse
from django.views.decorators.http import require_http_methods
12
@require_http_methods(["GET"])
def index(request):
    t = loader.get_template('home/index.html')
    c = Context({
        'message': "Welcome to the Django Framework on the Google App Engine"
    })
    return HttpResponse(t.render(c))

@require_http_methods(["GET"])
def about(request):
    t = loader.get_template('home/about.html')
    c = Context({
        'message': "Narbley is the codename"
    })
    return HttpResponse(t.render(c))
&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Great so that is the index and the about page sorted.&amp;nbsp; One thing I will point
out here is a point with regards to how python handles namespaces/file structure/packages
or how ever you want to call the equivalent.&amp;nbsp; I have created a folder called
controllers and inside I have a file called homecontroller.py.&amp;nbsp; I also need to
add the file __init__.py .&amp;nbsp; Unfortunately as of this moment I cannot tell you
why, only that I know it requires it, and subsequently I think for any other folder
nesting. 
&lt;/p&gt;
&lt;h2&gt;Master/Content Page Templates
&lt;/h2&gt;
&lt;p&gt;
These are self explanatory and their implementation quite similar, with a simple change
to the import and the syntax of course.&amp;nbsp; From my experience to date, the DJango
templates require the .html extension whether they are content or master.&amp;nbsp; You
need to add a reference to any folders which will be deemed as template folders inside
the settings.py file, i.e.:
&lt;/p&gt;
&lt;p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:1a7f8be1-1823-4d9d-885e-cab88095a7f9" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="brush: c#"&gt;ROOT_PATH = os.path.dirname(__file__)
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    ROOT_PATH + '/views',
)&lt;/pre&gt;
&lt;/div&gt;
&gt;
&lt;p&gt;
Inline with the project files from a default ASP.NET MVC Project I have simply copied
and changed the files to use the DJango templating syntax, notice how:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
The content placeholders are defined&lt;/li&gt;
&lt;li&gt;
The master page is defined and referenced&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;The master page (views/shared/master.html)
&lt;/h3&gt;
&lt;p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:e69e9f89-eb9d-4d41-b5cd-c4b6a76bdfa9" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="brush: c#"&gt;&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&amp;gt;
&amp;lt;html xmlns="http://www.w3.org/1999/xhtml"&amp;gt;
&amp;lt;head runat="server"&amp;gt;
    &amp;lt;title&amp;gt;{% block title %}{% endblock %}&amp;lt;/title&amp;gt;
    &amp;lt;link href="/content/site.css" rel="stylesheet" type="text/css" /&amp;gt;
    {% block css_includes %}{% endblock %}
    {% block script_includes %}{% endblock %}
&amp;lt;/head&amp;gt;

&amp;lt;body&amp;gt;
    &amp;lt;div class="page"&amp;gt;

        &amp;lt;div id="header"&amp;gt;
            &amp;lt;div id="title"&amp;gt;
                &amp;lt;h1&amp;gt;My MVC Application&amp;lt;/h1&amp;gt;
            &amp;lt;/div&amp;gt;
            
            &amp;lt;div id="menucontainer"&amp;gt;
            
                &amp;lt;ul id="menu"&amp;gt;              
                    &amp;lt;li&amp;gt;&amp;lt;a href="/home/"&amp;gt;Home&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;
                    &amp;lt;li&amp;gt;&amp;lt;a href="/home/about/"&amp;gt;About&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;
                &amp;lt;/ul&amp;gt;
            
            &amp;lt;/div&amp;gt;
	&amp;lt;br style="clear:both"/&amp;gt;
        &amp;lt;/div&amp;gt;

        &amp;lt;div id="main"&amp;gt;
            {% block content %}{% endblock %}

            &amp;lt;div id="footer"&amp;gt;
		{% block footer %}{% endblock %}
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&gt;
&lt;h3&gt;The homepage (views/home/index.html)
&lt;/h3&gt;
&lt;p&gt;
I am only attaching the code for the homepage as the about page is very similar.
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:afac7d25-ee72-467d-b05c-83db7090a77a" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="brush: c#"&gt;{% extends "shared/master.html" %}

{% block title %}DJango Example{% endblock %}
{% block css_includes %}{% endblock %}
{% block script_includes %}{% endblock %}


{% block content %}
&amp;lt;p&amp;gt;{{ message }}.&amp;lt;/p&amp;gt;
{% endblock %}

{% block footer %}
Footer here
{% endblock %}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
&lt;a href="/content/binary/WindowsLiveWriter/Cre.0projecttemplatewithDjangoandtheGoog_2EC7/image_4.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="image" border="0" alt="image" align="right" src="/blog/content/binary/WindowsLiveWriter/Cre.0projecttemplatewithDjangoandtheGoog_2EC7/image_thumb_1.png" width="304" height="647"&gt;&lt;/a&gt; Apart
from that there is just the default application files required by Python/DJango and
Google App Engine.&amp;nbsp; I am currently looking into:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
Routing&lt;/li&gt;
&lt;li&gt;
Extension less Urls&lt;/li&gt;
&lt;li&gt;
JSON support libraries in Python&lt;/li&gt;
&lt;li&gt;
The Message Queue of the Google App Engine&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
The resulting project structure for the base project is shown on the right.&amp;nbsp;
I opened the website inside Visual Studio to see the structure, not for editing lol.
&lt;/p&gt;
&lt;p&gt;
I should have deleted it but I have not, the http_methods file is not used, I forgot
to delete.
&lt;/p&gt;
&lt;p&gt;
Cheers,
&lt;/p&gt;
&lt;p&gt;
Andrew
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=a579aeb0-c123-4e28-b47e-3d2d04f465de" /&gt;</description>
      <comments>http://www.andrewrea.co.uk/blog/CommentView,guid,a579aeb0-c123-4e28-b47e-3d2d04f465de.aspx</comments>
      <category>Google AppEngine</category>
      <category>Python</category>
    </item>
    <item>
      <trackback:ping>http://www.andrewrea.co.uk/blog/Trackback.aspx?guid=ec167e3d-5c8a-4302-bf19-3809c9cba630</trackback:ping>
      <pingback:server>http://www.andrewrea.co.uk/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.andrewrea.co.uk/blog/PermaLink,guid,ec167e3d-5c8a-4302-bf19-3809c9cba630.aspx</pingback:target>
      <dc:creator>Andrew Rea</dc:creator>
      <wfw:comment>http://www.andrewrea.co.uk/blog/CommentView,guid,ec167e3d-5c8a-4302-bf19-3809c9cba630.aspx</wfw:comment>
      <wfw:commentRss>http://www.andrewrea.co.uk/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=ec167e3d-5c8a-4302-bf19-3809c9cba630</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <h2>Files
</h2>
        <p>
Please download the example solution for this post from the following url.
</p>
        <p>
          <a href="/ResourcesExampleMvc.rar">http://lab.andrewrea.co.uk/ResourcesExampleMvc.rar</a>
        </p>
        <h2>Summary
</h2>
        <p>
Ok, I have been writing this one as I went, whilst thinking and deving so my opinion
on this has changed from when I started writing this to what I ended up with and I
have to say I am quite chuffed with the outcome as it yields some other possibilities
which I want to now blog about, but to cut a long story/blog post short I have made
a Http Handler which accepts some parameters so it can locate a resource file, enumerate
through its properties and output them as JavaScript variables to the Response Output
Stream. This allows me to expose resources the application is using to client script
so I am not duplicating any of them and making maintenance and additions much easier.
</p>
        <p>
I have also wrapped in a bit of token based security, although I do kind of ensure
that what is attempted to be enumerated is a resource file by passing the type into
a ResourceManager I have added the token based security regardless.  Another
good option would be to encrypt the url like the common .axd resource handler does,
but either way I have used a token based approach using HMAC and SHA1. 
</p>
        <p>
Example usage:
</p>
        <div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:d5bcdcbb-550c-4925-b722-bc645eb64c07" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
          <pre name="code" class="brush: c#">&lt;%= Html.ClientResourceLink&lt;ResourcesExampleMvc.Core.Resources.Global&gt;("jsloc.axd","fr") %&gt;</pre>
        </div>
        <p>
Example output:
</p>
        <div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:0cc018eb-857b-4484-aca8-881e4fc76d39" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
          <pre name="code" class="brush: c#">&lt;script type="text/javascript" src="/jsloc.axd?typeName=ResourcesExampleMvc.Core.Resources.Web.Controllers.Home.Home&amp;culture=fr&amp;token=2E935FA9EF23865A9A57B437EC9A7CCE62A7712B&amp;timestamp=1260744495"&gt;&lt;/script&gt; </pre>
        </div>
        <p>
The handler at work:
</p>
        <p>
        </p>
        <div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:bc40d9cb-c9f9-4eb1-82c8-20650dc1653c" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
          <pre name="code" class="brush: c#">var cache_date = "13 December 2009 23:57";
var GlobalString1 = "French Global String 1";</pre>
        </div>
        <p>
          <a href="/content/binary/WindowsLiveWriter/Anidearelatingtoexposingtheresourcefiles_11774/image_6.png">
            <img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="88" alt="image" src="/blog/content/binary/WindowsLiveWriter/Anidearelatingtoexposingtheresourcefiles_11774/image_thumb_2.png" width="600" border="0" />
          </a>
        </p>
        <p>
Finally I have made a HtmlHelper which will generate the relevant link / links I need. 
So the blog that I started writing, dev’d and changed my mind…
</p>
        <h2>here goes…
</h2>
        <p>
I have been looking at different examples on the web relating to client side localisation. 
The two main points I see are:
</p>
        <ol>
          <li>
Add secondary resources inside JavaScript files (This leads to duplication of resources) 
</li>
          <li>
Make a call to the Resource Manager inside delimiters inside the mark-up. (This is
fine as long as you are not using separate JavaScript Files)</li>
        </ol>
        <p>
I might be wrong, but from what I can see on the Resource Manager, there is only a
set way of getting access to a resource, and that is by its name, so if I want to
get several related items, I need to know the keys of each.  As I am writing
this I am now starting to think if what I originally wanted to do is as efficient
as I first thought.
</p>
        <p>
Basically I thought that inside each Resource file that is defined, each key could
be prefixed with some kind of grouping information, e.g. HomeController , so I could
have the following keys:
</p>
        <ul>
          <li>
HomeController_WelcomeText</li>
          <li>
HomeController_Button1</li>
          <li>
HomeController_Button2</li>
        </ul>
        <p>
With this I then thought of making a way to query the resources, so I could apply
a prefix and then get in return all matched keys.  I would do this by reflection
and looping over each property, storing its name and value. 
</p>
        <p>
So to summarise I was stuck in the way of thinking one resource file and differentiating
based on the string key.  DOH!, thinking about it now, I think the best and most
clean solution is to use a separate resource file per each localisable entity i.e.
a Form, or Controller etc…  If you think about it also, this will make things
much more organised when you get to a point where you have thousands of resources. 
Having them logically separated in line with the entity which will be localised makes
good sense.  Not only that it also make the task I was thinking about much easier.
</p>
        <h3>
        </h3>
        <h3>The Idea
</h3>
        <p>
If you think about ASP.NET MVC for example, and the following. You will always have
resources which are common or global and then you will have resources which are specific
to a certain part of the project, e.g. <strong>Home Controller</strong>.
</p>
        <p>
I want to be able to output any localisation that I need so that I can consume with
JavaScript without any unnecessary AJAX calls.  More so I only want to output
the required keys from the global resources and the resources specific to the area
which it is currently being executed, i.e. <strong>Home Controller</strong>. 
</p>
        <p>
The format which I am thinking for the output of the client side localisation is simply
a included JavaScript file with the contents simply declared variables which match
the name of those inside the resource files i.e.
</p>
        <div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:54c7d142-7957-4677-aacf-2a0f0e7a9b47" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
          <pre name="code" class="brush: c#">var Global_Resource_Key_1 = "Hello World";
var Global_Resource_Key_2 = "Hello Galaxy";
var Local_Resource_Key_1 = "Local Number 1";
var Local_Resource_Key_2 = "Local Number 2";</pre>
        </div>
        <p>
Going back to what I said above, these will be output by a method using reflection
to iterate through each of its properties to then generate the required output. 
Once the iteration has complete it would be wise to store the resulting collection
in Cache or Application object.  I am thinking that the generation of the script
will be using a HttpHandler, allowing for the variables to be dynamic inside the mark-up
and script  declaration.
</p>
        <p>
          <strong>Thinking about it more, this is exactly why we are given the special .NET
folders of :</strong>
        </p>
        <ul>
          <li>
            <strong>App_GlobalResources</strong>
          </li>
          <li>
            <strong>App_LocalResources</strong>
          </li>
        </ul>
        <p>
These are great, but, I need to have the resource files inside another assembly so
that they can be referenced both from the web and also internally from the calling
assembly.  So inside a test project I have done the following to setup:
</p>
        <p>
          <a href="/content/binary/WindowsLiveWriter/Anidearelatingtoexposingtheresourcefiles_11774/image_4.png">
            <img title="image" style="border-right: 0px; border-top: 0px; display: inline; margin: 0px 0px 0px 10px; border-left: 0px; border-bottom: 0px" height="504" alt="image" src="/blog/content/binary/WindowsLiveWriter/Anidearelatingtoexposingtheresourcefiles_11774/image_thumb_1.png" width="279" align="right" border="0" />
          </a>
        </p>
        <ul>
          <li>
Create a MVC Application</li>
          <ul>
            <li>
Delete the Account View and Controllers</li>
            <li>
Move the Controllers, Global.asax.cs and Models to the Class Library project</li>
          </ul>
          <li>
Create a separate Class Library Project</li>
          <ul>
            <li>
Create a folder for resources</li>
            <li>
Create a Global Resources and also a Resource file per Controller with the relevant
folder structure</li>
            <li>
Created a Configuration folder and class to handle the secret key for hmac’ing and
cache timeout</li>
            <li>
Created an Extension Method folder and HtmlHelper class which will be a shortcut for
the deveoper to use which will generate the link</li>
            <li>
Created a HttpHandlers folder and the actual handler which I will use to generate
and cache the relevant properties</li>
          </ul>
        </ul>
        <p>
Also, I have omitted any DI/IOC for the purposes of this example. I will go through
each of the Class Library project sections separately.
</p>
        <h3>Create a folder for resources &amp; Create a Global Resources and also a Resource
file per Controller with the relevant folder structure
</h3>
        <p>
Having a separate folder in the resource means I can consume these from the web application
but also from any models which are inside the assembly or business data for example
where I may state the resource for validation attributes like those used in the DataAnnotations
or the MVAB (Microsoft Validation Application Block).
</p>
        <p>
I have but the global resource file directly inside this folder and then created sub
folders to reflect different parts of the application which the one being in this
instance, Web and then even further by controller.  I think grouping the resources
by Controller for the web is a logical step, and along with a global resource file,
you are pretty much covered.
</p>
        <p>
          <a href="/content/binary/WindowsLiveWriter/Anidearelatingtoexposingtheresourcefiles_11774/image_2.png">
            <img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="170" alt="image" src="/blog/content/binary/WindowsLiveWriter/Anidearelatingtoexposingtheresourcefiles_11774/image_thumb.png" width="600" border="0" />
          </a>
        </p>
        <p>
When you build the solution, .NET will logically group your assemblies by culture,
so have many resource files still means they will compile down into one assembly,
which is great.
</p>
        <h3>Created a Configuration folder and class to handle the secret key for hmac’ing
and cache timeout
</h3>
        <p>
I could quite as easily have used the AppSettings but I thought that it would be good
to give this attempt its own configuration section, which I could extend and keep
encapsulated in the future.  The two things which I am using this section for
at the moment is to store the key I will use to generate the HMAC hashes and also
the sliding timeout for the cache of the resources.  The secret key can be anything
you want, but I needed it in a centralised place so i can ensure the same one is used
to generate and also compare.  There is not much to the Configuration Section
accept a couple of required attributes and the syntax for retrieving the value declared
in the config file.
</p>
        <div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:37d73064-790e-4f57-a181-04ca429575b9" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
          <pre name="code" class="brush: c#">&lt;clientResourceConfiguration 
	resourceSlidingTimeout="20" 
	resourceHmacKey="470F0BE4675941baBEFBC1134CC1FEAF28C47C15D71543b8A9F57360CFFCD33B"/&gt;</pre>
        </div>
        <p>
The secret key / resourceHmacKey here is simply two GUIDs stripped of the curlies
and dashes and concatenated together.  To reference this configuration inside
the code, I have placed a static property on the MvcApplication class inside the Global.asax.cs
file.  Seemed like a logical place to put it, and of course made it a singleton.
</p>
        <div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:ce334f1d-71c3-4c9c-b9e0-50746f795434" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
          <pre name="code" class="brush: c#">    public class MvcApplication : System.Web.HttpApplication
    {
        private static ClientResourceConfiguration _clientResourceConfiguration = null;

        public static ClientResourceConfiguration ClientResourceConfiguration
        {
            get
            {
                if (_clientResourceConfiguration == null)
                {
                    _clientResourceConfiguration = (ClientResourceConfiguration)ConfigurationManager.GetSection("clientResourceConfiguration");
                }
                return _clientResourceConfiguration;
            }
        }

...</pre>
        </div>
        <h3>Created an Extension Method folder and HtmlHelper class which will be a shortcut
for the developer to use which will generate the link
</h3>
        <p>
        </p>
        <p>
        </p>
        <p>
        </p>
        <p>
        </p>
        <p>
This is simply to make it easier for the developer to create the link.  You can
simply add the type you want to parse, the name of the handler which is mapped in
the config file and the culture.  In this implementation I have designed it to
expect the two letter culture name and then go on to resolve the specific culture. 
I know it would have been easier to just specify the specific culture but I dev’d
this with a work related problem I had and wanted to simulate the environment in which
I have to work with. 
</p>
        <p>
I have created an overloaded method so that if I need to I can force clear the cache
for a specific handler.  As I will show you further down I also output the date
it was cached, again simply for diagnostic purposes.
</p>
        <p>
The token here is simply so i can be sure that the resource file which is being requested
has been authorized by the server, as it is the server which is the only entity that
has the secret key and can create such links.  I have included a timestamp which
makes the HMAC hash different each time.  The validation of this token will only
occur if the requested resource is not in the cache, as I make the assumption that
is if it is in the cache, then it has to have been generated for a valid reason by
the server.
</p>
        <p>
Oh and there is a small method in there I found on Brad Abrams site which simply gives
me back the number of seconds since 1970, which acts as a timestamp.
</p>
        <div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:42a60117-fe12-4e94-a92c-6e5018c335e4" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
          <pre name="code" class="brush: c#">    public static class HtmlHelpers
    {
        public static string ClientResourceLink&lt;T&gt;(this HtmlHelper helper, string handler, string twoLetterCultureName)
        {
            return ClientResourceLink&lt;T&gt;(helper, handler, twoLetterCultureName, true);
        }

        public static string ClientResourceLink&lt;T&gt;(this HtmlHelper helper, string handler, string twoLetterCultureName, bool cache)
        {
            var typeName = typeof(T).FullName;
            var timeStamp = GetTimeStamp().ToString();
            var valueToHash = String.Concat(typeName, twoLetterCultureName, timeStamp);
            var token = CryptoHelper.Hmac(valueToHash, MvcApplication.ClientResourceConfiguration.ResourceHmacKey, HashType.SHA1);
            var url = String.Format("~/{0}?typeName={1}&amp;culture={2}&amp;token={3}&amp;timestamp={4}",
                handler,
                typeName,
                twoLetterCultureName,
                token,
                timeStamp);
            if (!cache)
            {
                url += "&amp;cache=ncache";
            }
            return String.Format("&lt;script type=\"text/javascript\" src=\"{0}\"&gt;&lt;/script&gt;",
                new UrlHelper(helper.ViewContext.RequestContext).Content(url));
        }

        /// &lt;summary&gt;
        /// From Brad Abrams : http://blogs.msdn.com/brada/archive/2004/03/20/93332.aspx
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        private static int GetTimeStamp()
        {
            TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
            int timestamp = (int)t.TotalSeconds;
            return timestamp;
        }
    }</pre>
        </div>
        <p>
The CryptoHelper class is one which “I made earlier,” and which I blogged about here <a href="/2009/10/05/ACryptographyHelperClassForHashingAndForKHMACKeyedHashMessageAuthenticationCode.aspx">http://www.andrewrea.co.uk/2009/10/05/ACryptographyHelperClassForHashingAndForKHMACKeyedHashMessageAuthenticationCode.aspx</a>. 
It is simply a helper method wrapping around some types and methods inside the System.Security.Cryptography
namespace.  You will see some example usages in the summary above.
</p>
        <h3>Created a HttpHandlers folder and the actual handler which I will use to generate
and cache the relevant properties
</h3>
        <p>
This is basically the crooks of the solution and it is the handler.  I have used
the .axd extension simply because it is already recognised and is ignored my the MVC
route handler.  
</p>
        <p>
Below is the entry I have used to configure the Http Handler for GET only and an example
path to map it to
</p>
        <div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:24129782-9818-433c-a333-b8624032ea22" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
          <pre name="code" class="brush: c#">&lt;add verb="GET" path="/jsloc.axd" validate="false" type="ResourcesExampleMvc.Core.HttpHandlers.ClientSideResourceHttpHandler,ResourcesExampleMvc.Core" /&gt;</pre>
        </div>
        <p>
It is in this class where I handle:
</p>
        <ul>
          <li>
The parameters passed in</li>
          <li>
The validation of the token</li>
          <li>
The cache of the resources for the client</li>
          <li>
The generation of the resources</li>
        </ul>
        <p>
I simply set the Response.ContentType to text/javascript and then write out the information
through a StreamWriter.  The first variable I add is the CacheDate and then followed
by the resources themselves, as they appear inside the resource file.  A point
to mention here is if you have defined any of the keys in the resource files with
spaces in they will be replaced with underscores.
</p>
        <p>
          <strong>Major Point : You must set the scope of your Resource File, which ever one
you want the Handler to parse as Public, this is due to me put Binding Flags on the
reflection as Public and Static.  I suppose I could have added Internal, but
not sure, so I will leave for now as Public.</strong>
        </p>
        <p>
        </p>
        <div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:b321a968-b4d5-4726-bccc-85e615c9c3b5" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
          <pre name="code" class="brush: c#">    public class ClientSideResourceHttpHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string typeName = context.Request.QueryString["typeName"];
            string twoLetterCultureName = context.Request.QueryString["culture"];
            string token = context.Request.QueryString["token"];
            string timestamp = context.Request.QueryString["timestamp"];
            string nocache = context.Request.QueryString["nocache"];
            var timeout = MvcApplication.ClientResourceConfiguration.ResourceSlidingTimeout;

            string key = GetKey(typeName, twoLetterCultureName);

            if (context.Cache[key] == null || !String.IsNullOrEmpty(nocache))
            {
                var type = Type.GetType(typeName);
                var resourceManager = new ResourceManager(type);

                if (!ValidateToken(typeName, twoLetterCultureName, timestamp, token))
                    throw new SecurityException("Invalid token submitted for client resource");

                var list = new List&lt;KeyValuePair&lt;string, string&gt;&gt;();
                var properties = type.GetProperties(
                    System.Reflection.BindingFlags.Public |
                    System.Reflection.BindingFlags.Static);

                foreach (var property in properties)
                {
                    if (property.PropertyType == typeof(string))
                    {

                        list.Add(
                            new KeyValuePair&lt;string, string&gt;(property.Name,
                                resourceManager.GetString(property.Name.Replace("_", " "),
                                GetCulture(twoLetterCultureName))
                                )
                        );
                    }
                }

                context.Cache.Insert(key, list, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(timeout));
            }

            context.Response.ContentType = "text/javascript";
            WriteOutClientResources(context.Response.OutputStream, (List&lt;KeyValuePair&lt;string, string&gt;&gt;)context.Cache[key]);
            context.Response.End();
        }

        #endregion

        private void WriteOutClientResources(Stream outputStream, List&lt;KeyValuePair&lt;string, string&gt;&gt; values)
        {
            using (var sw = new StreamWriter(outputStream))
            {
                sw.WriteLine(String.Format("var cache_date = \"{0}\";", DateTime.Now.ToString("f")));
                foreach (var item in values)
                {
                    sw.WriteLine(String.Format("var {0} = \"{1}\";", item.Key, item.Value));
                }
                sw.Flush();
            }
        }

        private bool ValidateToken(string typeName, string twoLetterCultureName, string timestamp, string token)
        {
            var valueToHmac = String.Concat(typeName, twoLetterCultureName, timestamp);
            var valueToCompare = CryptoHelper.Hmac(valueToHmac, MvcApplication.ClientResourceConfiguration.ResourceHmacKey, HashType.SHA1);
            return valueToCompare.Equals(token);
        }

        private string GetKey(string controllerName, string twoLetterCultureName)
        {
            return String.Format("{0}!{1}", controllerName, twoLetterCultureName);
        }

        private CultureInfo GetCulture(string twoLetterCultureName)
        {
            switch (twoLetterCultureName)
            {
                case "fr":
                    return CultureInfo.CreateSpecificCulture("fr-FR");
                default:
                    return CultureInfo.CreateSpecificCulture("en-GB");
            }
        }
    }</pre>
        </div>
        <p>
If you did not want the overhead of a Handler, or you do not want the actual dynamic
script reference, then there is nothing stopping you in cutting this write down, and
making a HtmlHelper which simply parsing a type and outputs the JavaScript variables
directly to the requesting resource, so instead of an include script tag, it would
output a script block directly in the dom.  Personally I just like the script
tag and the visual reduction in code in the view source, I am unsure of any performance
gain if any.  
</p>
        <p>
So that is basically it, this is something I am definitely going to test drive and
among other things, use it for other purposes.  One idea I had was to use this
to generate Client Side objects based on say the models. I will do this for the next
post I hope.
</p>
        <img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=ec167e3d-5c8a-4302-bf19-3809c9cba630" />
      </body>
      <title>An idea relating to, exposing the resource files of different assemblies for consumption by the client side</title>
      <guid isPermaLink="false">http://www.andrewrea.co.uk/blog/PermaLink,guid,ec167e3d-5c8a-4302-bf19-3809c9cba630.aspx</guid>
      <link>http://www.andrewrea.co.uk/blog/2009/12/13/AnIdeaRelatingToExposingTheResourceFilesOfDifferentAssembliesForConsumptionByTheClientSide.aspx</link>
      <pubDate>Sun, 13 Dec 2009 23:53:19 GMT</pubDate>
      <description>&lt;h2&gt;Files
&lt;/h2&gt;
&lt;p&gt;
Please download the example solution for this post from the following url.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="/ResourcesExampleMvc.rar"&gt;http://lab.andrewrea.co.uk/ResourcesExampleMvc.rar&lt;/a&gt;
&lt;/p&gt;
&lt;h2&gt;Summary
&lt;/h2&gt;
&lt;p&gt;
Ok, I have been writing this one as I went, whilst thinking and deving so my opinion
on this has changed from when I started writing this to what I ended up with and I
have to say I am quite chuffed with the outcome as it yields some other possibilities
which I want to now blog about, but to cut a long story/blog post short I have made
a Http Handler which accepts some parameters so it can locate a resource file, enumerate
through its properties and output them as JavaScript variables to the Response Output
Stream. This allows me to expose resources the application is using to client script
so I am not duplicating any of them and making maintenance and additions much easier.
&lt;/p&gt;
&lt;p&gt;
I have also wrapped in a bit of token based security, although I do kind of ensure
that what is attempted to be enumerated is a resource file by passing the type into
a ResourceManager I have added the token based security regardless.&amp;nbsp; Another
good option would be to encrypt the url like the common .axd resource handler does,
but either way I have used a token based approach using HMAC and SHA1. 
&lt;/p&gt;
&lt;p&gt;
Example usage:
&lt;/p&gt;
&lt;div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:d5bcdcbb-550c-4925-b722-bc645eb64c07" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="brush: c#"&gt;&amp;lt;%= Html.ClientResourceLink&amp;lt;ResourcesExampleMvc.Core.Resources.Global&amp;gt;("jsloc.axd","fr") %&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Example output:
&lt;/p&gt;
&lt;div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:0cc018eb-857b-4484-aca8-881e4fc76d39" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="brush: c#"&gt;&amp;lt;script type="text/javascript" src="/jsloc.axd?typeName=ResourcesExampleMvc.Core.Resources.Web.Controllers.Home.Home&amp;amp;culture=fr&amp;amp;token=2E935FA9EF23865A9A57B437EC9A7CCE62A7712B&amp;amp;timestamp=1260744495"&amp;gt;&amp;lt;/script&amp;gt; &lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The handler at work:
&lt;/p&gt;
&lt;p&gt;
&lt;div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:bc40d9cb-c9f9-4eb1-82c8-20650dc1653c" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="brush: c#"&gt;var cache_date = "13 December 2009 23:57";
var GlobalString1 = "French Global String 1";&lt;/pre&gt;
&lt;/div&gt;
&gt;
&lt;p&gt;
&lt;a href="/content/binary/WindowsLiveWriter/Anidearelatingtoexposingtheresourcefiles_11774/image_6.png"&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="88" alt="image" src="/blog/content/binary/WindowsLiveWriter/Anidearelatingtoexposingtheresourcefiles_11774/image_thumb_2.png" width="600" border="0"&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
Finally I have made a HtmlHelper which will generate the relevant link / links I need.&amp;nbsp;
So the blog that I started writing, dev’d and changed my mind…
&lt;/p&gt;
&lt;h2&gt;here goes…
&lt;/h2&gt;
&lt;p&gt;
I have been looking at different examples on the web relating to client side localisation.&amp;nbsp;
The two main points I see are:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
Add secondary resources inside JavaScript files (This leads to duplication of resources) 
&lt;li&gt;
Make a call to the Resource Manager inside delimiters inside the mark-up. (This is
fine as long as you are not using separate JavaScript Files)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
I might be wrong, but from what I can see on the Resource Manager, there is only a
set way of getting access to a resource, and that is by its name, so if I want to
get several related items, I need to know the keys of each.&amp;nbsp; As I am writing
this I am now starting to think if what I originally wanted to do is as efficient
as I first thought.
&lt;/p&gt;
&lt;p&gt;
Basically I thought that inside each Resource file that is defined, each key could
be prefixed with some kind of grouping information, e.g. HomeController , so I could
have the following keys:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
HomeController_WelcomeText&lt;/li&gt;
&lt;li&gt;
HomeController_Button1&lt;/li&gt;
&lt;li&gt;
HomeController_Button2&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
With this I then thought of making a way to query the resources, so I could apply
a prefix and then get in return all matched keys.&amp;nbsp; I would do this by reflection
and looping over each property, storing its name and value. 
&lt;/p&gt;
&lt;p&gt;
So to summarise I was stuck in the way of thinking one resource file and differentiating
based on the string key.&amp;nbsp; DOH!, thinking about it now, I think the best and most
clean solution is to use a separate resource file per each localisable entity i.e.
a Form, or Controller etc…&amp;nbsp; If you think about it also, this will make things
much more organised when you get to a point where you have thousands of resources.&amp;nbsp;
Having them logically separated in line with the entity which will be localised makes
good sense.&amp;nbsp; Not only that it also make the task I was thinking about much easier.
&lt;/p&gt;
&lt;h3&gt;
&lt;/h3&gt;
&lt;h3&gt;The Idea
&lt;/h3&gt;
&lt;p&gt;
If you think about ASP.NET MVC for example, and the following. You will always have
resources which are common or global and then you will have resources which are specific
to a certain part of the project, e.g. &lt;strong&gt;Home Controller&lt;/strong&gt;.
&lt;/p&gt;
&lt;p&gt;
I want to be able to output any localisation that I need so that I can consume with
JavaScript without any unnecessary AJAX calls.&amp;nbsp; More so I only want to output
the required keys from the global resources and the resources specific to the area
which it is currently being executed, i.e. &lt;strong&gt;Home Controller&lt;/strong&gt;. 
&lt;/p&gt;
&lt;p&gt;
The format which I am thinking for the output of the client side localisation is simply
a included JavaScript file with the contents simply declared variables which match
the name of those inside the resource files i.e.
&lt;/p&gt;
&lt;div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:54c7d142-7957-4677-aacf-2a0f0e7a9b47" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="brush: c#"&gt;var Global_Resource_Key_1 = "Hello World";
var Global_Resource_Key_2 = "Hello Galaxy";
var Local_Resource_Key_1 = "Local Number 1";
var Local_Resource_Key_2 = "Local Number 2";&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Going back to what I said above, these will be output by a method using reflection
to iterate through each of its properties to then generate the required output.&amp;nbsp;
Once the iteration has complete it would be wise to store the resulting collection
in Cache or Application object.&amp;nbsp; I am thinking that the generation of the script
will be using a HttpHandler, allowing for the variables to be dynamic inside the mark-up
and script&amp;nbsp; declaration.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Thinking about it more, this is exactly why we are given the special .NET
folders of :&lt;/strong&gt;
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;App_GlobalResources&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;App_LocalResources&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
These are great, but, I need to have the resource files inside another assembly so
that they can be referenced both from the web and also internally from the calling
assembly.&amp;nbsp; So inside a test project I have done the following to setup:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="/content/binary/WindowsLiveWriter/Anidearelatingtoexposingtheresourcefiles_11774/image_4.png"&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; margin: 0px 0px 0px 10px; border-left: 0px; border-bottom: 0px" height="504" alt="image" src="/blog/content/binary/WindowsLiveWriter/Anidearelatingtoexposingtheresourcefiles_11774/image_thumb_1.png" width="279" align="right" border="0"&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
Create a MVC Application&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;
Delete the Account View and Controllers&lt;/li&gt;
&lt;li&gt;
Move the Controllers, Global.asax.cs and Models to the Class Library project&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;
Create a separate Class Library Project&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;
Create a folder for resources&lt;/li&gt;
&lt;li&gt;
Create a Global Resources and also a Resource file per Controller with the relevant
folder structure&lt;/li&gt;
&lt;li&gt;
Created a Configuration folder and class to handle the secret key for hmac’ing and
cache timeout&lt;/li&gt;
&lt;li&gt;
Created an Extension Method folder and HtmlHelper class which will be a shortcut for
the deveoper to use which will generate the link&lt;/li&gt;
&lt;li&gt;
Created a HttpHandlers folder and the actual handler which I will use to generate
and cache the relevant properties&lt;/li&gt;
&lt;/ul&gt;
&lt;/ul&gt;
&lt;p&gt;
Also, I have omitted any DI/IOC for the purposes of this example. I will go through
each of the Class Library project sections separately.
&lt;/p&gt;
&lt;h3&gt;Create a folder for resources &amp;amp; Create a Global Resources and also a Resource
file per Controller with the relevant folder structure
&lt;/h3&gt;
&lt;p&gt;
Having a separate folder in the resource means I can consume these from the web application
but also from any models which are inside the assembly or business data for example
where I may state the resource for validation attributes like those used in the DataAnnotations
or the MVAB (Microsoft Validation Application Block).
&lt;/p&gt;
&lt;p&gt;
I have but the global resource file directly inside this folder and then created sub
folders to reflect different parts of the application which the one being in this
instance, Web and then even further by controller.&amp;nbsp; I think grouping the resources
by Controller for the web is a logical step, and along with a global resource file,
you are pretty much covered.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="/content/binary/WindowsLiveWriter/Anidearelatingtoexposingtheresourcefiles_11774/image_2.png"&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="170" alt="image" src="/blog/content/binary/WindowsLiveWriter/Anidearelatingtoexposingtheresourcefiles_11774/image_thumb.png" width="600" border="0"&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
When you build the solution, .NET will logically group your assemblies by culture,
so have many resource files still means they will compile down into one assembly,
which is great.
&lt;/p&gt;
&lt;h3&gt;Created a Configuration folder and class to handle the secret key for hmac’ing
and cache timeout
&lt;/h3&gt;
&lt;p&gt;
I could quite as easily have used the AppSettings but I thought that it would be good
to give this attempt its own configuration section, which I could extend and keep
encapsulated in the future.&amp;nbsp; The two things which I am using this section for
at the moment is to store the key I will use to generate the HMAC hashes and also
the sliding timeout for the cache of the resources.&amp;nbsp; The secret key can be anything
you want, but I needed it in a centralised place so i can ensure the same one is used
to generate and also compare.&amp;nbsp; There is not much to the Configuration Section
accept a couple of required attributes and the syntax for retrieving the value declared
in the config file.
&lt;/p&gt;
&lt;div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:37d73064-790e-4f57-a181-04ca429575b9" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="brush: c#"&gt;&amp;lt;clientResourceConfiguration 
	resourceSlidingTimeout="20" 
	resourceHmacKey="470F0BE4675941baBEFBC1134CC1FEAF28C47C15D71543b8A9F57360CFFCD33B"/&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The secret key / resourceHmacKey here is simply two GUIDs stripped of the curlies
and dashes and concatenated together.&amp;nbsp; To reference this configuration inside
the code, I have placed a static property on the MvcApplication class inside the Global.asax.cs
file.&amp;nbsp; Seemed like a logical place to put it, and of course made it a singleton.
&lt;/p&gt;
&lt;div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:ce334f1d-71c3-4c9c-b9e0-50746f795434" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="brush: c#"&gt;    public class MvcApplication : System.Web.HttpApplication
    {
        private static ClientResourceConfiguration _clientResourceConfiguration = null;

        public static ClientResourceConfiguration ClientResourceConfiguration
        {
            get
            {
                if (_clientResourceConfiguration == null)
                {
                    _clientResourceConfiguration = (ClientResourceConfiguration)ConfigurationManager.GetSection("clientResourceConfiguration");
                }
                return _clientResourceConfiguration;
            }
        }

...&lt;/pre&gt;
&lt;/div&gt;
&lt;h3&gt;Created an Extension Method folder and HtmlHelper class which will be a shortcut
for the developer to use which will generate the link
&lt;/h3&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
This is simply to make it easier for the developer to create the link.&amp;nbsp; You can
simply add the type you want to parse, the name of the handler which is mapped in
the config file and the culture.&amp;nbsp; In this implementation I have designed it to
expect the two letter culture name and then go on to resolve the specific culture.&amp;nbsp;
I know it would have been easier to just specify the specific culture but I dev’d
this with a work related problem I had and wanted to simulate the environment in which
I have to work with. 
&lt;/p&gt;
&lt;p&gt;
I have created an overloaded method so that if I need to I can force clear the cache
for a specific handler.&amp;nbsp; As I will show you further down I also output the date
it was cached, again simply for diagnostic purposes.
&lt;/p&gt;
&lt;p&gt;
The token here is simply so i can be sure that the resource file which is being requested
has been authorized by the server, as it is the server which is the only entity that
has the secret key and can create such links.&amp;nbsp; I have included a timestamp which
makes the HMAC hash different each time.&amp;nbsp; The validation of this token will only
occur if the requested resource is not in the cache, as I make the assumption that
is if it is in the cache, then it has to have been generated for a valid reason by
the server.
&lt;/p&gt;
&lt;p&gt;
Oh and there is a small method in there I found on Brad Abrams site which simply gives
me back the number of seconds since 1970, which acts as a timestamp.
&lt;/p&gt;
&lt;div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:42a60117-fe12-4e94-a92c-6e5018c335e4" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="brush: c#"&gt;    public static class HtmlHelpers
    {
        public static string ClientResourceLink&amp;lt;T&amp;gt;(this HtmlHelper helper, string handler, string twoLetterCultureName)
        {
            return ClientResourceLink&amp;lt;T&amp;gt;(helper, handler, twoLetterCultureName, true);
        }

        public static string ClientResourceLink&amp;lt;T&amp;gt;(this HtmlHelper helper, string handler, string twoLetterCultureName, bool cache)
        {
            var typeName = typeof(T).FullName;
            var timeStamp = GetTimeStamp().ToString();
            var valueToHash = String.Concat(typeName, twoLetterCultureName, timeStamp);
            var token = CryptoHelper.Hmac(valueToHash, MvcApplication.ClientResourceConfiguration.ResourceHmacKey, HashType.SHA1);
            var url = String.Format("~/{0}?typeName={1}&amp;amp;culture={2}&amp;amp;token={3}&amp;amp;timestamp={4}",
                handler,
                typeName,
                twoLetterCultureName,
                token,
                timeStamp);
            if (!cache)
            {
                url += "&amp;amp;cache=ncache";
            }
            return String.Format("&amp;lt;script type=\"text/javascript\" src=\"{0}\"&amp;gt;&amp;lt;/script&amp;gt;",
                new UrlHelper(helper.ViewContext.RequestContext).Content(url));
        }

        /// &amp;lt;summary&amp;gt;
        /// From Brad Abrams : http://blogs.msdn.com/brada/archive/2004/03/20/93332.aspx
        /// &amp;lt;/summary&amp;gt;
        /// &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;
        private static int GetTimeStamp()
        {
            TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
            int timestamp = (int)t.TotalSeconds;
            return timestamp;
        }
    }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The CryptoHelper class is one which “I made earlier,” and which I blogged about here &lt;a href="/2009/10/05/ACryptographyHelperClassForHashingAndForKHMACKeyedHashMessageAuthenticationCode.aspx"&gt;http://www.andrewrea.co.uk/2009/10/05/ACryptographyHelperClassForHashingAndForKHMACKeyedHashMessageAuthenticationCode.aspx&lt;/a&gt;.&amp;nbsp;
It is simply a helper method wrapping around some types and methods inside the System.Security.Cryptography
namespace.&amp;nbsp; You will see some example usages in the summary above.
&lt;/p&gt;
&lt;h3&gt;Created a HttpHandlers folder and the actual handler which I will use to generate
and cache the relevant properties
&lt;/h3&gt;
&lt;p&gt;
This is basically the crooks of the solution and it is the handler.&amp;nbsp; I have used
the .axd extension simply because it is already recognised and is ignored my the MVC
route handler.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
Below is the entry I have used to configure the Http Handler for GET only and an example
path to map it to
&lt;/p&gt;
&lt;div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:24129782-9818-433c-a333-b8624032ea22" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="brush: c#"&gt;&amp;lt;add verb="GET" path="/jsloc.axd" validate="false" type="ResourcesExampleMvc.Core.HttpHandlers.ClientSideResourceHttpHandler,ResourcesExampleMvc.Core" /&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
It is in this class where I handle:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
The parameters passed in&lt;/li&gt;
&lt;li&gt;
The validation of the token&lt;/li&gt;
&lt;li&gt;
The cache of the resources for the client&lt;/li&gt;
&lt;li&gt;
The generation of the resources&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
I simply set the Response.ContentType to text/javascript and then write out the information
through a StreamWriter.&amp;nbsp; The first variable I add is the CacheDate and then followed
by the resources themselves, as they appear inside the resource file.&amp;nbsp; A point
to mention here is if you have defined any of the keys in the resource files with
spaces in they will be replaced with underscores.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Major Point : You must set the scope of your Resource File, which ever one
you want the Handler to parse as Public, this is due to me put Binding Flags on the
reflection as Public and Static.&amp;nbsp; I suppose I could have added Internal, but
not sure, so I will leave for now as Public.&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:b321a968-b4d5-4726-bccc-85e615c9c3b5" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="brush: c#"&gt;    public class ClientSideResourceHttpHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string typeName = context.Request.QueryString["typeName"];
            string twoLetterCultureName = context.Request.QueryString["culture"];
            string token = context.Request.QueryString["token"];
            string timestamp = context.Request.QueryString["timestamp"];
            string nocache = context.Request.QueryString["nocache"];
            var timeout = MvcApplication.ClientResourceConfiguration.ResourceSlidingTimeout;

            string key = GetKey(typeName, twoLetterCultureName);

            if (context.Cache[key] == null || !String.IsNullOrEmpty(nocache))
            {
                var type = Type.GetType(typeName);
                var resourceManager = new ResourceManager(type);

                if (!ValidateToken(typeName, twoLetterCultureName, timestamp, token))
                    throw new SecurityException("Invalid token submitted for client resource");

                var list = new List&amp;lt;KeyValuePair&amp;lt;string, string&amp;gt;&amp;gt;();
                var properties = type.GetProperties(
                    System.Reflection.BindingFlags.Public |
                    System.Reflection.BindingFlags.Static);

                foreach (var property in properties)
                {
                    if (property.PropertyType == typeof(string))
                    {

                        list.Add(
                            new KeyValuePair&amp;lt;string, string&amp;gt;(property.Name,
                                resourceManager.GetString(property.Name.Replace("_", " "),
                                GetCulture(twoLetterCultureName))
                                )
                        );
                    }
                }

                context.Cache.Insert(key, list, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(timeout));
            }

            context.Response.ContentType = "text/javascript";
            WriteOutClientResources(context.Response.OutputStream, (List&amp;lt;KeyValuePair&amp;lt;string, string&amp;gt;&amp;gt;)context.Cache[key]);
            context.Response.End();
        }

        #endregion

        private void WriteOutClientResources(Stream outputStream, List&amp;lt;KeyValuePair&amp;lt;string, string&amp;gt;&amp;gt; values)
        {
            using (var sw = new StreamWriter(outputStream))
            {
                sw.WriteLine(String.Format("var cache_date = \"{0}\";", DateTime.Now.ToString("f")));
                foreach (var item in values)
                {
                    sw.WriteLine(String.Format("var {0} = \"{1}\";", item.Key, item.Value));
                }
                sw.Flush();
            }
        }

        private bool ValidateToken(string typeName, string twoLetterCultureName, string timestamp, string token)
        {
            var valueToHmac = String.Concat(typeName, twoLetterCultureName, timestamp);
            var valueToCompare = CryptoHelper.Hmac(valueToHmac, MvcApplication.ClientResourceConfiguration.ResourceHmacKey, HashType.SHA1);
            return valueToCompare.Equals(token);
        }

        private string GetKey(string controllerName, string twoLetterCultureName)
        {
            return String.Format("{0}!{1}", controllerName, twoLetterCultureName);
        }

        private CultureInfo GetCulture(string twoLetterCultureName)
        {
            switch (twoLetterCultureName)
            {
                case "fr":
                    return CultureInfo.CreateSpecificCulture("fr-FR");
                default:
                    return CultureInfo.CreateSpecificCulture("en-GB");
            }
        }
    }&lt;/pre&gt;
&lt;/div&gt;
&gt;
&lt;p&gt;
If you did not want the overhead of a Handler, or you do not want the actual dynamic
script reference, then there is nothing stopping you in cutting this write down, and
making a HtmlHelper which simply parsing a type and outputs the JavaScript variables
directly to the requesting resource, so instead of an include script tag, it would
output a script block directly in the dom.&amp;nbsp; Personally I just like the script
tag and the visual reduction in code in the view source, I am unsure of any performance
gain if any.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
So that is basically it, this is something I am definitely going to test drive and
among other things, use it for other purposes.&amp;nbsp; One idea I had was to use this
to generate Client Side objects based on say the models. I will do this for the next
post I hope.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=ec167e3d-5c8a-4302-bf19-3809c9cba630" /&gt;</description>
      <comments>http://www.andrewrea.co.uk/blog/CommentView,guid,ec167e3d-5c8a-4302-bf19-3809c9cba630.aspx</comments>
      <category>.NET</category>
      <category>C#</category>
      <category>JavaScript</category>
    </item>
    <item>
      <trackback:ping>http://www.andrewrea.co.uk/blog/Trackback.aspx?guid=b4d9ff93-d457-4b36-a0d3-2b9db26990e7</trackback:ping>
      <pingback:server>http://www.andrewrea.co.uk/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.andrewrea.co.uk/blog/PermaLink,guid,b4d9ff93-d457-4b36-a0d3-2b9db26990e7.aspx</pingback:target>
      <dc:creator>Andrew Rea</dc:creator>
      <wfw:comment>http://www.andrewrea.co.uk/blog/CommentView,guid,b4d9ff93-d457-4b36-a0d3-2b9db26990e7.aspx</wfw:comment>
      <wfw:commentRss>http://www.andrewrea.co.uk/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=b4d9ff93-d457-4b36-a0d3-2b9db26990e7</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I had a requirement on a small home project I am working on, where I need to add some
more information to a content result than was there.  More specifically I had
to add the status code and also have access to the response header collection. 
I did come across an interesting thing with this, where by accessing and adding to
the response header collection in a certain way will actually raise an exception and
inform you that this is only support when IIS Integrated Pipeline is enabled. 
I did some looking about and found a post by Phil Haack showing how he had achieved
what I was looking for when he made the Download result class.  
</p>
        <p>
So the following causes an exception:
</p>
        <p>
        </p>
        <div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:f2f2c7bb-c66c-41e3-98ac-6ceb4ed8461b" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
          <pre name="code" class="brush: c#">public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.StatusCode = (int)StatusCode;
            foreach (string s in Headers.Keys)
            {
                context.HttpContext.Response.Headers.Add(s,Headers[s]);
            }
            base.ExecuteResult(context);
        }</pre>
        </div>
        <p>
And the following works fine, notice the subtle difference in how the header is added
now:
</p>
        <div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:fed58937-b6e1-4d1c-a62e-56f9ff8efbcf" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
          <pre name="code" class="brush: c#">        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.StatusCode = (int)StatusCode;
            foreach (string s in Headers.Keys)
            {
                context.HttpContext.Response.AddHeader(s,Headers[s]);
            }
            base.ExecuteResult(context);
        }</pre>
        </div>
        <p>
So the full code implementation of the result is below.  
</p>
        <div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:dc0a4cc8-72ed-47a2-b9c1-2567a74f262c" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
          <pre name="code" class="brush: c#"> public class ExtendedContentResult : ContentResult
    {
        public NameValueCollection Headers { get; set; }
        public HttpStatusCode StatusCode { get; set; }

        public ExtendedContentResult()
        {
            Headers = new NameValueCollection();
        }

        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.StatusCode = (int)StatusCode;
            foreach (string s in Headers.Keys)
            {
                context.HttpContext.Response.AddHeader(s,Headers[s]);
            }
            base.ExecuteResult(context);
        }
    }</pre>
        </div>
        <img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=b4d9ff93-d457-4b36-a0d3-2b9db26990e7" />
      </body>
      <title>Creating an Extended Content Result for ASP.NET MVC</title>
      <guid isPermaLink="false">http://www.andrewrea.co.uk/blog/PermaLink,guid,b4d9ff93-d457-4b36-a0d3-2b9db26990e7.aspx</guid>
      <link>http://www.andrewrea.co.uk/blog/2009/12/01/CreatingAnExtendedContentResultForASPNETMVC.aspx</link>
      <pubDate>Tue, 01 Dec 2009 00:13:31 GMT</pubDate>
      <description>&lt;p&gt;
I had a requirement on a small home project I am working on, where I need to add some
more information to a content result than was there.&amp;nbsp; More specifically I had
to add the status code and also have access to the response header collection.&amp;nbsp;
I did come across an interesting thing with this, where by accessing and adding to
the response header collection in a certain way will actually raise an exception and
inform you that this is only support when IIS Integrated Pipeline is enabled.&amp;nbsp;
I did some looking about and found a post by Phil Haack showing how he had achieved
what I was looking for when he made the Download result class.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
So the following causes an exception:
&lt;/p&gt;
&lt;p&gt;
&lt;div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:f2f2c7bb-c66c-41e3-98ac-6ceb4ed8461b" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="brush: c#"&gt;public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.StatusCode = (int)StatusCode;
            foreach (string s in Headers.Keys)
            {
                context.HttpContext.Response.Headers.Add(s,Headers[s]);
            }
            base.ExecuteResult(context);
        }&lt;/pre&gt;
&lt;/div&gt;
&gt;
&lt;p&gt;
And the following works fine, notice the subtle difference in how the header is added
now:
&lt;/p&gt;
&lt;div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:fed58937-b6e1-4d1c-a62e-56f9ff8efbcf" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="brush: c#"&gt;        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.StatusCode = (int)StatusCode;
            foreach (string s in Headers.Keys)
            {
                context.HttpContext.Response.AddHeader(s,Headers[s]);
            }
            base.ExecuteResult(context);
        }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
So the full code implementation of the result is below.&amp;nbsp; 
&lt;/p&gt;
&lt;div class="wlWriterEditableSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:dc0a4cc8-72ed-47a2-b9c1-2567a74f262c" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="brush: c#"&gt; public class ExtendedContentResult : ContentResult
    {
        public NameValueCollection Headers { get; set; }
        public HttpStatusCode StatusCode { get; set; }

        public ExtendedContentResult()
        {
            Headers = new NameValueCollection();
        }

        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.StatusCode = (int)StatusCode;
            foreach (string s in Headers.Keys)
            {
                context.HttpContext.Response.AddHeader(s,Headers[s]);
            }
            base.ExecuteResult(context);
        }
    }&lt;/pre&gt;
&lt;/div&gt;
&lt;img width="0" height="0" src="http://www.andrewrea.co.uk/blog/aggbug.ashx?id=b4d9ff93-d457-4b36-a0d3-2b9db26990e7" /&gt;</description>
      <comments>http://www.andrewrea.co.uk/blog/CommentView,guid,b4d9ff93-d457-4b36-a0d3-2b9db26990e7.aspx</comments>
      <category>ASP.NET MVC</category>
    </item>
  </channel>
</rss>