<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>AmazedSaint : Spiritual Programming</title>
	<atom:link href="http://amazedsaint.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://amazedsaint.wordpress.com</link>
	<description>Anoop's Blog - From Spirituality To Super Conciousness</description>
	<lastBuildDate>Wed, 07 Jul 2010 06:47:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='amazedsaint.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>AmazedSaint : Spiritual Programming</title>
		<link>http://amazedsaint.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://amazedsaint.wordpress.com/osd.xml" title="AmazedSaint : Spiritual Programming" />
	<atom:link rel='hub' href='http://amazedsaint.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Hobby Programming – Creating your first robotic simulation using Microsoft Robotic Dev Studio and Visual Programming Language</title>
		<link>http://amazedsaint.wordpress.com/2010/07/05/hobby-programming-%e2%80%93-creating-your-first-robotic-simulation-using-microsoft-robotic-dev-studio-and-visual-programming-language/</link>
		<comments>http://amazedsaint.wordpress.com/2010/07/05/hobby-programming-%e2%80%93-creating-your-first-robotic-simulation-using-microsoft-robotic-dev-studio-and-visual-programming-language/#comments</comments>
		<pubDate>Mon, 05 Jul 2010 13:43:00 +0000</pubDate>
		<dc:creator>amazedsaint</dc:creator>
				<category><![CDATA[.NET 4.0]]></category>
		<category><![CDATA[DSL]]></category>
		<category><![CDATA[Programming-Tips]]></category>
		<category><![CDATA[Robotics]]></category>

		<guid isPermaLink="false">http://amazedsaint.wordpress.com/2010/07/05/hobby-programming-%e2%80%93-creating-your-first-robotic-simulation-using-microsoft-robotic-dev-studio-and-visual-programming-language</guid>
		<description><![CDATA[Preface This is a quick introduction towards starting your life with Microsoft Robotic Developer Studio (RDS) and Microsoft Visual Programming Language (MVPL) for creating simple robotic simulations. This is intended to be an ‘absolute beginner’s guide’ to RDS.&#160; In fact, I just started playing with RDS after some inspiration from Ramaprasanna during Kerala DevCon 2010 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=273&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2><a href="http://lh4.ggpht.com/__Mw4iY-4nuY/TDHXet-kqaI/AAAAAAAAA3k/2YMmIG-JtAA/image10.png?imgmax=800"><img title="image" border="0" alt="image" align="right" src="http://lh3.ggpht.com/__Mw4iY-4nuY/TDHXvEMh3pI/AAAAAAAAA3o/_A_-ZwXTB9g/image_thumb8.png?imgmax=800" width="240" height="158" /></a></h2>
<h3>Preface</h3>
<p>This is a quick introduction towards starting your life with Microsoft Robotic Developer Studio (RDS) and Microsoft Visual Programming Language (MVPL) for creating simple robotic simulations. This is intended to be an ‘absolute beginner’s guide’ to RDS.&#160; </p>
<p>In fact, I just started playing with RDS after some inspiration from <a href="http://twitter.com/ramaprasanna">Ramaprasanna</a> during Kerala DevCon 2010 &#8211; and it is fun. And the objective of this post is to share the fun, mainly from a hobby programming perspective. </p>
<p>As a pre-requisite, for doing the hands own instructions below &#8211; you may need to download and install&#160; <a href="http://www.microsoft.com/robotics/">Microsoft Robotic Developer Studio 2008 R3</a> – The installation should be pretty simple and easy.</p>
<p>Microsoft Robotic Developer Studio (RDS) comes with</p>
<ul>
<li>Microsoft Visual Programming Language – An easy to use visual language so that even non programmers can create simulations </li>
<li>A 3D Environment simulation module </li>
</ul>
<p>The RDS comes with two runtimes</p>
<ul>
<li>The Concurrency and Coordination runtime (CCR) – To make easy the handling of asynchronous input/output scenarios when you deal with sensors, motors etc </li>
<li>The Decentralized Software Services (DSS) model – To enable easy access and response to your robots and devices, via desktop, web etc </li>
</ul>
<p>Now, the fun part.</p>
<h3>Your First Simulation</h3>
</p>
<p>So, Let us create a quick simulation, using the Microsoft Visual Programming Language environment. </p>
<p><strong>1 – Bring up the VPL Designer</strong></p>
<p>Assuming that you’ve already got the Microsoft Robotic Developer Studio installed, goto Start –&gt; Programs –&gt; Microsoft Robotics Developer Studio 2008 R3 –&gt; Microsoft Visual Programming Language 2008 R3, to bring up the Visual Programming Language environment.</p>
<p>Note that you’ll get the VPL Designer, and you’ve a Basic Activities toolbox and Services toolbox on the left pane, a Designer in the middle, and a Project explorer pane towards the right.</p>
<p><a href="http://lh4.ggpht.com/__Mw4iY-4nuY/TDHX6CymnJI/AAAAAAAAA3s/oKK-EC7giEY/s1600-h/image18.png"><img title="image" border="0" alt="image" src="http://lh6.ggpht.com/__Mw4iY-4nuY/TDHYIVGjjPI/AAAAAAAAA3w/MB12PjpP9R0/image_thumb12.png?imgmax=800" width="710" height="457" /></a> </p>
<p><strong>2 – Let us pick a Joystick</strong> </p>
<p>In the Services pane, search for <em>Joystick</em> to filter the listings. Just drag and drop Desktop Joystick from the Services toolbox to the designer pane as shown below. You’ll see a rectangular indicator with a set of connectors.</p>
<p><a href="http://lh5.ggpht.com/__Mw4iY-4nuY/TDHYR8cY0QI/AAAAAAAAA30/m0P028Pke0Y/s1600-h/image22.png"><img title="image" border="0" alt="image" src="http://lh3.ggpht.com/__Mw4iY-4nuY/TDHYXTicEFI/AAAAAAAAA34/sgQT4xOdZZM/image_thumb14.png?imgmax=800" width="714" height="461" /></a> </p>
</p>
<p><strong>3 – Let us pick a Target service</strong></p>
<p>The next step is obviously to pick a target to receive our Joystick notifications. So, again from the services pane, locate a simple Generic Differential Drive device, and drag it to the designer area as we did for the Joystick. </p>
<p><a href="http://lh3.ggpht.com/__Mw4iY-4nuY/TDHYfRA0yUI/AAAAAAAAA38/D0O8vaxSDbg/s1600-h/image35.png"><img title="image" border="0" alt="image" src="http://lh3.ggpht.com/__Mw4iY-4nuY/TDHYoVz88KI/AAAAAAAAA4A/KYVN6TKVmrE/image_thumb21.png?imgmax=800" width="775" height="492" /></a> </p>
</p>
<p><strong>4 – Connect the Joystick to our target</strong></p>
<p>The next step is to connect the Joystick to the target device. For this, create a connection from the Notification icon of our DesktopJoystick towards the GenerciDifferntialDrive indicator (You can click and drag), so that it’ll bring up the Connections dialog box. There, on the ‘From’ area, select UpdateAxes, and ‘To’ area, select <em>SetDrivePower</em>. </p>
<p><a href="http://lh4.ggpht.com/__Mw4iY-4nuY/TDHYvy4vGlI/AAAAAAAAA4E/NYteMFkQwV0/s1600-h/image45.png"><img title="image" border="0" alt="image" src="http://lh4.ggpht.com/__Mw4iY-4nuY/TDHY6fel3oI/AAAAAAAAA4I/JyR4VSOog4s/image_thumb27.png?imgmax=800" width="303" height="231" /></a>&#160;&#160; <a href="http://lh4.ggpht.com/__Mw4iY-4nuY/TDHZJpuAksI/AAAAAAAAA4M/R4DROwvyQak/s1600-h/image50.png"><img title="image" border="0" alt="image" src="http://lh4.ggpht.com/__Mw4iY-4nuY/TDHZfykD-GI/AAAAAAAAA4Q/sx8yj4y1ikc/image_thumb30.png?imgmax=800" width="430" height="384" /></a> </p>
<p><a href="http://lh5.ggpht.com/__Mw4iY-4nuY/TDHZpiFFN4I/AAAAAAAAA4U/S7GJ69FyivQ/s1600-h/image40.png"></a>By common sense, this means that when ever user changes the axes of the Joystick, the notification will be pumped to SetDrivePower action of our <em>GenericDifferentialDrive</em> service</p>
</p>
</p>
<p><strong>5 – Set the data properties</strong></p>
<p>Once you press OK button of the connections dialog, this will bring up the Data Connections dialog box. There, you need to check the ‘<em>Edit Values directly</em>’ checkbox (see the <em>Data Connections</em> dialog box below), so that you can edit the values. Modify the Values to what you see in the dialog box below. The target variables (LeftWheelPower and RightWheelPower) represent the parameters of <em>SetDrivePower</em> notification we specified in the above step. The X and Y values represent the input values we are getting from the <em>DesktopJoystick</em> service. And finally, your diagram should look like what you see in the Diagram pane below. You can select the Connector anytime to edit the data connection properties you just specified.</p>
<p>&#160;<img title="image" border="0" alt="image" align="left" src="http://lh4.ggpht.com/__Mw4iY-4nuY/TDHZwnHs0tI/AAAAAAAAA4Y/ugw5pSaEqAk/image_thumb36.png?imgmax=800" width="426" height="380" /><a href="http://lh3.ggpht.com/__Mw4iY-4nuY/TDHZ2EkRoHI/AAAAAAAAA4c/WlE1vwHx_uU/s1600-h/image71.png"><img title="image" border="0" alt="image" align="right" src="http://lh4.ggpht.com/__Mw4iY-4nuY/TDHZ7f6Zn1I/AAAAAAAAA4g/IWZ59VhN6sY/image_thumb45.png?imgmax=800" width="583" height="380" /></a>&#160;&#160;&#160;&#160; </p>
<p>&#160;</p>
</p>
</p>
<p>&#160; </p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p><strong>6 – Specify a manifest for your DifferentialDrive service</strong></p>
<p>The final step is to specify a manifest for the GenericDifferentialDrive Service. For this, Select the GenericDifferentialDrive service by clicking it to bring up the properties in the Properties window. In the Properties window, select the Configuration as “Use a manifest”, and click the ‘Import’ button to select a manifest. This will bring up a dialog box, and select the <em>IRobot.Create.Simulation.Manifest</em>, so that it’ll appear in the properties windows as shown below.</p>
<p><a href="http://lh6.ggpht.com/__Mw4iY-4nuY/TDHaA0GpvcI/AAAAAAAAA4k/o1UbYFu-oyI/s1600-h/image76.png"><img title="image" border="0" alt="image" src="http://lh4.ggpht.com/__Mw4iY-4nuY/TDHaG2CHPEI/AAAAAAAAA4o/3GwpqslSTWI/image_thumb48.png?imgmax=800" width="779" height="566" /></a>&#160; </p>
<p><strong>7 – Time for action, Run the simulation.</strong></p>
<p>Just press F5 to run the simulation. You’ll see the simulation environment coming up. Just use your mouse in the Desktop Joystick window, and see the robot moving in the simulator.</p>
<p><a href="http://lh6.ggpht.com/__Mw4iY-4nuY/TDHaOOWgOnI/AAAAAAAAA4s/lli8Z_GuAgw/s1600-h/image81.png"><img title="image" border="0" alt="image" src="http://lh5.ggpht.com/__Mw4iY-4nuY/TDHaXHR3jMI/AAAAAAAAA4w/8TUIi7B2Z4E/image_thumb51.png?imgmax=800" width="811" height="511" /></a> </p>
<p>Go ahead and explore more. Have a look at the samples that came with your Robotic Studio installation. Happy Coding!!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/amazedsaint.wordpress.com/273/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/amazedsaint.wordpress.com/273/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/amazedsaint.wordpress.com/273/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/amazedsaint.wordpress.com/273/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/amazedsaint.wordpress.com/273/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/amazedsaint.wordpress.com/273/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/amazedsaint.wordpress.com/273/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/amazedsaint.wordpress.com/273/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/amazedsaint.wordpress.com/273/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/amazedsaint.wordpress.com/273/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/amazedsaint.wordpress.com/273/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/amazedsaint.wordpress.com/273/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/amazedsaint.wordpress.com/273/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/amazedsaint.wordpress.com/273/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=273&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://amazedsaint.wordpress.com/2010/07/05/hobby-programming-%e2%80%93-creating-your-first-robotic-simulation-using-microsoft-robotic-dev-studio-and-visual-programming-language/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da8002b8d2a0051531f0ffc4213af039?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">amazedsaint</media:title>
		</media:content>

		<media:content url="http://lh3.ggpht.com/__Mw4iY-4nuY/TDHXvEMh3pI/AAAAAAAAA3o/_A_-ZwXTB9g/image_thumb8.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh6.ggpht.com/__Mw4iY-4nuY/TDHYIVGjjPI/AAAAAAAAA3w/MB12PjpP9R0/image_thumb12.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh3.ggpht.com/__Mw4iY-4nuY/TDHYXTicEFI/AAAAAAAAA34/sgQT4xOdZZM/image_thumb14.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh3.ggpht.com/__Mw4iY-4nuY/TDHYoVz88KI/AAAAAAAAA4A/KYVN6TKVmrE/image_thumb21.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh4.ggpht.com/__Mw4iY-4nuY/TDHY6fel3oI/AAAAAAAAA4I/JyR4VSOog4s/image_thumb27.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh4.ggpht.com/__Mw4iY-4nuY/TDHZfykD-GI/AAAAAAAAA4Q/sx8yj4y1ikc/image_thumb30.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh4.ggpht.com/__Mw4iY-4nuY/TDHZwnHs0tI/AAAAAAAAA4Y/ugw5pSaEqAk/image_thumb36.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh4.ggpht.com/__Mw4iY-4nuY/TDHZ7f6Zn1I/AAAAAAAAA4g/IWZ59VhN6sY/image_thumb45.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh4.ggpht.com/__Mw4iY-4nuY/TDHaG2CHPEI/AAAAAAAAA4o/3GwpqslSTWI/image_thumb48.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh5.ggpht.com/__Mw4iY-4nuY/TDHaXHR3jMI/AAAAAAAAA4w/8TUIi7B2Z4E/image_thumb51.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>A Convention based Approach for wiring your Views to ViewModels in MVVM &#8211; AutoViewModelLocator</title>
		<link>http://amazedsaint.wordpress.com/2010/06/29/a-convention-based-approach-for-wiring-your-views-to-viewmodels-in-mvvm-autoviewmodellocator/</link>
		<comments>http://amazedsaint.wordpress.com/2010/06/29/a-convention-based-approach-for-wiring-your-views-to-viewmodels-in-mvvm-autoviewmodellocator/#comments</comments>
		<pubDate>Tue, 29 Jun 2010 07:34:00 +0000</pubDate>
		<dc:creator>amazedsaint</dc:creator>
				<category><![CDATA[.NET 4.0]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://amazedsaint.wordpress.com/2010/06/29/a-convention-based-approach-for-wiring-your-views-to-viewmodels-in-mvvm-autoviewmodellocator</guid>
		<description><![CDATA[Preface This post assumes you are familiar a bit with the MVVM concepts. Otherwise, here is a 5 minute overview from John Papa How do you wire up your ViewModels to your Views in your WPF and Silverlight apps? Of course, the simplest approach is assigning your View Model’s instance to the View’s data context, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=272&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Preface</h3>
<p> This post assumes you are familiar a bit with the MVVM concepts. Otherwise, here is a <a href="http://johnpapa.net/silverlight/5-minute-overview-of-mvvm-in-silverlight/">5 minute overview from John Papa</a></p>
<p>How do you wire up your ViewModels to your Views in your WPF and Silverlight apps? Of course, the simplest approach is assigning your View Model’s instance to the View’s data context, in the code behind <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<pre class="c#">    /// &lt;summary&gt;
    /// Interaction logic for MainWindow.xaml
    /// &lt;/summary&gt;
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
        }
    </pre>
<h3><a href="http://lh6.ggpht.com/__Mw4iY-4nuY/TCma9N_44kI/AAAAAAAAA3M/ufZ21gnH1js/s1600-h/image%5B14%5D.png"><img title="image" border="0" alt="image" align="right" src="http://lh3.ggpht.com/__Mw4iY-4nuY/TCma9hgjmbI/AAAAAAAAA3Q/faUY2nRW9Mk/image_thumb%5B8%5D.png?imgmax=800" width="222" height="240" /></a>Understanding The ViewModelLocator Concept</h3>
<p>An alternate way to do the above task is via a ViewModelLocator implementation, mainly so that you can preserve the <em>Blendability</em> &#8211; to enable designers to see see the correct preview of the View. <a href="http://www.galasoft.ch/">Laurent Bugnion</a> has a pretty neat implementation of <a href="http://mvvmlight.codeplex.com/sourcecontrol/changeset/view/35938?projectName=mvvmlight#790544">ViewModelLocator</a> in his <a href="http://mvvmlight.codeplex.com/">MVVM Light toolkit</a> . A simple approach to use ViewModelLoator in MVVMLight is &#8211; you can create an instance of ViewModelLocator and keep it in App.xaml as a global resource, so that you can bind your views to that – As shown below. Assume we have a MainWindow.xaml view and a MainViewModel class as our view model</p>
<p><strong>1 &#8211; Create a global resource in your App.xaml </strong></p>
<pre class="xml">    &lt;Application.Resources&gt;
        &lt;!--Global View Model Locator--&gt;
        &lt;vm:ViewModelLocator x:Key=&quot;Locator&quot;
                             d:IsDataSource=&quot;True&quot; /&gt;
    &lt;/Application.Resources&gt;</pre>
<p><strong>2 &#8211; You can bind to your locator from your Views. </strong></p>
<pre class="xml">&lt;Window x:Class=&quot;MvvmLightApp.MainWindow&quot;
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
        Title=&quot;MainWindow&quot;
        Height=&quot;300&quot;
        Width=&quot;300&quot;
        DataContext=&quot;{Binding Main, Source={StaticResource Locator}}&quot;&gt;

		&lt;!-- More Xaml --&gt;

&lt;/Window&gt;	</pre>
<p>If you are interested in the actual implementation of ViewModelLocator in MVVMLight, here is a ‘trimmed down’ version (The whole code of <a href="http://mvvmlight.codeplex.com/sourcecontrol/changeset/view/35938?projectName=mvvmlight#790544">ViewModelLocator.cs</a> is here in codeplex, under MVVMLight repository)</p>
<pre class="c#">  public class ViewModelLocator
    {
        private static MainViewModel _main;

        /// &lt;summary&gt;
        /// Initializes a new instance of the ViewModelLocator class.
        /// &lt;/summary&gt;
        public ViewModelLocator()
        {
            CreateMain();
        }

        /// &lt;summary&gt;
        /// Gets the Main property.
        /// &lt;/summary&gt;
        public static MainViewModel MainStatic
        {
            get
            {
                if (_main == null)
                {
                    CreateMain();
                }

                return _main;
            }
        }

        /// Gets the Main property.
        public MainViewModel Main
        {
            get
            {
                return MainStatic;
            }
        }

        /// Provides a deterministic way to create the Main property.
        public static void CreateMain()
        {
            if (_main == null)
            {
                _main = new MainViewModel();
            }
        }

		//Clean up code omitted..

    }	</pre>
<p>As you can see, you are expected to expose a property per ViewModel that returns a singleton instance of the same &#8211; so that we can bind to the same from the View.&#160; Of course, the MVVMLight implementation is pretty clean and neatly blendable.</p>
<h3>Locating ViewModels by Convention – AutoViewModelLocator</h3>
<p>I was a bit lazy to create a property per ViewModel in the ViewModelLocator, and thought it is nice if I get my ViewModels resolved by convention. Thus born the AutoViewModelLocator. Have a look at the source code first.</p>
<pre class="c#"> public class AutoViewModelLocator
    {
        private static List&lt;object&gt; _viewModels = new List&lt;object&gt;();

        /// &lt;summary&gt;
        /// Return the view model based
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;name&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public object this[string name]
        {
            get
            {
                //Need to have a cleaner way of doing this
                var type = typeof(AutoViewModelLocator).Assembly.GetTypes().First
                 (t =&gt; t.IsClass &amp;&amp; t.Name.EndsWith(name + &quot;ViewModel&quot;));

                var obj = _viewModels.Find(vm =&gt; vm.GetType() == type);

                if (obj != null)
                {
                    return obj;
                }
                else
                {
                    obj = Activator.CreateInstance(type);
                    _viewModels.Add(obj);
                    return obj;
                }
            }
        }

        /// &lt;summary&gt;
        /// Cleans up all the resources.
        /// &lt;/summary&gt;
        public static void Cleanup()
        {
            foreach (var vm in _viewModels)
            {
                //Cleaup here
            }
        }
    }</pre>
<p>Nothing big there. As you can see, we are instantiating the view models based on reflection. In actual implementation, you may use a better resolution method, probably using an Container or so.</p>
<p>Anyway, now you can use the AutoViewModelLocator much like we explained earlier – by creating it as a global resource in App.xaml, and then binding to the same from the View. How ever, please note that in the View, we should bind to the Indexer from Xaml (Please have a look at the source code attached). </p>
<p>Let us test our Locator via a simple ViewModel and a View.</p>
<p><strong>Our Minimal View Model</strong> </p>
<pre class="c#"> //Our minimal view model
 public class MainViewModel
    {

        public string Data
        {
            get
            {
                return &quot;Hello via AutoViewModelLocator&quot;;
            }
        }
    }</pre>
<p><strong>Binding the View </strong></p>
<p>Note that we are binding the data context of the control to the Indexer of our AutoViewModelLocator. And we have a text box that binds to our above Data property. Here is how that looks like in Visual Studio.</p>
<p><a href="http://lh4.ggpht.com/__Mw4iY-4nuY/TCma-nC8URI/AAAAAAAAA3U/97nWD49mbNs/s1600-h/image%5B4%5D.png"><img title="image" border="0" alt="image" src="http://lh5.ggpht.com/__Mw4iY-4nuY/TCma_cRW4DI/AAAAAAAAA3Y/caVKjjhcePc/image_thumb%5B2%5D.png?imgmax=800" width="696" height="439" /></a></p>
<p>And in Expression Blend 4.0</p>
<p><a href="http://lh4.ggpht.com/__Mw4iY-4nuY/TCmbAE9KavI/AAAAAAAAA3c/ldIFPdmAnvM/s1600-h/image%5B9%5D.png"><img title="image" border="0" alt="image" src="http://lh6.ggpht.com/__Mw4iY-4nuY/TCmbA3553AI/AAAAAAAAA3g/ClMOKhDYxhc/image_thumb%5B5%5D.png?imgmax=800" width="652" height="367" /></a> </p>
<p>Happy Coding!!</p>
<p><strong>[+]</strong> <a href="http://amazedsaint.net/cvml.zip"><strong>Download Related Source Code</strong></a></p>
<p>&#160;</p>
<p>There are more interesting reads here, make sure you read about</p>
<ul>
<li><a href="http://amazedsaint.blogspot.com/2010/05/4-net-40-libraries-you-should-know.html">4 .NET 4.0 Libraries You *Should* Know Better – MEF, Reactive, Tasks and Dynamic</a></li>
<li><a href="http://amazedsaint.blogspot.com/2010/05/tasks-1-2-3-parallel-extensions-in-net.html">Developing for Multicore machines. Tasks in .NET 4.0 &#8211; Why/What/How?</a></li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/amazedsaint.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/amazedsaint.wordpress.com/272/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/amazedsaint.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/amazedsaint.wordpress.com/272/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/amazedsaint.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/amazedsaint.wordpress.com/272/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/amazedsaint.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/amazedsaint.wordpress.com/272/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/amazedsaint.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/amazedsaint.wordpress.com/272/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/amazedsaint.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/amazedsaint.wordpress.com/272/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/amazedsaint.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/amazedsaint.wordpress.com/272/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=272&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://amazedsaint.wordpress.com/2010/06/29/a-convention-based-approach-for-wiring-your-views-to-viewmodels-in-mvvm-autoviewmodellocator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da8002b8d2a0051531f0ffc4213af039?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">amazedsaint</media:title>
		</media:content>

		<media:content url="http://lh3.ggpht.com/__Mw4iY-4nuY/TCma9hgjmbI/AAAAAAAAA3Q/faUY2nRW9Mk/image_thumb%5B8%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh5.ggpht.com/__Mw4iY-4nuY/TCma_cRW4DI/AAAAAAAAA3Y/caVKjjhcePc/image_thumb%5B2%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh6.ggpht.com/__Mw4iY-4nuY/TCmbA3553AI/AAAAAAAAA3g/ClMOKhDYxhc/image_thumb%5B5%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>#DevCon 2010 by K-MUG : Agenda, VS2010 Launch, Location, Speakers, And Places To See</title>
		<link>http://amazedsaint.wordpress.com/2010/06/26/devcon-2010-by-k-mug-agenda-vs2010-launch-location-speakers-and-places-to-see/</link>
		<comments>http://amazedsaint.wordpress.com/2010/06/26/devcon-2010-by-k-mug-agenda-vs2010-launch-location-speakers-and-places-to-see/#comments</comments>
		<pubDate>Sat, 26 Jun 2010 04:47:00 +0000</pubDate>
		<dc:creator>amazedsaint</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Community]]></category>
		<category><![CDATA[K-MUG]]></category>
		<category><![CDATA[Me]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://amazedsaint.wordpress.com/2010/06/26/devcon-2010-by-k-mug-agenda-vs2010-launch-location-speakers-and-places-to-see</guid>
		<description><![CDATA[K-MUG (Kerala Microsoft Users Group) is pretty excited to announce DevCon2010, the Grant Developer conference in Kerala – The God’s own land. DevCon 2010 will be conducted in Park Centre, Techopark, Trivandrum, Kerala &#8211; on 3rd and 4th July, 2010. We have different sessions planned as a part of this event. A lot of excitement [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=271&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://k-mug.org">K-MUG</a> (Kerala Microsoft Users Group) is pretty excited to announce <a href="http://k-mug.org/events/devcon2010/">DevCon2010</a>, the Grant Developer conference in Kerala – The God’s own land. DevCon 2010 will be conducted in Park Centre, <a href="http://technopark.org">Techopark</a>, Trivandrum, Kerala &#8211; on 3rd and 4th July, 2010. We have different sessions planned as a part of this event.</p>
<p>A lot of excitement is there in the air, and the focus will be on Cloud computing, VS2010 Features, Robotics, Windows Phone 7, Azure, Application Compatibility, ASP.NET etc. I would be one of the speakers as well. Walk in, uplift yourself, and go back with some great energy.</p>
<p>We’ll also launch Microsot Office 2010 during the event.</p>
<p><a href="http://lh3.ggpht.com/__Mw4iY-4nuY/TCV_Pz1i9eI/AAAAAAAAA3E/2owaMH8KWn0/s1600-h/image%5B21%5D.png"><img title="image" border="0" alt="image" align="left" src="http://lh5.ggpht.com/__Mw4iY-4nuY/TCV_RFKzbZI/AAAAAAAAA3I/SNEzYTosM00/image_thumb%5B15%5D.png?imgmax=800" width="660" height="244" /></a> </p>
</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<h2>Speakers</h2>
<p>We’ve got speakers including <a href="http://www.janakiramm.net/">Janakiram</a>, Vijay (<a href="http://www.msigeek.com">msigeek</a>), <a href="http://www.msigeek.com/3966/buddyhome-a-hobby-robot-project-by-ramaprasanna-chellamuthu">Ramaprasanna</a>, <a href="http://www.codegeeks.net/">Shobhan</a>, <a href="http://weblogs.asp.net/shijuvarghese/">Shiju</a>, <a href="http://sreesharp.com">Sreeju</a>, Praseed, Jene, Manu etc.&#160; Checkout the speakers page in <a href="http://k-mug.org/events/devcon2010/">DevCon</a> 2010 website. </p>
<p><img src="http://www.sreesharp.com/devcon2010/wp-content/uploads/2010/06/jani.jpg" />&#160;<img src="http://www.sreesharp.com/devcon2010/wp-content/uploads/2010/06/VJ1.jpg" width="87" height="119" /> <img src="http://www.virtualtechdays.com/vtdadmin/retrieveImages.aspx?showid=75" />&#160;<img src="http://k-mug.org/images/Sreejumon.jpg" /><img src="http://k-mug.org/images/devcon2010/manu.jpg" /></p>
<p>&#160;<img src="http://k-mug.org/images/praseed.jpg" />&#160;<img src="http://k-mug.org/cfs-filesystemfile.ashx/__key/CommunityServer.Components.SiteFiles/Jeen.JPG" width="95" height="116" />&#160;<img src="http://k-mug.org/images/shiju.JPG" />&#160;<img src="http://k-mug.org/images/devcon2010/anoop_m.jpg" />&#160;<img src="http://k-mug.org/images/devcon2010/shobankumar.jpg" /></p>
<p>Oh yea, I’m also taking a session. I’ll be taking a session on VS 2010 + .NET 4.0 – I’ll talk about <a href="http://amazedsaint.blogspot.com/2010/04/6-cool-vs2010-quick-tips-you-should.html">New VS2010 Features</a>, and <a href="http://amazedsaint.blogspot.com/2010/05/4-net-40-libraries-you-should-know.html">.NET 4.0 Frameworks</a>. A session on Windows Phone 7 is also planned</p>
<h2>Agenda</h2>
<p>Here is the detailed Agenda.</p>
<p><strong>Day 1 (3rd July – Saturday) </strong></p>
<ul>
<li>08:30AM – 09:15AM – Registration Confirmation</li>
<li>09:15AM – 09:30AM – Welcome Speech</li>
<li>09:30AM – 10:15AM – Key Note Session – “Cloud – The Meta Platform”</li>
<li>10:15AM – 11:00AM – New features in .NET 4.0 &amp; Visual Studio 2010</li>
<li>11:00AM – 11:15AM – Tea break</li>
<li>11:15AM – 12:15PM – Robotics Programing</li>
<li>12:15PM – 01:15PM – Web Security and Security Auditing</li>
<li>01:15PM – 02:15PM – Lunch</li>
<li>02:15PM – 03:15PM – Windows Azure</li>
<li>03:15PM – 04:00PM – Great Developer Contest – Final</li>
<li>04:00PM – 05:00PM – Managing Application Compatibility in Windows 7</li>
</ul>
<p><strong>Day 2 (4th July – Sunday)</strong></p>
<ul>
<li>08:30AM – 09:30AM – Registration Confirmation</li>
<li>09:30AM – 10:30AM – Data on the Cloud</li>
<li>10:30AM – 11:30AM – Mixed Mode Windows development using C# and C++</li>
<li><em>11:30AM – 11:45AM – Tea Break</em></li>
<li>11:45AM – 12:00PM – Visual Studio 2010 tips</li>
<li>12:30PM – 01:30PM – Tuning Tools in SQL Server 2008</li>
<li><em>01:30PM – 02:30PM – Lunch</em></li>
<li>02:30PM – 03:15PM – ASP.NET MVC</li>
<li>03:15PM – 04:00PM – Windows 7 Phone</li>
<li>04:00PM – 05:00PM – Closing Ceremony</li>
</ul>
<p>We’ll also perform the Microsoft Office 2010 Launch during the event. </p>
<h2>How to Reach</h2>
<p>Kerala is known for it’s natural beauty, and is called God’s own land. The event is in <a href="http://technopark.org">Technopark</a>, Trivandrum, Kerala – Technopark is the greenest IT Park in India. </p>
<p><a href="http://maps.google.co.in/maps?um=1&amp;ie=UTF-8&amp;q=technopark&amp;fb=1&amp;gl=in&amp;hq=technopark&amp;cid=0,0,5779012482801929797&amp;ei=f30lTKGpF9CFrQfr2sT8BA&amp;sa=X&amp;oi=local_result&amp;ct=image&amp;resnum=1&amp;ved=0CB8QnwIwAA">See the Map</a> | <a href="http://www.technopark.org/">See Technopark Website</a> | <a href="http://www.technopark.org/photogallery/campus/index.htm">Campus Photos</a></p>
<p><img src="http://www.technopark.org/photogallery/campus/images/01b.jpg" /></p>
<h2>Places To See</h2>
<p>Don’t miss these places, if you are in Trivandrum. These locations are near by.</p>
<p><img src="http://t0.gstatic.com/images?q=tbn:kWosZ1Nrkld9MM:http://i24.photobucket.com/albums/c4/rajithtvm/Veli_floatingrest.jpg" />&#160; <img src="http://t2.gstatic.com/images?q=tbn:3KCORo5vva5gJM:http://www.amitbhawani.com/india/Images/T/Thiruvananthapuram/Veli-Lake-3.jpg" width="142" height="107" />&#160; <img src="http://t1.gstatic.com/images?q=tbn:vBipyKaB-pZIxM:http://i1.trekearth.com/photos/98312/sree_padmanabha_swami_temple.jpg" width="143" height="107" />&#160;<img src="http://t2.gstatic.com/images?q=tbn:m8omBRjvtzoTGM:http://www.keralatravels.com/webadmin/upload/35/kovalam.jpg" width="145" height="109" /></p>
<ul>
<li>Veli Tourist Village:</li>
<ul>
<li>It is about 5kms from the place of DevCon event, and boating facilities are offered at this picnic spot. Speed boats, restaurants and well landscaped gardens are available. </li>
</ul>
<li>Kovalam:</li>
<ul>
<li>It is a globally renowned beach destination of Trivandrum and is strewn with the coconut groves that make it a tropical paradise </li>
</ul>
<li>Padmanabhaswamy Vishnu Temple:</li>
<ul>
<li>It is a magnificent temple, which featuring pure Dravidian style of architecture. The temple houses the shrine of the presiding deity of Thiruvananthapuram, Lord Vishnu and was built by the Maharaja of Travancore. </li>
</ul>
<li>Napier Museum:</li>
<ul>
<li>On your travel to Trivandrum, you will also come across this museum that was built in the 19th century and is an amazing example of the affluent history of Kerala </li>
</ul>
</ul>
<p>Visit <a href="http://k-mug.org/events/devcon2010/">DevCon2010</a> website to take part in the cool contests, to book your seat etc. See you guys there!!.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/amazedsaint.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/amazedsaint.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/amazedsaint.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/amazedsaint.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/amazedsaint.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/amazedsaint.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/amazedsaint.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/amazedsaint.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/amazedsaint.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/amazedsaint.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/amazedsaint.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/amazedsaint.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/amazedsaint.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/amazedsaint.wordpress.com/271/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=271&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://amazedsaint.wordpress.com/2010/06/26/devcon-2010-by-k-mug-agenda-vs2010-launch-location-speakers-and-places-to-see/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da8002b8d2a0051531f0ffc4213af039?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">amazedsaint</media:title>
		</media:content>

		<media:content url="http://lh5.ggpht.com/__Mw4iY-4nuY/TCV_RFKzbZI/AAAAAAAAA3I/SNEzYTosM00/image_thumb%5B15%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://www.sreesharp.com/devcon2010/wp-content/uploads/2010/06/jani.jpg" medium="image" />

		<media:content url="http://www.sreesharp.com/devcon2010/wp-content/uploads/2010/06/VJ1.jpg" medium="image" />

		<media:content url="http://www.virtualtechdays.com/vtdadmin/retrieveImages.aspx?showid=75" medium="image" />

		<media:content url="http://k-mug.org/images/Sreejumon.jpg" medium="image" />

		<media:content url="http://k-mug.org/images/devcon2010/manu.jpg" medium="image" />

		<media:content url="http://k-mug.org/images/praseed.jpg" medium="image" />

		<media:content url="http://k-mug.org/cfs-filesystemfile.ashx/__key/CommunityServer.Components.SiteFiles/Jeen.JPG" medium="image" />

		<media:content url="http://k-mug.org/images/shiju.JPG" medium="image" />

		<media:content url="http://k-mug.org/images/devcon2010/anoop_m.jpg" medium="image" />

		<media:content url="http://k-mug.org/images/devcon2010/shobankumar.jpg" medium="image" />

		<media:content url="http://www.technopark.org/photogallery/campus/images/01b.jpg" medium="image" />

		<media:content url="http://t0.gstatic.com/images?q=tbn:kWosZ1Nrkld9MM:http://i24.photobucket.com/albums/c4/rajithtvm/Veli_floatingrest.jpg" medium="image" />

		<media:content url="http://t2.gstatic.com/images?q=tbn:3KCORo5vva5gJM:http://www.amitbhawani.com/india/Images/T/Thiruvananthapuram/Veli-Lake-3.jpg" medium="image" />

		<media:content url="http://t1.gstatic.com/images?q=tbn:vBipyKaB-pZIxM:http://i1.trekearth.com/photos/98312/sree_padmanabha_swami_temple.jpg" medium="image" />

		<media:content url="http://t2.gstatic.com/images?q=tbn:m8omBRjvtzoTGM:http://www.keralatravels.com/webadmin/upload/35/kovalam.jpg" medium="image" />
	</item>
		<item>
		<title>Book Review: JQuery &amp; ASP.NET Controls – 51 Tips, Tricks and Recipes</title>
		<link>http://amazedsaint.wordpress.com/2010/06/16/book-review-jquery-asp-net-controls-%e2%80%93-51-tips-tricks-and-recipes/</link>
		<comments>http://amazedsaint.wordpress.com/2010/06/16/book-review-jquery-asp-net-controls-%e2%80%93-51-tips-tricks-and-recipes/#comments</comments>
		<pubDate>Wed, 16 Jun 2010 06:35:00 +0000</pubDate>
		<dc:creator>amazedsaint</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Books]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://amazedsaint.wordpress.com/2010/06/16/book-review-jquery-asp-net-controls-%e2%80%93-51-tips-tricks-and-recipes</guid>
		<description><![CDATA[My copy of JQuery &#38; ASP.NET Controls – 51 Tips, Tricks and Recipes (published by DotnetCurry fame (and my friend and ASP.NET Architecture MVP) Suprotim Agarwal) arrived some time back. I paid some serious attention to the book over the last couple of weekends, when I was playing around with JQuery a bit to implement [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=270&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>My copy of <a href="http://www.dotnetcurry.com/order/jQueryASPNETRecipesBook.aspx" target="_blank">JQuery &amp; ASP.NET Controls – 51 Tips, Tricks and Recipes</a> (published by <a href="http://www.dotnetcurry.com" target="_blank">DotnetCurry</a> fame (and my friend and ASP.NET Architecture MVP) <a href="http://www.dotnetcurry.com/About.aspx" target="_blank">Suprotim Agarwal</a>) arrived some time back. </p>
<p>I paid some serious attention to the book over the last couple of weekends, when I was playing around with JQuery a bit to implement some desired user experience. I should say I’m pretty impressed with the book – mainly for it’s practical value, and about the way it is organized. </p>
<p>The whole book has ten sections, with multiple recipes under each section, detailing specific tasks. In short, you’ll be able to quickly find how to implement a specific functionality in JQuery, just by looking at the index. </p>
<p><a href="http://lh3.ggpht.com/__Mw4iY-4nuY/TBhpkAZO1HI/AAAAAAAAA2A/DIGt1lDrOqo/s1600-h/image%5B4%5D.png"><img title="image" border="0" alt="image" src="http://lh6.ggpht.com/__Mw4iY-4nuY/TBhpk0-SdyI/AAAAAAAAA2E/rz6NxgWoeuY/image_thumb%5B2%5D.png?imgmax=800" width="625" height="358" /></a>&#160;&#160; </p>
<p>I feel that the practical value of the book is immense. The examples and explanation are clear and concise – you don’t find any useless crap there. Each recipe has a problem statement (challenge), solution (the actual code),&#160; Explanation of the code, A link to a live demo, a note on Browsers supported,&#160; and a set of useful links on this problem. Great.</p>
<p>For my scenario, I was actually trying for implementing a Google reader like feature using JQuery – to high light multiple rows of the Grid view, so that the user can perform an operation with the high lighted rows. Wow, and I got pleasantly surprised when I saw this. </p>
<p><a href="http://lh6.ggpht.com/__Mw4iY-4nuY/TBhplZw4P8I/AAAAAAAAA2I/Wb-wmjQqvoA/s1600-h/image%5B9%5D.png"><img title="image" border="0" alt="image" src="http://lh5.ggpht.com/__Mw4iY-4nuY/TBhpmfbbirI/AAAAAAAAA2M/RukP4GH50pk/image_thumb%5B5%5D.png?imgmax=800" width="581" height="313" /></a> </p>
<p>I think the book, along with the sample code, can really fasten up the development time of web applications. For a developer, with out doubt, this e-book will serve as a travelling compass in the world of ASP.NET and JQuery, and is definitely recommended for anyone who is interested to build great user experiences with JQuery.&#160;&#160;&#160;&#160; </p>
<p>You may read <a href="http://www.dotnetcurry.com/ShowArticle.aspx?ID=393" target="_blank">5 sample chapters of the book here</a> for free. And if you are serious about learning JQuery, don’t waste time, <a href="http://www.dotnetcurry.com/order/jQueryASPNET.aspx" target="_blank">Go and buy it for $14.99</a> – The book comes with</p>
<ul>
<li>51 Tips, Tricks and Recipes with jQuery and ASP.Controls EBook (PDF) </li>
<li>Entire Source Code of the EBook </li>
<li>Cross Browser Scripts &#8211; tested on IE 7, IE 8, Firefox 3, Chrome 2, Safari 4 </li>
<li>Common code that runs on ASP.NET Page, Master Pages, and in most cases, HTML pages too. </li>
</ul>
<p>Again, congratulations to Suprotim for his great effort.</p>
<div class="wlWriterHeaderFooter" style="margin:0;padding:0;">
<div class="shoutIt"><a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http%3a%2f%2famazedsaint.blogspot.com%2f2010%2f06%2fbook-review-jquery-aspnet-controls-51.html&amp;title=Book+Review%3a+JQuery+%26+ASP.NET+Controls+%e2%80%93+51+Tips%2c+Tricks+and+Recipes"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http://amazedsaint.blogspot.com/2010/06/book-review-jquery-aspnet-controls-51.html" /></a></div>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/amazedsaint.wordpress.com/270/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/amazedsaint.wordpress.com/270/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/amazedsaint.wordpress.com/270/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/amazedsaint.wordpress.com/270/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/amazedsaint.wordpress.com/270/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/amazedsaint.wordpress.com/270/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/amazedsaint.wordpress.com/270/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/amazedsaint.wordpress.com/270/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/amazedsaint.wordpress.com/270/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/amazedsaint.wordpress.com/270/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/amazedsaint.wordpress.com/270/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/amazedsaint.wordpress.com/270/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/amazedsaint.wordpress.com/270/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/amazedsaint.wordpress.com/270/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=270&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://amazedsaint.wordpress.com/2010/06/16/book-review-jquery-asp-net-controls-%e2%80%93-51-tips-tricks-and-recipes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da8002b8d2a0051531f0ffc4213af039?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">amazedsaint</media:title>
		</media:content>

		<media:content url="http://lh6.ggpht.com/__Mw4iY-4nuY/TBhpk0-SdyI/AAAAAAAAA2E/rz6NxgWoeuY/image_thumb%5B2%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh5.ggpht.com/__Mw4iY-4nuY/TBhpmfbbirI/AAAAAAAAA2M/RukP4GH50pk/image_thumb%5B5%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://dotnetshoutout.com/image.axd?url=http://amazedsaint.blogspot.com/2010/06/book-review-jquery-aspnet-controls-51.html" medium="image">
			<media:title type="html">Shout it</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating a custom View Engine for ASP.NET MVC leveraging Text Template (T4) engine for rendering the view</title>
		<link>http://amazedsaint.wordpress.com/2010/06/11/creating-a-custom-view-engine-for-asp-net-mvc-leveraging-text-template-t4-engine-for-rendering-the-view/</link>
		<comments>http://amazedsaint.wordpress.com/2010/06/11/creating-a-custom-view-engine-for-asp-net-mvc-leveraging-text-template-t4-engine-for-rendering-the-view/#comments</comments>
		<pubDate>Fri, 11 Jun 2010 12:36:00 +0000</pubDate>
		<dc:creator>amazedsaint</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[.NET 4.0]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://amazedsaint.wordpress.com/2010/06/11/creating-a-custom-view-engine-for-asp-net-mvc-leveraging-text-template-t4-engine-for-rendering-the-view</guid>
		<description><![CDATA[This post explains how to create a View Engine for ASP.NET MVC, leveraging the Text Template (T4) infrastructure already out there for rendering the view based using a custom T4 template host. Clarification: Here, I’m not using T4 for design time code generation. We are using T4 toolkit to render the views during runtime. [+] [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=269&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://lh5.ggpht.com/__Mw4iY-4nuY/TBIfhS6p_TI/AAAAAAAAA1Y/uoG2G9ihmXY/s1600-h/image4.png"><img title="image" border="0" alt="image" align="right" src="http://lh3.ggpht.com/__Mw4iY-4nuY/TBIfjpmSH8I/AAAAAAAAA1c/s-LaIirDUj4/image_thumb2.png?imgmax=800" width="235" height="240"></a></p>
<p>This post explains how to create a View Engine for <a href="http://www.asp.net/mvc" target="_blank">ASP.NET MVC</a>, leveraging the <a href="http://msdn.microsoft.com/en-us/library/bb126445.aspx" target="_blank">Text Template (T4)</a> infrastructure already out there for rendering the view based using a custom T4 template host.</p>
<p><em>Clarification: Here, I’m not using T4 for design time code generation. We are using T4 toolkit to render the views during runtime.</em></p>
<p>[+] <a href="http://amazedsaint.net/MvcT4ViewEngine.zip" target="_blank">Download Related Source Code</a></p>
<p>For me, the most beautiful aspect of ASP.NET MVC is it’s extensibility – they way you can ‘stretch’ the framework, to make it suitable for your own needs. I highly recommend you to read this article from Code Climber’s blog &#8211; <a href="http://codeclimber.net.nz/archive/2009/04/08/13-asp.net-mvc-extensibility-points-you-have-to-know.aspx" target="_blank">13 ASP.NET MVC Extensibility Points you have to know</a></p>
<p>In this post, we’ll explore the following concepts.</p>
<ul>
<li>ViewEngines in ASP.NET MVC
<li>Creating a custom ViewEngine for ASP.NET MVC
<li>Supporting multiple View Types (our view engine will support both <em>aspx/ascx</em> files and <em>tt</em> files)
<li>Partial rendering between view types (you can render a <em>tt</em> view from an aspx view)</li>
</ul>
<h3>Preface About View Engines</h3>
<p>This is a quick recap on how the View Engine is invoked with in the ASP.NET MVC Framework. Let us start from how a controller is created and how an action is called. I’m going the easy way &#8211; the <a href="http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx" target="_blank">route handling system</a> in ASP.NET MVC invokes a DefaultControllerFactory by default, which is responsible to choose the correct controller class and an action for a given request. For example, consider the URL <em>http://Portal.com/Customer/Get/3</em> &#8211; As you know, by default, MVC will expect a <em>CustomerController</em> class with a <em>Get</em> Action inside the same, like </p>
<pre class="c#">   public class CustomerController : Controller
    {
        public ActionResult Get(int id)
        {

           //Get the customer with ID from repository, place it in ViewData
            ViewData["Customer"] = rep.GetCustomerWithId(id);

            //View method returns a Viewresult
            return View();
        }
    }</pre>
<p><a href="http://lh4.ggpht.com/__Mw4iY-4nuY/TBIflhCPP-I/AAAAAAAAA1g/z0pb-X0GNZQ/s1600-h/image%5B9%5D.png"><img title="image" border="0" alt="image" align="right" src="http://lh5.ggpht.com/__Mw4iY-4nuY/TBIfnzP3Z8I/AAAAAAAAA1k/S_Sg2M5IhsM/image_thumb%5B6%5D.png?imgmax=800" width="416" height="276"></a>The controller will invoke the correct action method, which returns an <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.actionresult.aspx" target="_blank">ActionResult</a> object. In the above example, you may see that we are returning a <em><a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.viewresult.aspx" target="_blank">ViewResult</a>.</em> In ASP.NET MVC, there are various action results, including <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.viewresult.aspx" target="_blank">ViewResult</a>, <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.contentresult.aspx" target="_blank">ContentResult</a> etc. </p>
<p>Wow, There we are. If the controller action is returning a ViewResult, the action method can use the ViewData structure (see the above example) to fill it with some values, to pass the same to ViewResult. ViewResult can locate and render a particular view template using ViewData. It does so by invoking <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.webformviewengine.aspx" target="_blank">WebFormViewEngine</a>.</p>
<p>The default View engine available with ASP.NET MVC is WebFormViewEngine, which creates a <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.webformview.aspx" target="_blank">WebFormView</a> to render your <em>aspx</em> and <em>ascx</em> files. The View Engine normally passes the path information of the file to render, along with the view context information to the view. </p>
<p>The view file name and path is normally detected based on convention – normally in the path – <em>/Views/{ControllerName}/{ActionName} </em>– i.e, If your Controller class name is CustomerController and action/method name is Get, the default view engine will expect a file in the location <em>/Views/Customer/Get.aspx</em></p>
<h3>Using Text Template Toolkit To Render A View</h3>
<p>The beauty of ASP.NET MVC is in it’s extensibility. All interaction points above can be customized the way you like. As of now, we are only interested to see how to create a custom View Engine, which can create a T4View that knows how to render a text template (tt) file, leveraging the <a href="http://msdn.microsoft.com/en-us/library/bb126445.aspx" target="_blank">Text Templating infrastructure</a>. </p>
<p>Normally, as you are aware, Text Templates (T4) are used with in Visual Studio for activities like Code Generation. When I was going through this exercise of explaining how to create a custom view engine for ASP.NET MVC, I thought it’ll be an interesting exercise to leverage T4 toolkit for the task. </p>
<p>But we’ve got a problem there – We can’t use the <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.texttemplating(VS.80).aspx" target="_blank">Microsoft.VisualStudio.TextTemplating</a> libraries, because I don&#8217;t believe that T4 can be legally redistributed without Visual Studio. So, I’ve decided to relay on the Mono equivalent T4 implementation, <a href="http://tirania.org/blog/archive/2009/Mar-10.html" target="_blank">Mono.TextTemplating</a> (included in the download)</p>
<p>Now, let us get in to the actual task. These are the steps we should do to create our view engine.</p>
<ul>
<li>A ViewEngine implementation
<ul>
<li>We’ll create a view engine by implementing the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.iviewengine.aspx" target="_blank">IViewEngine</a> interface. There is an abstract class <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.virtualpathproviderviewengine.aspx" target="_blank">VirtualPathProviderViewEngine</a> that already implements IViewEngine interface and provides some extra functionality for path detection of view files.&nbsp; VirtualPathProviderViewEngine&nbsp; has two methods we are concerned about – <em>CreateView</em> and <em>CreatePartialView</em> from where we should return a custom View, that has the path information to the template file (*.tt) to render. </li>
</ul>
<li>A View
<ul>
<li>We’ll create a view, by implementing the IView interface. <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.iview.aspx" target="_blank">IView</a> has a Render method that we are interested about. We’ll read and render the tt file, leveraging the TT engine </li>
</ul>
<li>A T4 Host
<ul>
<li>We’ll also create a custom T4 host, by implementing the <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.texttemplating.itexttemplatingenginehost(VS.80).aspx" target="_blank">ITextTemplatingEngineHost</a> interface, for self hosting the template transformation process. </li>
</ul>
</li>
</ul>
<p>Once we’ve the above pieces, we need to register our custom view engine with ASP.NET MVC. That’s pretty simple, and we’ll see that soon. </p>
<h3>The View Engine Implementation</h3>
<p><a href="http://lh4.ggpht.com/__Mw4iY-4nuY/TBIfpf6cpXI/AAAAAAAAA1o/SafhJbjfHdg/s1600-h/image%5B16%5D.png"><img title="image" border="0" alt="image" align="right" src="http://lh5.ggpht.com/__Mw4iY-4nuY/TBIfq1yjAcI/AAAAAAAAA1s/mHZog2aR1AE/image_thumb%5B11%5D.png?imgmax=800" width="245" height="201"></a>May be it is time to have a look in to the actual view engine implementation. A slight variation to what we discussed earlier. Instead of creating a ViewEngine from scratch, we are going to inherit our ViewEngine from <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.virtualpathproviderviewengine.aspx" target="_blank">VirtualPathProviderViewEngine</a> that’s already there in MVC framework – so that all the file path logic will be taken care automatically. VirtualPathProviderViewEngine provides some extra functionality so that we can specify the location formats to look for our view files (in this case, *.tt files), when ever the View Engine is invoked. </p>
<p>Alright. Let us be a bit more creative here. What about creating a View Engine that can handle the <em>aspx and ascx files</em> *along with* the text template files? Creating such a composite view engine is pretty simple – So, this is what our view engine should do.</p>
<ul>
<li>First, the view engine should look for a View file that ends with <em>*.view.tt</em>
<ul>
<li>If that file exists, create and return a T4View that’ll render our tt file
<li>If not, look for a View file that ends with *.ascx or *.aspx
<ul>
<li>If exists, create and return a WebFormView that knows how to render the aspx/ascx files. </li>
</ul>
</li>
</ul>
</li>
</ul>
<p>Enough blabbering. Here we go, the code of our CompositeViewEngine. All the implementations are in <em>MvcT4ViewEngine.Lib</em> project, so you may download the related source code from the above link to have a look at the same side by side.</p>
<pre class="c#">    /// &lt;summary&gt;
    /// A composite view engine to help plugging view engines
    /// &lt;/summary&gt;
    public class CompositeViewEngine : VirtualPathProviderViewEngine
    {
        // Ctor - Let us set all location formats
        public CompositeViewEngine()
        {
            base.MasterLocationFormats = new string[] { "~/Views/{1}/{0}.master",
                                                        "~/Views/Shared/{0}.master" };
            base.AreaMasterLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.master",
                                                         "~/Areas/{2}/Views/Shared/{0}.master" };
            base.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.view.tt",
                                                      "~/Views/{1}/{0}.aspx", "~/Views/{1}/{0}.ascx",
                                                      "~/Views/Shared/{0}.view.tt",
                                                      "~/Views/Shared/{0}.aspx", "~/Views/Shared/{0}.ascx" };
            base.AreaViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.view.tt",
                                                       "~/Areas/{2}/Views/{1}/{0}.aspx", "~/Areas/{2}/Views/{1}/{0}.ascx",
                                                       "~/Areas/{2}/Views/Shared/{0}.view.tt",
                                                       "~/Areas/{2}/Views/Shared/{0}.aspx", "~/Areas/{2}/Views/Shared/{0}.ascx" };
            base.PartialViewLocationFormats = base.ViewLocationFormats;
            base.AreaPartialViewLocationFormats = base.AreaViewLocationFormats;
        }

        /// &lt;summary&gt;
        /// Handle the creation of a partial view
        /// &lt;/summary&gt;
        protected override IView CreatePartialView
                 (ControllerContext controllerContext, string partialPath)
        {
            if (partialPath.EndsWith(".view.tt"))
                return new T4View(partialPath);
            else
                return new WebFormView(partialPath, null);
        }

        /// &lt;summary&gt;
        /// Handle the creation of a view
        /// &lt;/summary&gt;
        protected override IView CreateView
               (ControllerContext controllerContext, string viewPath, string masterPath)
        {
            if (viewPath.EndsWith(".view.tt") &amp;&amp; String.IsNullOrEmpty(masterPath))
            {
                return new T4View(viewPath);
            }
            else if (viewPath.EndsWith(".view.tt") &amp;&amp; !String.IsNullOrEmpty(masterPath))
            {
                return new T4View(viewPath,masterPath);
            }
            else
                return new WebFormView(viewPath, masterPath);
        }

        /// &lt;summary&gt;
        /// Check if the file exists
        /// &lt;/summary&gt;
        protected override bool FileExists
                (ControllerContext controllerContext, string virtualPath)
        {
            return base.FileExists(controllerContext, virtualPath);
        }

    }
</pre>
<pre></pre>
<p>That looks pretty simple, right? Have a look at the constructor, and you’ll find that we are specifying the path format constraints to detect our T4 view files as well (*.view.tt), along with the aspx and ascx path formats. And you may also find that in the CreateView and CreatePartialView, we are creating and returning a WebFormView, in case the *.vew.tt files are not found. CreatePartialView will be invoked when a partial rendering is requested – e.g. when the user calls a RenderPartial method in a view.</p>
<p>Now, the interesting aspect there is, you can render a text template view from an aspx view, using the Ht</p>
<h3>The View Implementation</h3>
<p>The T4View implementation is also very simple. We are just invoking our T4 host, to render the tt files. Have a look at the Render method below. You may also note that we are passing the ViewContext to the host, so that we can access the view context later in our text template files, via the host variable.</p>
<pre class="c#">     /// &lt;summary&gt;
    /// A view based on T4
    /// &lt;/summary&gt;
    public class T4View : IView
    {

        #region IView Members

        private string viewName = string.Empty;
        private string masterName = string.Empty;

        public T4View(string ttViewName)
        {
            viewName = ttViewName;
        }
        public T4View(string ttViewName, string masterttName)
        {
            viewName = ttViewName;
            masterName = masterttName;
        }

        /// &lt;summary&gt;
        /// Render our tt file
        /// &lt;/summary&gt;
        /// &lt;param name="viewContext"&gt;&lt;/param&gt;
        /// &lt;param name="writer"&gt;&lt;/param&gt;
        public void Render(ViewContext viewContext, System.IO.TextWriter writer)
        {
            string filePath = viewContext.HttpContext.Server.MapPath(viewName);
            string masterPath=string.Empty;

            if (!string.IsNullOrEmpty(masterName))
            {
                masterPath=viewContext.HttpContext.Server.MapPath(masterName);
            }

            var thost = new T4TemplateHost();
            thost["ViewContext"] = viewContext;

            string data = string.Empty;
            var results = thost.ProcessTemplate(filePath, masterPath, out data);
            if (results.HasErrors)
            {
                writer.WriteLine("&lt;h1&gt;errors found&lt;/h1&gt;");
            }
            foreach (var res in results)
            {
                writer.WriteLine("Error - " + (res as CompilerError).ToString());
            }
            writer.Write(data);

        }

        #endregion
    }
</pre>
<h3>About the Template Host</h3>
<p>You may see that in the Render method, we are creating an instance of our T4 template host, and requesting the template host to process our our <em>*.view.tt</em> file. You may read more about <a href="http://msdn.microsoft.com/en-us/library/bb126579.aspx" target="_blank">creating a custom template host here</a>, though I’m not detailing that much. How ever, if you are so curios, here is the ProcessTemplate method in our custom T4 host.</p>
<pre class="c#">        /// &lt;summary&gt;
        /// Process the input template
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public CompilerErrorCollection ProcessTemplate
		          (string templateFileName, string masterFileName, out string data)
        {

            if (!File.Exists(templateFileName))
            {
                throw new FileNotFoundException("The file cannot be found");
            }

            var engine = new TemplatingEngine();
            TemplateFile = templateFileName;

            //Read the text template.
            string input = File.ReadAllText(templateFileName);

            if (!string.IsNullOrEmpty(masterFileName))
            {
                input = File.ReadAllText(masterFileName).Replace("&lt;!--[Content]--&gt;",input);
            }

            //Transform the text template.
            data = engine.ProcessTemplate(input, this);
            return Errors;
        }
</pre>
<h3>Registering our View Engine</h3>
<p>The last piece of the puzzle would be to register our custom View Engine, so that the framework will use our View Engine instead of the default one. Let us create a new ASP.NET MVC Project. Now in the Global.asax.cs file of our MVC application (See MvcT4ViewEngine.Demo project in the downloaded source code), we need to specify our CompositeViewEngine as the default view engine, in the Application_Start. </p>
<pre class="c#">    protected void Application_Start()
        {
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new CompositeViewEngine());
            RegisterRoutes(RouteTable.Routes);
        }
</pre>
<p>And there we go.</p>
<p>&nbsp;</p>
<h3>The Results</h3>
<p>First of all, let us add a new GetMessage method to the HomeController ASP.NET MVC project. Our GetMessage action in the Home controller simply returns a view after storing someting in ViewData, like </p>
<pre class="c#">   public ActionResult GetMessage()
        {
            ViewData["MessageForT4"] = "Welcome to ASP.NET MVC Views using T4";
            return View();
        }
</pre>
<p>Now, add a new view, named <em>GetMessage.view.tt</em> in the <em>Views/Home&nbsp; </em>folder as shown below. And you can access the ViewData like this. </p>
<p><a href="http://lh3.ggpht.com/__Mw4iY-4nuY/TBIftWdXRpI/AAAAAAAAA1w/Y-2SXrbYEfU/s1600-h/image%5B34%5D.png"><img title="image" border="0" alt="image" src="http://lh6.ggpht.com/__Mw4iY-4nuY/TBIfwLun4EI/AAAAAAAAA10/GnWMcJpuB0A/image_thumb%5B21%5D.png?imgmax=800" width="759" height="477"></a> </p>
<p>Now, run the application, and navigate to the path <em>/Home/GetMessage</em> and you should be able to see the above view getting rendered. If you are wondering what the GetViewData method does, it fetches the ViewData context we set to the host earlier, in the above Render method.</p>
<p><a href="http://lh6.ggpht.com/__Mw4iY-4nuY/TBIfyLKnuFI/AAAAAAAAA14/F2qP1PpZwTs/s1600-h/image%5B29%5D.png"><img title="image" border="0" alt="image" src="http://lh6.ggpht.com/__Mw4iY-4nuY/TBIf0MhHKzI/AAAAAAAAA18/cGVk9msBG6s/image_thumb%5B18%5D.png?imgmax=800" width="579" height="307"></a> </p>
<p>&nbsp;</p>
<p>More interestingly, you may also try partially rendering a T4 view from an aspx file. You can use <em>Html.RenderPartial(&#8220;YourView&#8221;); </em>from your aspx view, to render the <em>YourView.view.tt</em> file – See how I’m rendering <em>IndexPart.view.tt</em> from the <em>Index.aspx</em> view, in the attached example.</p>
<h3>Conclusion</h3>
<p>The intent of this article is just to explore how to create custom view engines for ASP.NET MVC. The example view engine we put together is very elementary as of now, but I’ld like to evolve that towards something useful, so that finally it can be a part of MvcContrib. For this, several performance features like caching of compiled views needs to be implemented. That is for later.</p>
<p>Recommending you to <a href="http://twitter.com/amazedsaint" target="_blank">follow me on twitter</a> – Also, read my previous posts – <a href="http://amazedsaint.blogspot.com/2010/02/10-minute-twitter-search-app-using-duck.html" target="_blank">A duck typed view model in ASP.NET MVC</a> or <a href="http://amazedsaint.blogspot.com/2010/06/mef-or-managed-extensibility-framework.html" target="_blank">Understanding Managed Extensibility Framework and Lazy&lt;T&gt;</a> – Happy Coding!!</p>
<div class="wlWriterHeaderFooter" style="margin:0;padding:0;">
<div class="shoutIt"><a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http%3a%2f%2famazedsaint.blogspot.com%2f2010%2f06%2fcreating-custom-view-engine-for-aspnet.html&amp;title=Creating+a+custom+View+Engine+for+ASP.NET+MVC+leveraging+Text+Template+(T4)+engine+for+rendering+the+view"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http://amazedsaint.blogspot.com/2010/06/creating-custom-view-engine-for-aspnet.html" /></a></div>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/amazedsaint.wordpress.com/269/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/amazedsaint.wordpress.com/269/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/amazedsaint.wordpress.com/269/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/amazedsaint.wordpress.com/269/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/amazedsaint.wordpress.com/269/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/amazedsaint.wordpress.com/269/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/amazedsaint.wordpress.com/269/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/amazedsaint.wordpress.com/269/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/amazedsaint.wordpress.com/269/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/amazedsaint.wordpress.com/269/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/amazedsaint.wordpress.com/269/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/amazedsaint.wordpress.com/269/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/amazedsaint.wordpress.com/269/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/amazedsaint.wordpress.com/269/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=269&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://amazedsaint.wordpress.com/2010/06/11/creating-a-custom-view-engine-for-asp-net-mvc-leveraging-text-template-t4-engine-for-rendering-the-view/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da8002b8d2a0051531f0ffc4213af039?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">amazedsaint</media:title>
		</media:content>

		<media:content url="http://lh3.ggpht.com/__Mw4iY-4nuY/TBIfjpmSH8I/AAAAAAAAA1c/s-LaIirDUj4/image_thumb2.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh5.ggpht.com/__Mw4iY-4nuY/TBIfnzP3Z8I/AAAAAAAAA1k/S_Sg2M5IhsM/image_thumb%5B6%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh5.ggpht.com/__Mw4iY-4nuY/TBIfq1yjAcI/AAAAAAAAA1s/mHZog2aR1AE/image_thumb%5B11%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh6.ggpht.com/__Mw4iY-4nuY/TBIfwLun4EI/AAAAAAAAA10/GnWMcJpuB0A/image_thumb%5B21%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh6.ggpht.com/__Mw4iY-4nuY/TBIf0MhHKzI/AAAAAAAAA18/cGVk9msBG6s/image_thumb%5B18%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://dotnetshoutout.com/image.axd?url=http://amazedsaint.blogspot.com/2010/06/creating-custom-view-engine-for-aspnet.html" medium="image">
			<media:title type="html">Shout it</media:title>
		</media:content>
	</item>
		<item>
		<title>MEF or Managed Extensibility Framework and Lazy&lt;T&gt; – Being Lazy with MEF, Custom Export Attributes etc</title>
		<link>http://amazedsaint.wordpress.com/2010/06/04/mef-or-managed-extensibility-framework-and-lazyt-%e2%80%93-being-lazy-with-mef-custom-export-attributes-etc/</link>
		<comments>http://amazedsaint.wordpress.com/2010/06/04/mef-or-managed-extensibility-framework-and-lazyt-%e2%80%93-being-lazy-with-mef-custom-export-attributes-etc/#comments</comments>
		<pubDate>Fri, 04 Jun 2010 08:10:00 +0000</pubDate>
		<dc:creator>amazedsaint</dc:creator>
				<category><![CDATA[.NET 4.0]]></category>
		<category><![CDATA[Back To Basics]]></category>
		<category><![CDATA[CSharp]]></category>

		<guid isPermaLink="false">http://amazedsaint.wordpress.com/2010/06/04/mef-or-managed-extensibility-framework-and-lazyt-%e2%80%93-being-lazy-with-mef-custom-export-attributes-etc</guid>
		<description><![CDATA[Overview The objective of this post is to brief how you can leverage the lazy initialization support available in MEF. We’ll examine MEF and Lazy, and then we’ll see how to use them together. [+] Download final version of source code Preface About MEF I hope you are already using Managed Extensibility Framework to build [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=268&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Overview </h3>
<p>The objective of this post is to brief how you can leverage the lazy initialization support available in MEF. We’ll examine MEF and Lazy, and then we’ll see how to use them together.</p>
<p>[+] <a href="http://amazedsaint.net/meflazy.zip" target="_blank">Download final version of source code</a></p>
<h3>Preface About MEF</h3>
<p>I hope you are already using Managed Extensibility Framework to build beautiful software. If you are not yet there, that is a crime, and I highly recommend you to read my <a href="http://amazedsaint.blogspot.com/2009/11/mef-or-managed-extension-framework.html" target="_blank">introductory post on MEF</a>. Let us start with another very basic MEF example. Let us get back our Zoo. </p>
<p><a href="http://lh6.ggpht.com/__Mw4iY-4nuY/TAit4L912PI/AAAAAAAAA1A/eCneYHi8d8I/s1600-h/image%5B19%5D.png"><img title="image" border="0" alt="image" src="http://lh3.ggpht.com/__Mw4iY-4nuY/TAit59JflAI/AAAAAAAAA1E/LuHoyeFXjnM/image_thumb%5B10%5D.png?imgmax=800" width="477" height="124" /></a>&#160;</p>
<p>We are composing our Zoo with a couple of Animals here. </p>
<pre class="c#">    //Abstract animal interface
    interface IAnimal { void Eat(); }

    //Concrete animal 1
    [Export(typeof(IAnimal))]
    class Lion : IAnimal
    {
        public Lion() { Console.WriteLine(&quot;Grr.. Lion got created&quot;); }
        public void Eat() { Console.WriteLine(&quot;Grr.. Lion eating meat&quot;); }
    }

    //Concrete animal 2
    [Export(typeof(IAnimal))]
    class Rabbit : IAnimal
    {
        public Rabbit() { Console.WriteLine(&quot;Crrr.. Rabbit got created&quot;); }
        public void Eat() { Console.WriteLine(&quot;Crrr.. Rabbit eating carrot&quot;); }
    }

    //Our Zoo. MEF will inject animals to this zoo later, at the time of composition
    class Zoo
    {
        [ImportMany(typeof(IAnimal))]
        public IEnumerable&lt;IAnimal&gt; Animals { get; set; }
    }

    //Let us construct our zoo and animals
    class Program
    {
        static void Main(string[] args)
        {
            //Let us create a catalog and a container
            var catalog = new AssemblyCatalog(typeof(Program).Assembly);
            var container = new CompositionContainer(catalog);

            //Compose the zoo.
            var zoo = new Zoo();
            container.ComposeParts(zoo);

            //Let's feed our animals
            foreach (var animal in zoo.Animals)
                animal.Eat();

        }
    }</pre>
<p>As you remember, a catalog is a sack full of types (cookies) to export. The container will fetch these exported types from the catalog, to instantiate and import them where ever applicable &#8211; based on the matching contracts specified in the Export and Import attributes. (Note to self &#8211; Shh!! don’t mention anything about ExportProvider and ExportDefinition now). In this case, we are using a type as the contract (IAnimal) for our Export and Import. And if you run that app, you’ll see.. hm.. a cute black screen. More importantly, you’ll see that MEF has created an instance of Lion and Rabbit at the time of composition – i.e, when we call <em>container.ComposeParts. </em>See the messages we are writing from the constructor.</p>
<p><a href="http://lh3.ggpht.com/__Mw4iY-4nuY/TAit7Lj6shI/AAAAAAAAA1I/G0Cx39ObfAM/s1600-h/image4.png"><img title="image" border="0" alt="image" src="http://lh4.ggpht.com/__Mw4iY-4nuY/TAit9K7T59I/AAAAAAAAA1M/5zYtRObZT4c/image_thumb2.png?imgmax=800" width="309" height="175" /></a>&#160;</p>
<p>Note – If you want to be more realistic or if you hate animals in general, my advice is to think about your Business class instead of the Zoo, and think about some validation rules instead of those Animals. So that, you can plug in new validation rules with out affecting your entire system.</p>
<p><strong></strong></p>
<h3>Preface About Lazy&lt;T&gt;</h3>
<p>Oh yea, though MEF is seductive, let us stop thinking about that for a moment. Let us be a bit Lazy. You might have already heard about the Lazy&lt;T&gt; class in .NET 4.0. Lazy class allow you to support for lazy initialization. I.e, you can use Lazy&lt;T&gt; to defer the creation of a large or resource-intensive object, till you really need that. </p>
<p>Here is a quick example.</p>
<p>&#160;</p>
<pre class="c#">            //Let us be lazy about creating a lion
            Lazy&lt;Lion&gt; lazyLion = new Lazy&lt;Lion&gt;();

            //Do something else..

            //Actual object will be created here
            var lion = lazyLion.Value;
   </pre>
<p>The interesting point to note is, you can defer the creation of your lion, till you really need it in your flow, probably inside an <em>if</em> block or so. Another interesting aspect of Lazy&lt;T&gt; is, you can specify your own factory method to create your object, via the Lazy&lt;T&gt; constructor. See this example.</p>
<pre class="c#">            //Let us be lazy about creating our animal
            Lazy&lt;IAnimal&gt; lazyAnimal = new Lazy&lt;IAnimal&gt;(()=&gt;new Lion());

            //Actual object will be created here
            var animal = lazyAnimal.Value;</pre>
<h3>Being Lazy with MEF</h3>
<p>Now, let us see how to combine MEF and Lazy together. All right, you don’t really need to do anything special there – MEF already has some great support for Lazy. MEF can wire up your exports directly to a Lazy at the time of import. Now, let us see how to do that. We just need to make two modifications to our zoo example. Time for a KG Excercise &#8211; Spot the difference of this code example with the very first example.</p>
<pre class="c#"> //Our zoo
    class Zoo
    {
        //** MODIFICATION 1 -You need to directly import to Lazy&lt;IAnimal&gt;
        [ImportMany(typeof(IAnimal))]
        public IEnumerable&lt;Lazy&lt;IAnimal&gt;&gt; Animals { get; set; }
    }

    //Abstract animal interface
    interface IAnimal { void Eat(); }

    //Concrete animal 1
    [Export(typeof(IAnimal))]
    class Lion : IAnimal
    {
        public Lion() { Console.WriteLine(&quot;Grr.. Lion got created&quot;); }
        public void Eat() { Console.WriteLine(&quot;Grr.. Lion eating meat&quot;); }
    }

    //Concrete animal 2
    [Export(typeof(IAnimal))]
    class Rabbit : IAnimal
    {
        public Rabbit() { Console.WriteLine(&quot;Crrr.. Rabbit got created&quot;); }
        public void Eat() { Console.WriteLine(&quot;Crrr.. Rabbit eating carrot&quot;); }
    }

    //Let us construct our zoo and animals
    class Program
    {
        static void Main(string[] args)
        {
            //Let us create a catalog and a container
            var catalog = new AssemblyCatalog(typeof(Program).Assembly);
            var container = new CompositionContainer(catalog);

            //Compose the zoo.
            var zoo = new Zoo();
            container.ComposeParts(zoo);

            //** MODIFICATION 2 - An instance will be created only when you access it
            //Use the Value property of the Lazy object to initialize and access the actual value
            foreach (var animal in zoo.Animals)
                animal.Value.Eat();
        }
    }</pre>
<p>And now, to understand how this changed the flow, let us run the application. </p>
<p><a href="http://lh3.ggpht.com/__Mw4iY-4nuY/TAit-fFtDnI/AAAAAAAAA1Q/g4k4wFwKqGI/s1600-h/image%5B8%5D.png"><img title="image" border="0" alt="image" src="http://lh3.ggpht.com/__Mw4iY-4nuY/TAit_p40DEI/AAAAAAAAA1U/VpqqPTarq00/image_thumb%5B3%5D.png?imgmax=800" width="317" height="151" /></a></p>
<p>You’ll see that our animals are getting created only when we consume them – and <em>not</em> at the time of composing the zoo as we did earlier.&#160; </p>
<h3>Dealing with Metadata when MEF goes Lazy</h3>
<p>MEF allows you to export Metadata along with the types you export. For example, assume that you want to specify whether your exported animals eat meat or not, so that some one can decide what to give them as food. One way is to use the ExportMetaData attribute with your exported types, as shown below.</p>
<pre class="c#">   //Concrete animal 1
    [Export(typeof(IAnimal))]
    [ExportMetadata(&quot;EatMeat&quot;,true)]
    class Lion : IAnimal
    {
        public Lion() { Console.WriteLine(&quot;Grr.. Lion got created&quot;); }
        public void Eat() { Console.WriteLine(&quot;Grr.. Lion eating meat&quot;); }
    }

    //Concrete animal 2
    [Export(typeof(IAnimal))]
    [ExportMetadata(&quot;EatMeat&quot;, false)]
    class Rabbit : IAnimal
    {
        public Rabbit() { Console.WriteLine(&quot;Crrr.. Rabbit got created&quot;); }
        public void Eat() { Console.WriteLine(&quot;Crrr.. Rabbit eating carrot&quot;); }
    }</pre>
<p>That looks a bit clumsy, because of those strings. Right? A better way is to create your own custom Export attribute that includes the metadata information as well. That is pretty simple. The code below is equivalent to what we have just done above. You see that we are creating a custom export attribute named ExportAnimal. </p>
<pre class="c#">       //Our custom metadata attribute to exp animals
    [MetadataAttribute]
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    class ExportAnimal : ExportAttribute
    {
        //Pass the contract type to the base
        public ExportAnimal() : base(typeof(IAnimal)) { }
        //Additional metadata info
        public bool EatMeat { get; set; }
    }

    //Concrete animal 1
    [ExportAnimal(EatMeat=true)]
    class Lion : IAnimal
    {
        public Lion() { Console.WriteLine(&quot;Grr.. Lion got created&quot;); }
        public void Eat() { Console.WriteLine(&quot;Grr.. Lion eating meat&quot;); }
    }

    //Concrete animal 2
    [ExportAnimal(EatMeat = false)]
    class Rabbit : IAnimal
    {
        public Rabbit() { Console.WriteLine(&quot;Crrr.. Rabbit got created&quot;); }
        public void Eat() { Console.WriteLine(&quot;Crrr.. Rabbit eating carrot&quot;); }
    }</pre>
<p>Now let us come to the real question. How to import the metadata information in a Lazy way? Fortunately, MEF has an overload of Lazy, Lazy that supports importing Metadata information. So, all we need to do is create a metadata import interface that matches our export definition, and use it. Like this. </p>
<pre class="c#">   //An interface to import animal metadata
   //This should match the metadata we've in our custom export definition
    public interface IAnimalMetadata
    {
        bool EatMeat { get; }
    }

    //Our zoo
    class Zoo
    {
        //Directly import to Lazy&lt;IAnimal,IAnimalMetadata&gt;
        [ImportMany(typeof(IAnimal))]
        public IEnumerable&lt;Lazy&lt;IAnimal, IAnimalMetadata&gt;&gt; Animals { get; set; }
    }</pre>
<p>So, here is the final piece that includes the above fragments. You can see that we are exporting our animals using a custom export attribute, and importing them in a lazy way along with the metadata. Then, Have a look at the Main method. You&#8217;ll find that we are using the metadata to feed only the animals that eat meat. </p>
<p>In other words, the Lazy implementation provides you the luxury of initializing only the animals that you want to feed, at the time of feeding them &#8211; and not all the animals. </p>
<pre class="c#">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;

namespace MefLazy
{

    #region Contracts

    //Abstract animal interface
    interface IAnimal { void Eat(); }

    #endregion

    #region Export Related

    //Our custom metadata attribute to exp animals
    [MetadataAttribute]
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    class ExportAnimal : ExportAttribute
    {
        //Pass the contract type to the base
        public ExportAnimal() : base(typeof(IAnimal)) { }
        //Additional metadata info
        public bool EatMeat { get; set; }
    }

    //Concrete animal 1
    [ExportAnimal(EatMeat = true)]
    class Lion : IAnimal
    {
        public Lion() { Console.WriteLine(&quot;Grr.. Lion got created&quot;); }
        public void Eat() { Console.WriteLine(&quot;Grr.. Lion eating meat&quot;); }
    }

    //Concrete animal 2
    [ExportAnimal(EatMeat = false)]
    class Rabbit : IAnimal
    {
        public Rabbit() { Console.WriteLine(&quot;Crrr.. Rabbit got created&quot;); }
        public void Eat() { Console.WriteLine(&quot;Crrr.. Rabbit eating carrot&quot;); }
    }

    #endregion

    #region Import Related

    //An interface to import animal metadata
    public interface IAnimalMetadata
    {
        bool EatMeat { get; }
    }

    //Our zoo
    class Zoo
    {
        //Directly import to Lazy&lt;IAnimal,IAnimalMetadata&gt;
        [ImportMany(typeof(IAnimal))]
        public IEnumerable&lt;Lazy&lt;IAnimal, IAnimalMetadata&gt;&gt; Animals { get; set; }
    }

    #endregion

    #region Main

    //Let us construct our zoo and animals
    class Program
    {
        static void Main(string[] args)
        {
            //Let us create a catalog and a container
            var catalog = new AssemblyCatalog(typeof(Program).Assembly);
            var container = new CompositionContainer(catalog);

            //Compose the zoo.
            var zoo = new Zoo();
            container.ComposeParts(zoo);

            //An instance will be created only when you access it
            //Use the Value property of the Lazy object to initialize and access the actual value
            //Let us feed only animals eating meat
            foreach (var animal in zoo.Animals)
                if (animal.Metadata.EatMeat)
                    animal.Value.Eat();
        }
    }

    #endregion
}</pre>
<h3>Conclusion</h3>
<p>I encourage you to apply these concepts to more practical scenarios. Like, instead of a Zoo, think about a RuleProcessor that runs a set of rules on a business object &#8211; and instead of an Animal, think about a Rule that can validate or process the business object. I’ll give some more practical examples pretty soon <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . For now, the objective was to introduce Lazy concepts and MEF, and I hope you enjoyed the read. And you can download the final version of the code from the above link. Keep in touch, <a href="http://twitter.com/amazedsaint" target="_blank">Follow me on twitter</a></p>
<p>Also, read my last post <a href="http://amazedsaint.blogspot.com/2010/05/4-net-40-libraries-you-should-know.html" target="_blank">4 .NET 4.0 Libraries You should know about</a></p>
<p>Happy Coding!!</p>
<div class="wlWriterHeaderFooter" style="margin:0;padding:0;">
<div class="shoutIt"><a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http%3a%2f%2famazedsaint.blogspot.com%2f2010%2f06%2fmef-or-managed-extensibility-framework.html&amp;title=MEF+or+Managed+Extensibility+Framework+and+Lazy%3cT%3e+%e2%80%93+Being+Lazy+with+MEF%2c+Custom+Export+Attributes+etc"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http://amazedsaint.blogspot.com/2010/06/mef-or-managed-extensibility-framework.html" /></a></div>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/amazedsaint.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/amazedsaint.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/amazedsaint.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/amazedsaint.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/amazedsaint.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/amazedsaint.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/amazedsaint.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/amazedsaint.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/amazedsaint.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/amazedsaint.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/amazedsaint.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/amazedsaint.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/amazedsaint.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/amazedsaint.wordpress.com/268/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=268&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://amazedsaint.wordpress.com/2010/06/04/mef-or-managed-extensibility-framework-and-lazyt-%e2%80%93-being-lazy-with-mef-custom-export-attributes-etc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da8002b8d2a0051531f0ffc4213af039?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">amazedsaint</media:title>
		</media:content>

		<media:content url="http://lh3.ggpht.com/__Mw4iY-4nuY/TAit59JflAI/AAAAAAAAA1E/LuHoyeFXjnM/image_thumb%5B10%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh4.ggpht.com/__Mw4iY-4nuY/TAit9K7T59I/AAAAAAAAA1M/5zYtRObZT4c/image_thumb2.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh3.ggpht.com/__Mw4iY-4nuY/TAit_p40DEI/AAAAAAAAA1U/VpqqPTarq00/image_thumb%5B3%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://dotnetshoutout.com/image.axd?url=http://amazedsaint.blogspot.com/2010/06/mef-or-managed-extensibility-framework.html" medium="image">
			<media:title type="html">Shout it</media:title>
		</media:content>
	</item>
		<item>
		<title>4 .NET 4.0 Libraries You *Should* Know Better – MEF, Reactive, Tasks and Dynamic</title>
		<link>http://amazedsaint.wordpress.com/2010/05/26/4-net-4-0-libraries-you-should-know-better-%e2%80%93-mef-reactive-tasks-and-dynamic/</link>
		<comments>http://amazedsaint.wordpress.com/2010/05/26/4-net-4-0-libraries-you-should-know-better-%e2%80%93-mef-reactive-tasks-and-dynamic/#comments</comments>
		<pubDate>Wed, 26 May 2010 15:49:00 +0000</pubDate>
		<dc:creator>amazedsaint</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[.NET 4.0]]></category>
		<category><![CDATA[VS2010]]></category>

		<guid isPermaLink="false">http://amazedsaint.wordpress.com/2010/05/26/4-net-4-0-libraries-you-should-know-better-%e2%80%93-mef-reactive-tasks-and-dynamic</guid>
		<description><![CDATA[In this post, I’ll consolidate few posts on four .NET libraries/frameworks, that’ll help you write better apps MEF or Managed Extensibility Framework &#8211; System.ComponentModel.Composition MEF or Managed Extensibility Framework is cool. Firstly, it allows you to decouple your components pretty easily. Secondly, it supports various component discovery scenarios, and enables you to write better frameworks. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=267&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://lh6.ggpht.com/__Mw4iY-4nuY/S_07549d4JI/AAAAAAAAA0w/wF5gDdeSx7g/s1600-h/image%5B4%5D.png"><img title="image" border="0" alt="image" align="right" src="http://lh6.ggpht.com/__Mw4iY-4nuY/S_077dx7rTI/AAAAAAAAA00/GjoXaGEHXgI/image_thumb%5B2%5D.png?imgmax=800" width="206" height="240" /></a>In this post, I’ll consolidate few posts on four .NET libraries/frameworks, that’ll help you write better apps<a href="http://lh6.ggpht.com/__Mw4iY-4nuY/S_07549d4JI/AAAAAAAAA0w/wF5gDdeSx7g/s1600-h/image%5B4%5D.png"></a> </p>
<p><strong>MEF or Managed Extensibility Framework &#8211; </strong><em>System.ComponentModel.Composition</em></p>
<p>MEF or Managed Extensibility Framework is cool. Firstly, it allows you to decouple your components pretty easily. Secondly, it supports various component discovery scenarios, and enables you to write better frameworks. </p>
<ul>
<li><a href="http://amazedsaint.blogspot.com/2009/11/mef-or-managed-extension-framework.html" target="_blank">An Introduction to MEF- Creating a Zoo And Animals</a> </li>
<li><a href="http://amazedsaint.blogspot.com/2010/06/mef-or-managed-extensibility-framework.html" target="_blank">MEF or Managed Extensibility Framework and Lazy&lt;T&gt; – Being Lazy with MEF, Export Attributes etc</a> </li>
</ul>
<p><strong>Reactive Extensions and LINQ To Events – </strong><em>System.Reactive</em></p>
<p>Reactive Extensions will soon become the de-facto for writing asynchronous code in a declarative manner .NET Rx gives greater freedom to compose new events – you can create specific events out of general events</p>
<ul>
<li><a href="http://amazedsaint.blogspot.com/2010/02/what-is-linq-to-events-aka-rx-framework.html" target="_blank">What is LINQ To Events</a> </li>
<li><a href="http://amazedsaint.blogspot.com/2009/11/systemreactive-or-net-reactive.html" target="_blank">Concepts And First Look</a> </li>
<li><a href="http://amazedsaint.blogspot.com/2009/11/linq-to-events-more-on-net-reactive.html" target="_blank">Linq To Events – A WPF Drawing Demo</a> </li>
<li><a href="http://amazedsaint.blogspot.com/2009/11/linq-to-events-generating-wrapper.html" target="_blank">A Text Template for generating GetEventName wrapper</a> </li>
</ul>
<p><strong>Parallel Extensions and Tasks</strong> – <em>System.Threading.Tasks</em></p>
<p>With those multi core processors everywhere, support for parallelism is an already implicit requirement for any new application. NET 4.0 framework provides a wealth of easy to use primitives and abstractions to enable developers to quickly write parallel programs, targeting multi core machines. </p>
<ul>
<li><a href="http://amazedsaint.blogspot.com/2010/05/tasks-1-2-3-parallel-extensions-in-net.html" target="_blank">An Introduction to Tasks in Parallel Extensions</a> </li>
</ul>
<p><strong>Dynamic Extensions</strong> – <em>System.Dynamic</em></p>
<p>C# 4.0 introduced dynamic capabilities (duck typing) capabilities. There are a number of scenarios where the dynamic features can really simplify things for you. For example, let us assume a Reflection based scenario where you load a type (from an external assembly or so) to invoke a member, or think about a dynamic fluent wrapper on top of XML or JSON.</p>
<ul>
<li><a href="http://amazedsaint.blogspot.com/2010/03/c-40-dynamic-keyword-for-dummies-under.html" target="_blank">An introduction to C# 4.0 dynamic keyword</a> </li>
<li><a href="http://amazedsaint.blogspot.com/2009/09/systemdynamicexpandoobject-similar.html" target="_blank">Understanding ExpandoObject in .NET 4.0</a> </li>
<li><a href="http://amazedsaint.blogspot.com/2010/02/introducing-elasticobject-for-net-40.html" target="_blank">A Dynamic Wrapper in .NET 4.0</a> </li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/amazedsaint.wordpress.com/267/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/amazedsaint.wordpress.com/267/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/amazedsaint.wordpress.com/267/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/amazedsaint.wordpress.com/267/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/amazedsaint.wordpress.com/267/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/amazedsaint.wordpress.com/267/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/amazedsaint.wordpress.com/267/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/amazedsaint.wordpress.com/267/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/amazedsaint.wordpress.com/267/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/amazedsaint.wordpress.com/267/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/amazedsaint.wordpress.com/267/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/amazedsaint.wordpress.com/267/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/amazedsaint.wordpress.com/267/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/amazedsaint.wordpress.com/267/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=267&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://amazedsaint.wordpress.com/2010/05/26/4-net-4-0-libraries-you-should-know-better-%e2%80%93-mef-reactive-tasks-and-dynamic/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da8002b8d2a0051531f0ffc4213af039?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">amazedsaint</media:title>
		</media:content>

		<media:content url="http://lh6.ggpht.com/__Mw4iY-4nuY/S_077dx7rTI/AAAAAAAAA00/GjoXaGEHXgI/image_thumb%5B2%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>An Extension Method to Dump Control Templates of WPF Controls</title>
		<link>http://amazedsaint.wordpress.com/2010/05/26/an-extension-method-to-dump-control-templates-of-wpf-controls/</link>
		<comments>http://amazedsaint.wordpress.com/2010/05/26/an-extension-method-to-dump-control-templates-of-wpf-controls/#comments</comments>
		<pubDate>Wed, 26 May 2010 12:53:00 +0000</pubDate>
		<dc:creator>amazedsaint</dc:creator>
				<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://amazedsaint.wordpress.com/2010/05/26/an-extension-method-to-dump-control-templates-of-wpf-controls</guid>
		<description><![CDATA[In Blend, you have the ability to create a copy of the control template of a control, and edit it (Right Click – Edit Template – &#62; Edit A Copy). If you are interested, you can dump the Control template of any given WPF control pretty easily, from the source code as well. Here is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=266&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img align="right" src="http://images.pbidir.com/progicons/pencil.png" />In Blend, you have the ability to create a copy of the control template of a control, and edit it (Right Click – Edit Template – &gt; Edit A Copy). If you are interested, you can dump the Control template of any given WPF control pretty easily, from the source code as well.</p>
<p>Here is a simple extension method to dump the control template of a WPF control.</p>
<pre class="c#">
 public static class ControlTemplateExtension
    {
         public static string DumpControlTemplate(this Control ctrl)
        {
            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Indent = true,
                NewLineOnAttributes = true
            };

            StringBuilder strbuild = new StringBuilder();
            XmlWriter xmlwrite = XmlWriter.Create(strbuild, settings);
            XamlWriter.Save(ctrl.Template, xmlwrite);
            return strbuild.ToString();
        }
	}
</pre>
<p>And now you can go ahead and dump your control templates, like this.</p>
<pre class="c#">

   //use your control name instead of mybutton
   var strXaml = this.myButton.DumpControlTemplate();
   //Do something with your control template
   Debug.WriteLine(strXaml);
</pre>
<div class="wlWriterHeaderFooter" style="margin:0;padding:0;">
<div class="shoutIt"><a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http%3a%2f%2famazedsaint.blogspot.com%2f2010%2f05%2fextension-method-to-dump-control.html&amp;title=An+Extension+Method+to+Dump+Control+Templates+of+WPF+Controls"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http://amazedsaint.blogspot.com/2010/05/extension-method-to-dump-control.html" /></a></div>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/amazedsaint.wordpress.com/266/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/amazedsaint.wordpress.com/266/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/amazedsaint.wordpress.com/266/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/amazedsaint.wordpress.com/266/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/amazedsaint.wordpress.com/266/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/amazedsaint.wordpress.com/266/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/amazedsaint.wordpress.com/266/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/amazedsaint.wordpress.com/266/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/amazedsaint.wordpress.com/266/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/amazedsaint.wordpress.com/266/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/amazedsaint.wordpress.com/266/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/amazedsaint.wordpress.com/266/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/amazedsaint.wordpress.com/266/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/amazedsaint.wordpress.com/266/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=266&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://amazedsaint.wordpress.com/2010/05/26/an-extension-method-to-dump-control-templates-of-wpf-controls/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da8002b8d2a0051531f0ffc4213af039?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">amazedsaint</media:title>
		</media:content>

		<media:content url="http://images.pbidir.com/progicons/pencil.png" medium="image" />

		<media:content url="http://dotnetshoutout.com/image.axd?url=http://amazedsaint.blogspot.com/2010/05/extension-method-to-dump-control.html" medium="image">
			<media:title type="html">Shout it</media:title>
		</media:content>
	</item>
		<item>
		<title>C# 4.0 AccessPrivateWrapper – Instantiate and Access Private/Internal Classes and Members via dynamic + reflection</title>
		<link>http://amazedsaint.wordpress.com/2010/05/23/c-4-0-accessprivatewrapper-%e2%80%93-instantiate-and-access-privateinternal-classes-and-members-via-dynamic-reflection/</link>
		<comments>http://amazedsaint.wordpress.com/2010/05/23/c-4-0-accessprivatewrapper-%e2%80%93-instantiate-and-access-privateinternal-classes-and-members-via-dynamic-reflection/#comments</comments>
		<pubDate>Sun, 23 May 2010 12:44:00 +0000</pubDate>
		<dc:creator>amazedsaint</dc:creator>
				<category><![CDATA[.NET 4.0]]></category>
		<category><![CDATA[CSharp]]></category>

		<guid isPermaLink="false">http://amazedsaint.wordpress.com/2010/05/23/c-4-0-accessprivatewrapper-%e2%80%93-instantiate-and-access-privateinternal-classes-and-members-via-dynamic-reflection</guid>
		<description><![CDATA[[+] Download Related Source code Frankly, intrusion in to the private space of others is not so great. Mostly, you’ll get a kick in your ass, but at times, if you are lucky and if you are really smart, you’ll end up finding something really cool (Bond, James Bond). For me, at times, when doing [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=265&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>[+] <a href="http://amazedsaint.net/AccessPrivateWrapper.zip" target="_blank">Download Related Source code</a></p>
<p><img title="I love to see private things" border="0" alt="I love to see private things" align="right" src="http://www.clipartheaven.com/clipart/people/cartoons_(a_-_l)/keyhole.gif" width="190" height="240" />Frankly, intrusion in to the private space of others is not so great. Mostly, you’ll get a kick in your ass, but at times, if you are lucky and if you are really smart, you’ll end up finding something really cool (Bond, James Bond). </p>
<p>For me, at times, when doing some hacks/exploration of compiled or third party assemblies, I end up wanting to initialize a private class or a class with a private or internal constructor. Or, at times, when dealing with pre-compiled legacy libraries that I can’t change &#8211; I want to write a couple of tests against a private method to understand how it works.&#160; I remember going through the source code of TFS power toys or so some time back &#8211; and I found that those guys are bringing up a lot of goodness by unearthing some private classes in the TFS library.</p>
<p>Still, I should warn you.</p>
<blockquote><p><strong>Warning (assume that this is in red):</strong> Private types, internals and private members are so because of some reason, and often you don’t want to mess with them directly. And if you do, chances are that you’ll break later, because there is no guarantee that the guys who created those assemblies will keep the private/internal implementations as such. </p>
</blockquote>
<p>If you still don’t mind breaking the rules so that you can un earth some hidden potential against all the danger warnings &#8211; here is a quick wrapper class that’ll make the job easy using C# 4.0 dynamic features and reflection.&#160; And more than that, this is a good learning point to see how you can use reflection to initialize private types, invoke private/internal constructors, get/set private properties, invoke private methods etc. </p>
<p><strong>1 – What we are talking about</strong></p>
<p>To explain further what we’ll achieve, consider this simple example.</p>
<pre class="c#">
class Program
    {
        static void Main(string[] args)
        {
            //Note that the type of 'wrapper' is dynamic
            dynamic wrapper =  new AccessPrivateWrapper(new ClassWithPrivateMembers()) ;

            //Let us access the private members
            wrapper.somePrivateField = &quot;Field Val&quot;;
            wrapper.SomePrivateProperty = &quot;Property Val&quot;;
            wrapper.DumpValues();

            Console.ReadLine();
        }

        class ClassWithPrivateMembers
        {
            private string somePrivateField;
            private string SomePrivateProperty { get; set; }

            private void DumpValues()
            {
                Console.WriteLine(&quot;Look ma, I'm accessing private members. Prop = &quot;
                    + SomePrivateProperty + &quot;, Fld=&quot; + somePrivateField);
            }

        }
    }</pre>
<p>And if you run that, you’ll find that the dynamic wrapper is correctly setting the the private field and property values, and then&#160; invoking a private method in the class (<em>DumpValues</em> method), to print the result.</p>
<p><a href="http://lh3.ggpht.com/__Mw4iY-4nuY/S_kcLphLsHI/AAAAAAAAA0o/IV-t4czeR3g/s1600-h/image%5B4%5D.png"><img title="image" border="0" alt="image" src="http://lh6.ggpht.com/__Mw4iY-4nuY/S_kcMiRyUBI/AAAAAAAAA0s/-nDW0k2lul0/image_thumb%5B2%5D.png?imgmax=800" width="388" height="117" /></a> </p>
<p>No, we are not yet happy. What about accessing private members in private classes in other assemblies? All right, you can use the FromType method of AccessPrivateWrapper to initialize a private/internal class in a different assembly &#8211; and you can initilize the class, even if it&#8217;s constructor is internal or private. Assume that you have a class named &#8216;ClassWithPrivateConstructor&#8217; in an assembly, and it is having a private constructor. And you want to create an instance of that, and to invoke some private members inside. This is what you can do. </p>
<pre class="c#">
            //Note that the wrapper is dynamic
            dynamic wrapper = AccessPrivateWrapper.FromType
                (typeof(SomeKnownClass).Assembly,&quot;ClassWithPrivateConstructor&quot;);

            //Access the private members
            wrapper.PrivateMethodInPrivateClass();</pre>
<p><strong>2 – What the heck is AccessPrivateWrapper</strong></p>
<p>If you are wondering what exactly is AccessPrivateWrapper – it is a simple class we inherited from the System.Dynamic.DynamicObject class. </p>
<p>But before that If the keyword ‘dynamic’s not not familiar to you, I really suggest you to read this article I wrote earlier &#8211; <a href="http://amazedsaint.blogspot.com/2010/03/c-40-dynamic-keyword-for-dummies-under.html" target="_blank">C# 4.0 dynamic keyword – Under the hood</a></p>
<p>Coming back to DynamicObject &#8211; In dynamic languages like Ruby, there is an interesting feature called method_missing. Method missing is where your method request will end if the method you called cannot be found. </p>
<p>In .NET 4.0, now you can bring in the same feature, by inheriting your object from the DynamicObject class. What this means is, you&#8217;ll get notified when a method/property is invoked/accessed on your object. The DynamicObject class has a few cool methods for you to override. For now, we are only interested in these members: </p>
<ul>
<li>TryInvokeMember &#8211; Provides the implementation of calling a member. </li>
<li>TrySetMember &#8211; Provides the implementation of setting a member. </li>
<li>TryGetMember &#8211; Provides the implementation of getting a member. </li>
</ul>
<p>So, we are inheriting our AccessPrivateWrapper from the DynamicObject class, and overriding these methods to access private and public methods, properties and fields via reflection (I hope you know the fact that via reflection, you can invoke, set and get the values of even private and internal members).</p>
<p>Have a look at the implementation of AccessPrivateWrapper</p>
<pre class="c#">/// &lt;summary&gt;
    /// A 10 minute wrapper to access private members, havn't tested in detail.
    /// Use under your own risk - amazedsaint@gmail.com
    /// &lt;/summary&gt;
    public class AccessPrivateWrapper : DynamicObject
    {

        /// &lt;summary&gt;
        /// The object we are going to wrap
        /// &lt;/summary&gt;
        object _wrapped;

        /// &lt;summary&gt;
        /// Specify the flags for accessing members
        /// &lt;/summary&gt;
        static BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance
            | BindingFlags.Static | BindingFlags.Public;

        /// &lt;summary&gt;
        /// Create a simple private wrapper
        /// &lt;/summary&gt;
        public AccessPrivateWrapper(object o)
        {
            _wrapped = o;
        }

        /// &lt;summary&gt;
        /// Create an instance via the constructor matching the args
        /// &lt;/summary&gt;
        public static dynamic FromType(Assembly asm,string type,params object[] args)
        {

            var allt = asm.GetTypes();
            var t=allt.First(item=&gt;item.Name==type);

            var types=from a in args
                      select a.GetType();

            //Gets the constructor matching the specified set of args
            var ctor = t.GetConstructor(flags, null, types.ToArray(), null);

            if (ctor != null)
            {
                var instance = ctor.Invoke(args);
                return new AccessPrivateWrapper(instance);
            }

            return null;
        }

        /// &lt;summary&gt;
        /// Try invoking a method
        /// &lt;/summary&gt;
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            var types=from a in args
                      select a.GetType();

            var method = _wrapped.GetType().GetMethod
                (binder.Name,flags, null, types.ToArray(), null);

            if (method == null)
                return base.TryInvokeMember(binder, args, out result);
            else
            {
                result=method.Invoke(_wrapped, args);
                return true;
            }
        }

        /// &lt;summary&gt;
        /// Tries to get a property or field with the given name
        /// &lt;/summary&gt;
        public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
        {
            //Try getting a property of that name
            var prop = _wrapped.GetType().GetProperty(binder.Name,flags);

            if (prop == null)
            {
                //Try getting a field of that name
                var fld = _wrapped.GetType().GetField(binder.Name, flags);
                if (fld != null)
                {
                    result = fld.GetValue(_wrapped);
                    return true;
                }
                else
                    return base.TryGetMember(binder, out result);
            }
            else
            {
                result = prop.GetValue(_wrapped, null);
                return true;
            }
        }

        /// &lt;summary&gt;
        /// Tries to set a property or field with the given name
        /// &lt;/summary&gt;
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            var prop = _wrapped.GetType().GetProperty(binder.Name, flags);
            if (prop == null)
            {
                var fld = _wrapped.GetType().GetField(binder.Name, flags);
                if (fld != null)
                {
                    fld.SetValue(_wrapped,value);
                    return true;
                }
                else
                    return base.TrySetMember(binder, value);
            }
            else
            {
                prop.SetValue(_wrapped, value, null);
                return true;
            }
        }

    }</pre>
<p>That looks simple, isn’t it? To detail that a bit, when ever user sets or gets a property or field on our dynamic object, the TrySetMember or TryGetMember will get called &#8211; and from there onwards, we use reflection to do the job of setting or getting the property or field value, regardless whether it is private or public. If a property of the given name doesn’t exist we’ll try to find a field of the given name to do the get or set operation.</p>
<p>Similarly, TryInvokeMethod will get fired when the user tries to invoke a method via our dynamic wrapper. We fetch the method matching the type of arguments, to obtain the correct overload, and then do the job via reflection. Make sure you download the code from the above link, and debug through a bit.</p>
<p>Also, pay some special attention to the FromType method that we used earlier. Basically, it’ll find the type to create an instance of, and then will find the constructor to invoke, based on the given arguments.</p>
<p><strong>More Thoughts</strong></p>
<p>Now, what about Unit testing your private members? Ever wanted to do that? That is not a common scenario, but at times, as I mentioned earlier, you might be dealing with a legacy system and you want to write a couple of tests against some of the private methods. Oh yes, you can use the AccessPrivateWrapper to do that. </p>
<p>Note that the above implementation don’t work with libraries that are obfuscated, because we are relying on reflection.</p>
<p>Also, the above implementation won’t access inherited private or internal members. That is pretty simple to implement, but that is an exercise for you <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p><strong>Conclusion</strong></p>
<p>A related tip: You can use <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx" target="_blank">InternalsVisibleTo</a> attribute to grant access to the internal members of the target assembly to your caller assembly, if you’ve access to both the assemblies. This is useful, especially when you do unit testing.</p>
<p>Also, check out my other C# 4.0 dynamic tricks</p>
<ul>
<li><a href="http://amazedsaint.blogspot.com/2009/09/systemdynamicexpandoobject-similar.html" target="_blank">ExpandoObject in C# 4.0 – Inside look</a> </li>
<li><a href="http://amazedsaint.blogspot.com/2010/02/introducing-elasticobject-for-net-40.html" target="_blank">Introducing ElasticObject in C# 4.0</a> </li>
</ul>
<p>&#160;</p>
<p>Happy Coding!!</p>
<div class="wlWriterHeaderFooter" style="margin:0;padding:0;">
<div class="shoutIt"><a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http%3a%2f%2famazedsaint.blogspot.com%2f2010%2f05%2faccessprivatewrapper-c-40-dynamic.html&amp;title=C%23+4.0+AccessPrivateWrapper+%e2%80%93+Instantiate+and+Access+Private%2fInternal+Classes+and+Members+via+dynamic+%2b+reflection"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http://amazedsaint.blogspot.com/2010/05/accessprivatewrapper-c-40-dynamic.html" /></a></div>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/amazedsaint.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/amazedsaint.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/amazedsaint.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/amazedsaint.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/amazedsaint.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/amazedsaint.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/amazedsaint.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/amazedsaint.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/amazedsaint.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/amazedsaint.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/amazedsaint.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/amazedsaint.wordpress.com/265/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/amazedsaint.wordpress.com/265/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/amazedsaint.wordpress.com/265/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=265&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://amazedsaint.wordpress.com/2010/05/23/c-4-0-accessprivatewrapper-%e2%80%93-instantiate-and-access-privateinternal-classes-and-members-via-dynamic-reflection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da8002b8d2a0051531f0ffc4213af039?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">amazedsaint</media:title>
		</media:content>

		<media:content url="http://www.clipartheaven.com/clipart/people/cartoons_(a_-_l)/keyhole.gif" medium="image">
			<media:title type="html">I love to see private things</media:title>
		</media:content>

		<media:content url="http://lh6.ggpht.com/__Mw4iY-4nuY/S_kcMiRyUBI/AAAAAAAAA0s/-nDW0k2lul0/image_thumb%5B2%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://dotnetshoutout.com/image.axd?url=http://amazedsaint.blogspot.com/2010/05/accessprivatewrapper-c-40-dynamic.html" medium="image">
			<media:title type="html">Shout it</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating a Standalone, offline Installer for installing Silverlight runtime + your XAP application</title>
		<link>http://amazedsaint.wordpress.com/2010/05/13/creating-a-standalone-offline-installer-for-installing-silverlight-runtime-your-xap-application/</link>
		<comments>http://amazedsaint.wordpress.com/2010/05/13/creating-a-standalone-offline-installer-for-installing-silverlight-runtime-your-xap-application/#comments</comments>
		<pubDate>Thu, 13 May 2010 11:30:00 +0000</pubDate>
		<dc:creator>amazedsaint</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://amazedsaint.wordpress.com/2010/05/13/creating-a-standalone-offline-installer-for-installing-silverlight-runtime-your-xap-application</guid>
		<description><![CDATA[Related Downloads Silverlight Nerd Dinner Client Offline Installer Files Required To Create the Installer (NSIS Script, XAP File etc) NSIS Installer to compile the above Script What? Recently a friend asked me to help him create an ‘installer’ to pack and distribute the Silverlight game he recently developed. He wanted to distribute his game via [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=264&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Related Downloads</h3>
<ul>
<li><a href="http://amazedsaint.net/nerddinner/DesktopInstaller.zip" target="_blank">Silverlight Nerd Dinner Client Offline Installer</a> </li>
<li><a href="http://amazedsaint.net/nerddinner/InstallerFiles.zip" target="_blank">Files Required To Create the Installer (NSIS Script, XAP File etc)</a> </li>
<li><a href="http://nsis.sourceforge.net/Main_Page" target="_blank">NSIS Installer to compile the above Script</a> </li>
</ul>
<h3>What?</h3>
<p>Recently a friend asked me to help him create an ‘installer’ to pack and distribute the Silverlight game he recently developed. He wanted to distribute his game via software download websites (like download.cnet.com), and via medias like CD/DVD. </p>
<p>In fact, that is pretty easy (technically) &#8211; and this post is about creating and deploying Silverlight Runtime + Your Silverlight application (Xap file) using your very own custom, standalone, offline installer with out getting a browser installed &#8211; instead of the user <a href="http://timheuer.com/blog/archive/2009/08/12/silverlight-out-of-browser-force-install-pattern.aspx" target="_blank">installing your Silverlight application Out Of Browser via the web browser</a>. </p>
<p>Alright. In this post, we’ll see how to build a standalone installer for <a href="http://amazedsaint.blogspot.com/2010/04/creating-silverlight-client-for.html" target="_blank">Silverlight Nerd Dinner Client</a> that I built some time earlier (It is a Silverlight client for Scott’s <a href="http://nerddinner.com" target="_blank">Nerddinner.com</a> to enable nerds to ‘eat in packs’). The installer will start with a Splash screen as well <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .&#160; </p>
<p><a href="http://lh3.ggpht.com/__Mw4iY-4nuY/S-vWvQMW8pI/AAAAAAAAAzk/se_gpayIobA/s1600-h/image%5B31%5D.png"><img title="image" border="0" alt="image" src="http://lh3.ggpht.com/__Mw4iY-4nuY/S-vWzFbHVoI/AAAAAAAAAzo/Gn2TktEZy7c/image_thumb%5B20%5D.png?imgmax=800" width="660" height="380" /></a></p>
<p>About License related issues, see the Appendix towards the end of this post. Also, the scenario I’m discussing is limited to creating installers for Windows machines alone <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . </p>
<h3>Why?</h3>
<p>I can already hear you thinking, “why this is required”? Think about this &#8211; You created a Nice game or a Cool gadget in Silverlight. Now you want to create a standalone Installer &#8211; so that you can push the same to your potential users via various means. Like, users may download your installer via CNET like software websites &#8211; or you may distribute your installer via CD/DVD media etc. In this way, you can push your Silverlight apps to the masses- instead of waiting for them to come to your website and discover it – You got it, that is what we are talking about <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p>So, in short, I think Silverlight can be used a platform of choice for building light weight desktop applications, mainly applications like utility tools, light weight games etc.</p>
<p>I feel there are a good number of use cases where you want to do this.</p>
<ul>
<li>You can write and deploy tiny apps and gadgets &#8211; with out worrying about the presence of/version of the .NET runtime in user’s machine. </li>
<li>You can maintain the same code base for your web and desktop versions if the scenario suits. </li>
<li>You can contribute towards increasing the number of boxes where Silverlight exists <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . More people with Silverlight = a brighter web <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  </li>
</ul>
<p>And yes, if you are doubtful about what you can really do from a Silverlight application that is running in an elevated trust, out of browser mode, check out this <a href="http://justinangel.net/CuttingEdgeSilverlight4ComFeatures" target="_blank">epic post from Justin Angel</a> where he demonstrates how to do all whacky things with Silverlight + COM, including accessing Win 7 APIs, Accessing Scanners and printers, Adding your OOB application to windows startup etc. He rocks.</p>
<h3>How?</h3>
<p>So, let us see this in detail &#8211; how to create a stand alone installer to install Silverlight Runtime + Your Silverlight Application (i.e, the Xap file). These steps detail how I created my installer for Silverlight <a href="http://amazedsaint.blogspot.com/2010/04/creating-silverlight-client-for.html" target="_blank">Nerd Dinner client.</a></p>
<p><strong>1 – Preparing the required files</strong></p>
<p>For this example, I’m going to use <a href="http://nsis.sourceforge.net/Main_Page" target="_blank">Nullsoft NSIS Installer</a> to roll down the custom installer. NSIS is a simple windows installer from the WinAmp guys, and you can find ton of information <a href="http://nsis.sourceforge.net/Main_Page" target="_blank">here on that</a>. You can write a custom NSIS script, and make a standalone installer executable out of that. </p>
<p>If you <a href="http://amazedsaint.net/nerddinner/InstallerFiles.zip" target="_blank">download the example package</a>, you’ll find</p>
<ul>
<li>The NSIS script to create the installer from. </li>
<li>The Silverlight runtime installer (Silverlight.exe) – You should ensure you have the latest <a href="http://go.microsoft.com/fwlink/%3FLinkID%3D107362&amp;sa=U&amp;ei=56XnS-_pDYW2rAeQ-JHwAw&amp;ct=res&amp;ved=0CBUQFjAA&amp;cd=1&amp;sig2=_fgv-St1vvH4XhVw8LosjQ&amp;usg=AFQjCNH6l0b-elAdCZUWfZ57bkRejJgxmQ" target="_blank">from here</a>. </li>
<li>Copy of your Silverlight Xap (that you are going to install in the user’s machine). </li>
<li>A license.txt file and splash.bmp file to show during the time of installation. </li>
</ul>
<p>Download and Extract the Required Files zip &#8211; and have a look at the files I have. I’ve a Nerddinner.nsi script (we’ll soon see what is inside that), the Silverlight.exe runtime installer, SilverlightNerdDinner.xap, a license file and a Splash screen for the installer.</p>
<p>&#160;</p>
<p><a href="http://lh3.ggpht.com/__Mw4iY-4nuY/S-vbf9_QmHI/AAAAAAAAAzs/FfezBfEg4vc/s1600-h/image4.png"><img title="image" border="0" alt="image" src="http://lh5.ggpht.com/__Mw4iY-4nuY/S-vbl0yiwiI/AAAAAAAAAzw/TLfyPq-8AYg/image_thumb2.png?imgmax=800" width="649" height="441" /></a>&#160;</p>
<p><strong>2 – What the installer should do</strong></p>
<p>Basically, we need our installer to</p>
<ul>
<li>Copy Silverlight.exe to the user’s machine and execute that in Silent mode to install the Silverlight runtime. </li>
<li>Use Sllanucher.exe to install our Xap in out of the browser mode (Sllauncher.exe will be installed by the above Silverlight runtime installer) – <a href="http://timheuer.com/blog/archive/2010/03/25/using-sllauncher-for-silent-install-silverlight-application.aspx" target="_blank">Tim already has a nice post on using sllauncher.exe</a> – I’ll also touch that a bit. </li>
</ul>
<p>The <a href="http://download.microsoft.com/download/7/8/d/78da8ec9-8801-42e5-89e5-3809386f1316/silverlight%2520deployment%2520guide.doc&amp;sa=U&amp;ei=5KfnS4fcComyrAfE7N2dBA&amp;ct=res&amp;ved=0CBoQFjAA&amp;cd=1&amp;sig2=j4j5HAbR9myCKq0gZ7ae7w&amp;usg=AFQjCNGN28TA8Prvb" target="_blank">Silverlight deployment guide</a> is a handy read regarding the supported command line arguments for Silverlight.exe and Sllauncher.exe, but here is the summary.</p>
<p>You can install the Silverlight runtime in quiet mode, using the following arguments.&#160; </p>
<pre>Silverlight.exe /q /doNotRequireDRMPrompt</pre>
<p>The &#8216;/q&#8217; switch will install the runtime in silent mode. Here is some excerpt from the Silverlight deployment manual version 4.0</p>
<blockquote>
<ul>
<li><strong><em>/q</em></strong> = quiet install or upgrade. This installs or upgrades Silverlight without seeing the GUI. When Silverlight is installed quietly, by default privacy related features such as DRM protected media playback and the Silverlight auto-update feature will be configured to prompt the user for permission on 1st use of the respective features. The Silverlight auto-update feature requires administrative rights so non-admin users will not be prompted. </li>
<li><strong><em>/doNotRequireDRMPrompt</em></strong> = turns off the 1st use prompt allowing content protected by Digital Rights Management (DRM) to play without requiring any end-user intervention. When Silverlight is installed quietly, DRM Playback is set to prompt on 1st use by default. </li>
<li><strong><em>/ignorewarnings</em></strong> = non-fatal warnings will not be reflected in the quiet installer return code but will instead return zero indicating success. </li>
<li><strong><em>/noupdate</em> </strong>= disables the Silverlight internal auto-updater. </li>
<li><strong><em>/qu</em></strong> = quiet uninstall. This uninstalls Silverlight without seeing the GUI. </li>
</ul>
</blockquote>
<p>The Silverlight runtime installer will install sllauncher.exe to the {PROGRAMFILES}\Microsoft Silverlight\sllauncher.exe path. So, after installing Silverlight runtime, we may use sllauncher.exe to ‘install’ our xap in Out of Browser mode, and to create the required short cuts</p>
<pre>sllauncher.exe
           /install:&quot;{LocalPathToXapFile}\Yourfile.xap&quot;
           /origin:&quot;{urltoxapfile}/Yourfile.xap&quot;
           /shortcut:desktop+startmenu</pre>
<p>You can see that Sllauncher.exe will accept the local path to the xap file, the url to the xap file and the shortcut options. Here is some excerpt from the Silverlight deployment manual about using sllauncher.exe to install XAP.</p>
<blockquote>
<p>Installation</p>
<ul>
<li><strong><em>/install:&quot;xapFile&quot;</em></strong> – where xapFile is the file name/file path to the .xap file., E.g. /install:&quot;c:\temp\sample.xap&quot; </li>
<li><em><strong>/origin:&quot;xapURI&quot;</strong> </em>– where xapURI is the URI where the .xap file would&#8217;ve come from if not installed at the commandline
<ul>
<li>e.g. /origin:&quot;<a href="http://example.com/sample.xap&quot;">http://example.com/sample.xap&quot;</a> .&#160; This URI will be used as the site of origin for security purposes. For example, for sandboxed applications, Silverlight networking requires a policy file check when making network requests to domains other than the site of origin.&#160; The origin also serves as a unique ID for the application.&#160; The xapURI must be an absolute URI not a relative URI, and must start with http:, https:, or file:. </li>
</ul>
</li>
<li><strong><em>/overwrite</em></strong> &#8212; (optional) Overwrites any previously installed .xap with that xapURI. </li>
</ul>
<p>Un installation</p>
<ul>
<li><strong><em>/uninstall</em></strong>&#160; – Uninstalls the application specified in /origin. This is the same /origin value that was used to install the app originally. </li>
<li><strong><em>/origin:&quot;xapURI&quot;</em></strong> – same as /origin for the install case </li>
</ul>
</blockquote>
<p><strong>3 – The NSIS Script</strong></p>
<p>So, now let us write a quick NSIS script to create an installer that performs these operations. Our script will look like this</p>
<pre>Name &quot;Nerd Dinner Desktop Installer&quot;
OutFile &quot;NerdDinnerDesktopInstaller.exe&quot;
InstallDir &quot;$PROGRAMFILES\NerdDinnerDesktop&quot;

XPStyle on

Function .onInit
	# the plugins dir is automatically deleted when the installer exits
	InitPluginsDir
	File /oname=$PLUGINSDIR\splash.bmp &quot;splash.bmp&quot;
	splash::show 1000 $PLUGINSDIR\splash
	Pop $0
FunctionEnd

Section
    SetOutPath &quot;$INSTDIR&quot;
    SetOverwrite ifnewer
    File &quot;Silverlight.exe&quot;
    ExecWait &quot;$INSTDIR\Silverlight.exe /q /doNotRequireDRMPrompt&quot;
    File &quot;SilverlightNerdDinner.xap&quot;
    ExecWait '&quot;$PROGRAMFILES\Microsoft Silverlight\sllauncher.exe&quot; /install:&quot;$INSTDIR\SilverlightNerdDinner.xap&quot; /origin:&quot;http://amazedsaint.net/nerddinner/clientbin/silverlightnerddinner2.xap&quot; /shortcut:desktop+startmenu'
SectionEnd</pre>
<p>Basically, the installer will </p>
<ol>
<li>Show a splash screen during initialization of the installer </li>
<li>Copy Silverlight.exe to the target folder, and execute it in quite mode </li>
<li>Copy our xap file to the target folder, and use sllauncher.exe to install the xap </li>
</ol>
<p><strong>4 – Creating the Installer</strong></p>
<p>Once you have <a href="http://nsis.sourceforge.net/Main_Page" target="_blank">NSIS</a> installed, you can simply right click on an NSIS file to ‘Compile’ it create an installer. </p>
<p><a href="http://lh5.ggpht.com/__Mw4iY-4nuY/S-vbnNM9rOI/AAAAAAAAAz0/zG_dpl0-Sw8/s1600-h/image%5B5%5D.png"><img title="image" border="0" alt="image" src="http://lh6.ggpht.com/__Mw4iY-4nuY/S-vbpDmeaZI/AAAAAAAAAz4/GrKRM8pwD7s/image_thumb%5B2%5D.png?imgmax=800" width="539" height="372" /></a> </p>
<p>You should see the MakeNSISW prompt, with a message that the installer is created. Our final installer (that contains Silverlight.exe runtime + XAP + Splash Screen image) is almost ~7 MB, and now you can distribute this the way you need, provided you have the permission from Microsoft to re-distribute Silverlight runtime.</p>
<p><a href="http://lh3.ggpht.com/__Mw4iY-4nuY/S-vbqZLmH4I/AAAAAAAAAz8/8mxDphsdj6U/s1600-h/image%5B10%5D.png"><img title="image" border="0" alt="image" src="http://lh6.ggpht.com/__Mw4iY-4nuY/S-vbsNC6WZI/AAAAAAAAA0A/038Uo7l6Fes/image_thumb%5B5%5D.png?imgmax=800" width="551" height="454" /></a> </p>
<p>The above installer will install your Silverlight application and will create the desktop and start menu short cuts. <a href="http://amazedsaint.net/nerddinner/DesktopInstaller.zip" target="_blank">Try the installer from here</a>, and you’ll see that it’ll get installed even in a machine with no Silverlight runtime already present.</p>
<p>When you create the installer from your own XAP file, make sure you have enabled Running your <a href="http://www.silverlightdev.net/?p=86" target="_blank">Silverlight Application out of browser</a>. Also, always make sure you’ve the latest version of Silverlight runtime installer, <em>Silverlight.exe</em> (Normally what ever you get from <a href="http://go.microsoft.com/fwlink/%3FLinkID%3D107362&amp;sa=U&amp;ei=56XnS-_pDYW2rAeQ-JHwAw&amp;ct=res&amp;ved=0CBUQFjAA&amp;cd=1&amp;sig2=_fgv-St1vvH4XhVw8LosjQ&amp;usg=AFQjCNH6l0b-elAdCZUWfZ57bkRejJgxmQ" target="_blank">this link</a> )</p>
<p>&#160;</p>
<h3>Appendix &#8211; Licensing Issues</h3>
<p>I asked Tim and Scott whether I can redistribute Silverlight runtime as part of my own custom installer. And this is the reply I got. There is a license available, but it depends on the situation. You should send your app details to Tim for the details <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Also, you might want to show the Silverlight license to the end users as part of your installer. I’m not pretty sure about this – the general recommendation is to fled Tim’s inbox.</p>
<p><a href="http://lh3.ggpht.com/__Mw4iY-4nuY/S-vbtgTRIoI/AAAAAAAAA0E/5mNzth1hios/s1600-h/image%5B15%5D.png"><img title="image" border="0" alt="image" src="http://lh3.ggpht.com/__Mw4iY-4nuY/S-vbvEJTO2I/AAAAAAAAA0I/cadQ_FsuMI0/image_thumb%5B8%5D.png?imgmax=800" width="707" height="187" /></a> </p>
<p>Having said that, I really think MS should encourage developers to re-distribute Silverlight runtime as part of their custom installers, because that can definitely contribute towards increasing the Silverlight runtime penetration.</p>
<div class="wlWriterHeaderFooter" style="margin:0;padding:0;">
<div class="shoutIt"><a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http%3a%2f%2famazedsaint.blogspot.com%2f2010%2f05%2fhow-to-create-offline-installer-no.html&amp;title=Creating+a+Standalone%2c+offline+Installer+for+installing+Silverlight+runtime+%2b+your+XAP+application"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http://amazedsaint.blogspot.com/2010/05/how-to-create-offline-installer-no.html" /></a></div>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/amazedsaint.wordpress.com/264/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/amazedsaint.wordpress.com/264/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/amazedsaint.wordpress.com/264/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/amazedsaint.wordpress.com/264/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/amazedsaint.wordpress.com/264/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/amazedsaint.wordpress.com/264/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/amazedsaint.wordpress.com/264/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/amazedsaint.wordpress.com/264/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/amazedsaint.wordpress.com/264/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/amazedsaint.wordpress.com/264/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/amazedsaint.wordpress.com/264/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/amazedsaint.wordpress.com/264/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/amazedsaint.wordpress.com/264/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/amazedsaint.wordpress.com/264/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=amazedsaint.wordpress.com&amp;blog=879534&amp;post=264&amp;subd=amazedsaint&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://amazedsaint.wordpress.com/2010/05/13/creating-a-standalone-offline-installer-for-installing-silverlight-runtime-your-xap-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/da8002b8d2a0051531f0ffc4213af039?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">amazedsaint</media:title>
		</media:content>

		<media:content url="http://lh3.ggpht.com/__Mw4iY-4nuY/S-vWzFbHVoI/AAAAAAAAAzo/Gn2TktEZy7c/image_thumb%5B20%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh5.ggpht.com/__Mw4iY-4nuY/S-vbl0yiwiI/AAAAAAAAAzw/TLfyPq-8AYg/image_thumb2.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh6.ggpht.com/__Mw4iY-4nuY/S-vbpDmeaZI/AAAAAAAAAz4/GrKRM8pwD7s/image_thumb%5B2%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh6.ggpht.com/__Mw4iY-4nuY/S-vbsNC6WZI/AAAAAAAAA0A/038Uo7l6Fes/image_thumb%5B5%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://lh3.ggpht.com/__Mw4iY-4nuY/S-vbvEJTO2I/AAAAAAAAA0I/cadQ_FsuMI0/image_thumb%5B8%5D.png?imgmax=800" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://dotnetshoutout.com/image.axd?url=http://amazedsaint.blogspot.com/2010/05/how-to-create-offline-installer-no.html" medium="image">
			<media:title type="html">Shout it</media:title>
		</media:content>
	</item>
	</channel>
</rss>
