<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>IDisposable Thoughts</title>
	
	<link>http://cprieto.com</link>
	<description>Honey... where's my coding t-shirt?</description>
	<lastBuildDate>Fri, 06 Apr 2012 03:35:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/IdisposableThoughts" /><feedburner:info uri="idisposablethoughts" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>HTML5 and Javascript is not a HTML5 Javascript application</title>
		<link>http://feedproxy.google.com/~r/IdisposableThoughts/~3/64zV1mZZAMg/</link>
		<comments>http://cprieto.com/2012/04/06/html5-and-javascript-is-not-a-html5-and-javascript-application/#comments</comments>
		<pubDate>Fri, 06 Apr 2012 03:31:33 +0000</pubDate>
		<dc:creator>cristian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[rant]]></category>

		<guid isPermaLink="false">http://cprieto.com/?p=796</guid>
		<description><![CDATA[Javascript and HTML5 is in everybody’s mouth nowadays, looks like everything is around them: Node.js is wonderful and made what others tried to achieve long time ago, frameworks like knockout.js or backbone.js taught us how to develop MVVM and MVC oriented applications using javascript, jQuery is your everyday tool, and even an major operating system [...]]]></description>
			<content:encoded><![CDATA[<p>Javascript and HTML5 is in everybody’s mouth nowadays, looks like everything is around them: <a href="http://nodejs.org/">Node.js</a> is wonderful and made what others tried to achieve long time ago, frameworks like <a href="http://knockoutjs.com/">knockout.js</a> or <a href="http://documentcloud.github.com/backbone/">backbone.js</a> taught us how to develop <a href="http://en.wikipedia.org/wiki/MVVM">MVVM</a> and <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a> oriented applications using javascript, <a href="http://jquery.com">jQuery</a> is your everyday tool, and even an major operating system (<a href="http://en.wikipedia.org/wiki/Windows_8">Windows 8</a> ) announced their support for native HTML5 and Javascript to develop desktop touch friendly&nbsp;applications.</p>
<p>Javascript has emerged from a mere hacking language as a now mainstream language, now it’s common to see job offers for “javascript frontend (or UI) developers” and almost every website I’ve been involved into requires a lot of interaction using your browser… So, what’s the&nbsp;problem?</p>
<p>The problem is simple, even when we have new frameworks, new IDE’s, new paradigms for HTML and javascript applications I see that most developers still treating javascript as a hacking language, I mean, throwing lines and lines of code into the problem, without any separation or patterns or anything else, they still writing rich interactive application as HTML plus javascript, not as a HTML and javascript&nbsp;application.</p>
<p>A good application is more than code and UI, a good application should follow DRY, KISS, SOLID or whatever other acronym do you want to throw at them. HTML and Javascript applications are more than just HTML with&nbsp;Javascript.</p>
<p>Want to do something better? don’t tread <a href="http://en.wikipedia.org/wiki/Javascript">Javascript</a> as a hacking language.&nbsp;Period.</p>
<img src="http://feeds.feedburner.com/~r/IdisposableThoughts/~4/64zV1mZZAMg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://cprieto.com/2012/04/06/html5-and-javascript-is-not-a-html5-and-javascript-application/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://cprieto.com/2012/04/06/html5-and-javascript-is-not-a-html5-and-javascript-application/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=html5-and-javascript-is-not-a-html5-and-javascript-application</feedburner:origLink></item>
		<item>
		<title>Provide unit test is not a guarantee of unit testing</title>
		<link>http://feedproxy.google.com/~r/IdisposableThoughts/~3/rojF0YfRwHo/</link>
		<comments>http://cprieto.com/2012/04/05/provide-unit-test-is-not-a-guarantee-of-unit-testing/#comments</comments>
		<pubDate>Thu, 05 Apr 2012 12:50:32 +0000</pubDate>
		<dc:creator>cristian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[mstest]]></category>
		<category><![CDATA[sdk]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[visual studio]]></category>
		<category><![CDATA[vsx]]></category>
		<category><![CDATA[xunit]]></category>

		<guid isPermaLink="false">http://cprieto.com/?p=793</guid>
		<description><![CDATA[In the last years we’ve been hearing a lot about unit testing, so much that now is in the mouth of almost every big or small software company. It’s even so common that many are so brave to say: “If you don’t provide unit tests for your code, then it’s&#160;worthless”. Well, I would be even [...]]]></description>
			<content:encoded><![CDATA[<p>In the last years we’ve been hearing a lot about unit testing, so much that now is in the mouth of almost every big or small software company. It’s even so common that many are so brave to say: “If you don’t provide unit tests for your code, then it’s&nbsp;worthless”.</p>
<p>Well, I would be even more brave and say: “If you provide unit tests with your code, even your templates, those test should be worth a&nbsp;penny”.</p>
<p>I found this wonderful piece of code today from a project&nbsp;template:</p>
<pre class="brush: csharp">[TestClass]
public class PackageTest {
    [TestMethod]
    public void CreateInstance() {
        var package = new Walkthrough_01Package();
    }

    [TestMethod]
    public void IsIVsPackage() {
        var package = new Walkthrough_01Package();
        Assert.IsNotNull(package, "The object does not implement IVsPackage");
    }

    [TestMethod]
    public void SetSite() {
        // Create the package
        IVsPackage package = new Walkthrough_01Package();
        Assert.IsNotNull(package, "The object does not implement IVsPackage");

        // Create a basic service provider
        OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices();

        // Site the package
        Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK");

        // Unsite the package
        Assert.AreEqual(0, package.SetSite(null), "SetSite(null) did not return S_OK");
    }
}
</pre>
<p>Ok, let’s just rewrite this test for the sake of just see how would it look&nbsp;like:</p>
<pre class="brush: csharp">public class SamplePackageFacts {
    private readonly IVsPackage _package = new Walkthrough_01Package();

    [Fact]
    public void PackageCanCorrectlySetSiteFromProvider() {
        var site = OleServiceProvider.CreateOleServiceProviderWithBasicServices();
        var answer = _package.SetSite(site);
        Assert.Equal(VSConstants.S_OK, answer);
    }

    [Fact]
    public void PackageCanCorrectlySetNullProvider() {
        var answer = _package.SetSite(null);
        Assert.Equal(VSConstants.S_OK, answer);
    }
}
</pre>
<p>Can you spot the problem? do you see any value at all in the original three tests&nbsp;methods?</p>
<p><strong>NOTE:</strong> I used <a href="http://xunit.codeplex.com/">xUnit</a> just because I like it. It’s not a problem inherited from using the test framework but from the way of look at what is a unit test, you could do exactly the same using&nbsp;MSTest.</p>
<img src="http://feeds.feedburner.com/~r/IdisposableThoughts/~4/rojF0YfRwHo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://cprieto.com/2012/04/05/provide-unit-test-is-not-a-guarantee-of-unit-testing/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://cprieto.com/2012/04/05/provide-unit-test-is-not-a-guarantee-of-unit-testing/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=provide-unit-test-is-not-a-guarantee-of-unit-testing</feedburner:origLink></item>
		<item>
		<title>Internet Explorer style limit</title>
		<link>http://feedproxy.google.com/~r/IdisposableThoughts/~3/6Db78LJlvh0/</link>
		<comments>http://cprieto.com/2012/03/19/internet-explorer-style-limit/#comments</comments>
		<pubDate>Mon, 19 Mar 2012 06:16:13 +0000</pubDate>
		<dc:creator>cristian</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[bugs]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[internet explorer]]></category>
		<category><![CDATA[web dev]]></category>

		<guid isPermaLink="false">http://cprieto.com/?p=789</guid>
		<description><![CDATA[Today I discovered something amazing and nasty at the same time, the page looked good in any other browser but it didn’t rendered in any version of IE (9, 8, 7). After taking a look at the network traffic I discovered one of the style pages was not loaded (IE never did the proper request [...]]]></description>
			<content:encoded><![CDATA[<p>Today I discovered something amazing and nasty at the same time, the page looked good in any other browser but it didn’t rendered in any version of IE (9, 8, 7). After taking a look at the network traffic I discovered one of the style pages was not loaded (IE never did the proper request to the server asking for the css file). That sounds weird… I looked at the source code and the correct <code>&lt;link&gt;</code> sentence was there, then looked at the HTML structure in the IE developer tools, bam! the link was not&nbsp;processed.</p>
<p>After some research in the internet I found something amazingly nasty: Internet Explorer cannot handle more than 31 <code>&lt;style&gt;</code> sentences in a page. This applies to every version of IE (<strong>Internet Explorer 10 fixes this issue</strong> and won’t be a problem any more). This applies even with the combination of <code>&lt;link rel=”stylesheet” /&gt;</code> and <code>&lt;style&gt;</code> tags in the same page. <a href="http://support.microsoft.com/kb/262161">This article by Microsoft</a> explains that there is not only a limit for the styles defined but the rules (the article says that you cannot apply more than 4095 rules to a webpage in&nbsp;IE).</p>
<p>I found a <a href="http://john.albin.net/css/ie-stylesheets-not-loading">nice blog post</a> by <a href="http://john.albin.net/">John Albin</a> (Drupal Evangelist) about the issue and looks that even using the <a href="http://www.stevesouders.com/blog/2009/04/09/dont-use-import/">ugly @import rule</a> you would be limited to 993 stylesheets in the same page for Internet Explorer,&nbsp;ugly.</p>
<p>How to solve this issue? well, the easy way is simplifying your styles and using a style minizer and compressor (like the <a href="http://www.asp.net/web-forms/videos/aspnet-vnext/aspnet-vnext-videos-bundling-and-minification">Bundler</a> or <a href="http://www.codethinked.com/squishit-the-friendly-aspnet-javascript-and-css-squisher">SquishIt</a> for ASP.NET). Lesson learned: “don’t abuse of your&nbsp;stylesheets”.</p>
<img src="http://feeds.feedburner.com/~r/IdisposableThoughts/~4/6Db78LJlvh0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://cprieto.com/2012/03/19/internet-explorer-style-limit/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://cprieto.com/2012/03/19/internet-explorer-style-limit/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=internet-explorer-style-limit</feedburner:origLink></item>
		<item>
		<title>At least an element should be filled validation using jQuery validation</title>
		<link>http://feedproxy.google.com/~r/IdisposableThoughts/~3/-11amBhUowI/</link>
		<comments>http://cprieto.com/2012/03/14/at-least-an-element-should-be-filled-validation-using-jquery-validation/#comments</comments>
		<pubDate>Wed, 14 Mar 2012 07:54:30 +0000</pubDate>
		<dc:creator>cristian</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery validation]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://cprieto.com/?p=786</guid>
		<description><![CDATA[Today I got a nice client side validation request, actually was nice because was a simple and very common use case in form validation. Make sure the user fill at least one of the fields in the form before&#160;continue. Let’s say this is the&#160;case: The user should fill any contact detail to validate the form, [...]]]></description>
			<content:encoded><![CDATA[<p>Today I got a nice client side validation request, actually was nice because was a simple and very common use case in form validation. Make sure the user fill at least one of the fields in the form before&nbsp;continue.</p>
<p>Let’s say this is the&nbsp;case:</p>
<p><iframe style="width: 100%; height: 300px" src="http://jsfiddle.net/cprieto/GwxfY/embedded/result,html,js/" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
<p>The user should fill any contact detail to validate the form, sounds simple, and it is! the simple way to solve the issue is just creating a jQuery validator method then simply adding the class to the elements in the same group, using the magic of the special jQuery validator selector <code>:filled</code> would return the number of non empty fields in the group and it’s just matter of falsy or truly. Maybe something like&nbsp;this:</p>
<p><iframe style="width: 100%; height: 300px" src="http://jsfiddle.net/cprieto/GwxfY/6/embedded/js,result,html/" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
<p>The only problem with this approach is the validation messages, we don&#8217;t want to see the same label error message everywhere, we just want to display the error message once. Well, just matter of specify a validation group in jQuery validation, that’s&nbsp;all!</p>
<p><iframe style="width: 100%; height: 300px" src="http://jsfiddle.net/cprieto/GwxfY/7/embedded/js,result,html/" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
<p>See? nothing to worry&nbsp;about!</p>
<img src="http://feeds.feedburner.com/~r/IdisposableThoughts/~4/-11amBhUowI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://cprieto.com/2012/03/14/at-least-an-element-should-be-filled-validation-using-jquery-validation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://cprieto.com/2012/03/14/at-least-an-element-should-be-filled-validation-using-jquery-validation/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=at-least-an-element-should-be-filled-validation-using-jquery-validation</feedburner:origLink></item>
		<item>
		<title>ASP.NET MVC3, Filter attributes and dependency injection</title>
		<link>http://feedproxy.google.com/~r/IdisposableThoughts/~3/KyeWpLrQuiQ/</link>
		<comments>http://cprieto.com/2012/03/12/asp-net-mvc3-filter-attributes-and-dependency-injection/#comments</comments>
		<pubDate>Mon, 12 Mar 2012 07:57:14 +0000</pubDate>
		<dc:creator>cristian</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[features]]></category>
		<category><![CDATA[ioc]]></category>
		<category><![CDATA[mvc]]></category>

		<guid isPermaLink="false">http://cprieto.com/?p=764</guid>
		<description><![CDATA[Today a co-worker made me a nice question regarding ASP.NET MVC3, sounds like a simple question with a simple answer, but I think it worth the blog&#160;post. How do I inject a concern into my custom authorization attribute (or any other filter attribute) in the ASP.NET MVC3&#160;framework? The case is pretty simple, let’s say you [...]]]></description>
			<content:encoded><![CDATA[<p>Today a co-worker made me a nice question regarding ASP.NET MVC3, sounds like a simple question with a simple answer, but I think it worth the blog&nbsp;post.</p>
<p>How do I inject a concern into my custom authorization attribute (or any other filter attribute) in the ASP.NET MVC3&nbsp;framework?</p>
<p>The case is pretty simple, let’s say you have the following service and of course you are using a container to inject your&nbsp;dependencies</p>
<pre class="brush: csharp;">
public interface ILogger {
    void Log(string message);
}
</pre>
<p>Well, let&#8217;s say that we need to use that service inside our custom attribute for&nbsp;logging: </p>
<pre class="brush: csharp;">
public class LogAttribute : FilterAttributeProvider {
    public override void OnActionExecuting(ActionExecutingContext context) {
       // I need to use the ILogger service here!
    }
}
</pre>
<p>Well, we have two options here, the proper and the hack&#8230; let&#8217;s see the hack option&nbsp;first! </p>
<p><p>For the hack option we just need to use the Service Locator included with the ASP.NET MVC3&nbsp;framework:</p>
<pre class="brush: csharp;">
public class LogAttribute : FilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext context) {
	var log = DependencyResolver.Current.GetInstance&lt;ILogger&gt;();
	// do whatever you want to do here
    }
}
</pre>
<p>This probably would be one of the only two places you should use a Service Locator, and of course I don&#8217;t like it&#8230; Thanks to the guys in the ASP.NET MVC framework we have a &#8216;proper-like&#8217; way to do it, using a filter&nbsp;provider:</p>
<p>The idea is simple, we have an specific special class to provide the attributes that we need to do the job, in ASP.NET MVC3 that class is an implementation of <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.filterattributefilterprovider(v=vs.98).aspx">FilterAttributeFilterProvider</a>, most container integrations already has support for it and bundle your filter provider, in this example we would use <a href="http://code.google.com/p/autofac/">Autofac</a> (because was the container used in that particular&nbsp;project).</p>
<p>First we need to register the needed service and the provider in your registration code (generally in your Global.asax.cs file), maybe something like&nbsp;this:</p>
<pre class="brush: csharp;">
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType&lt;Logger&gt;().As&lt;ILogger&gt;().InstancePerHttpRequest();
builder.RegisterFilterProvider();

DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));
</pre>
<p>To make this work remember to add a reference to <a href="http://code.google.com/p/autofac/wiki/Mvc3Integration">Autofac’s MVC3 integration</a>&nbsp;assembly. </p>
<p>Now just create a property dependency in your&nbsp;FilterAttribute</p>
<pre class="brush: csharp;">
public class LogAttribute : FilterAttribute {
    public ILogger Log { get; set; }
    public override void OnActionExecuting(ActionExecutingContext context) {
	// Now we can use Log here!
    }
}
</pre>
<p>And well, that&#8217;s all&#8230; just matter of apply the attribute to your&nbsp;actions/controllers</p>
<p>Personally I don&#8217;t like neither of the approaches, I think attributes should be only markers, not behaviour concerns. A good implementation would be splitting the attribute in two, a marker interface and a behaviour class that would act if the attribute is present. With a little of hack this could be possible (would involve creating your own FilterProvider class that would get the present attributes and apply the correct filter attribute action to the engine, something like that)&#8230; Well, you got the point&nbsp;=) </p>
<p>As always, I&#8217;m open to suggestions and I hope this would help you my&nbsp;friend.</p>
<p><a href="http://bradwilson.typepad.com/blog/">Brad Wilson</a> has a really good blog post series about Dependency Injection and MVC3, including <a href="http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html">Filter Providers</a>, go and give a&nbsp;read.</p>
<p class="repository">
Sample solution in bitbucket&nbsp;<a href="https://bitbucket.org/cprieto/blogsamplecode/src/67b0831a1c00/FilterProviderSample">https://bitbucket.org/cprieto/blogsamplecode/src/</a></p>
<img src="http://feeds.feedburner.com/~r/IdisposableThoughts/~4/KyeWpLrQuiQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://cprieto.com/2012/03/12/asp-net-mvc3-filter-attributes-and-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://cprieto.com/2012/03/12/asp-net-mvc3-filter-attributes-and-dependency-injection/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=asp-net-mvc3-filter-attributes-and-dependency-injection</feedburner:origLink></item>
		<item>
		<title>Testing COM1 ports using a virtual machine and putty</title>
		<link>http://feedproxy.google.com/~r/IdisposableThoughts/~3/jlN-vqErDv0/</link>
		<comments>http://cprieto.com/2012/03/12/testing-com1-ports-using-a-virtual-machine-and-putty/#comments</comments>
		<pubDate>Mon, 12 Mar 2012 03:12:44 +0000</pubDate>
		<dc:creator>cristian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[emulation]]></category>
		<category><![CDATA[questions]]></category>
		<category><![CDATA[samples]]></category>
		<category><![CDATA[serial port]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[virtual machines]]></category>

		<guid isPermaLink="false">http://cprieto.com/?p=756</guid>
		<description><![CDATA[A few days ago a friend of mine asked me a few questions about how to test a COM1 device. The question sounds simple but think about that, sometimes you don’t have the needed COM1 device to test or your computer doesn’t have a COM1 port at all (for example, a&#160;laptop). I think this is [...]]]></description>
			<content:encoded><![CDATA[<p>A few days ago a friend of mine asked me a few questions about how to test a COM1 device. The question sounds simple but think about that, sometimes you don’t have the needed COM1 device to test or your computer doesn’t have a COM1 port at all (for example, a&nbsp;laptop).</p>
<p>I think this is the kind of job for a Virtual Machine… Let’s&nbsp;try.</p>
<p>We would need a few&nbsp;things:</p>
<ul>
<li>A virtual machine (I will use <a href="http://www.vmware.com/">VMWare</a>, but <a href="http://virtualbox.org/">VirtualBox</a> would do the trick&nbsp;too)</li>
<li>Putty (freeware you can download at&nbsp;<a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html">http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html</a>)</li>
<li>If possible, the protocol or messages send by your device (I would use a simple chat to do the&nbsp;sample)</li>
</ul>
<p>The secret is to redirect the COM1 port from the virtual machine to a file (possible in VMWare) or a <a href="http://en.wikipedia.org/wiki/Named_pipe">named pipe</a>, for starters, a named pipe is an <a href="http://en.wikipedia.org/wiki/Inter-process_communication">IPC mechanism</a> for process&nbsp;intercommunication.</p>
<p>In the virtual machine settings add a new hardware device and then select <em>Serial Port</em>, <em>Add to named pipe</em>, <em>Finish</em>. Write somewhere the name of the named pipe, in my case would be&nbsp;<strong>&#92;.\pipe\com_1</strong></p>
<p><a href="http://cprieto.com/wp-content/uploads/2012/03/com_port_named_pipe.png" rel="lightbox[756]"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="com_port_named_pipe" border="0" alt="com_port_named_pipe" src="http://cprieto.com/wp-content/uploads/2012/03/com_port_named_pipe_thumb.png" width="367" height="320"></a></p>
<p>Now, just for this experiment, I will use putty in the virtual machine to connect to COM1 and in my guest to connect to the named pipe, in that way I will send messages from the virtual machine to COM1 (as any other application would do) and I would be able to receive those messages in the guest through putty, and of course I can answer back from the&nbsp;guest.</p>
<p>In your putty host session remember to select “serial” as the connection type and instead of COM1 select the named pipe created by&nbsp;vmware</p>
<p><a href="http://cprieto.com/wp-content/uploads/2012/03/putty_guest.png" rel="lightbox[756]"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="putty_guest" border="0" alt="putty_guest" src="http://cprieto.com/wp-content/uploads/2012/03/putty_guest_thumb.png" width="309" height="298"></a></p>
<p>In the putty guest session everything is normal, just select “serial” and the expected COM* port, in my case would be&nbsp;COM2:</p>
<p><a href="http://cprieto.com/wp-content/uploads/2012/03/putty_guest_001.png" rel="lightbox[756]"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="putty_guest_001" border="0" alt="putty_guest_001" src="http://cprieto.com/wp-content/uploads/2012/03/putty_guest_001_thumb.png" width="310" height="302"></a></p>
<p>Putty attention in vmware notification icons, even when your named pipe is “com_1” could be possible that in your virtual machine that virtual port is COM2 (not COM1 as you would&nbsp;expect).</p>
<p><a href="http://cprieto.com/wp-content/uploads/2012/03/virtual_session.png" rel="lightbox[756]"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="virtual_session" border="0" alt="virtual_session" src="http://cprieto.com/wp-content/uploads/2012/03/virtual_session_thumb.png" width="378" height="225"></a></p>
<p>Now when I type “hello” in my virtual machine putty instance it will echo in the host putty session and the same backwards. Now, the question is simple, how do I emulate correctly my weird&nbsp;device?</p>
<p>Well, a nice and easy way would be to “record” a common communication session between your device and a machine with a COM1 installed, and then “replay” that session back in your virtual environment using putty or a home made program. You know what, I found a program to do exactly that in <a href="http://www.codeproject.com">CodeProject</a> (<a href="http://www.codeproject.com/Articles/18797/Application-to-Debug-Serial-Port-Communication">Application to Debug Serial Port communication</a> and <a href="http://www.codeproject.com/Articles/75770/Basic-serial-port-listening-application/">Basic Serial Port Listening Application</a>), go, give a try&nbsp;=)</p>
<p>I hope this would help you someway my&nbsp;friend.</p>
<img src="http://feeds.feedburner.com/~r/IdisposableThoughts/~4/jlN-vqErDv0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://cprieto.com/2012/03/12/testing-com1-ports-using-a-virtual-machine-and-putty/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://cprieto.com/2012/03/12/testing-com1-ports-using-a-virtual-machine-and-putty/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=testing-com1-ports-using-a-virtual-machine-and-putty</feedburner:origLink></item>
		<item>
		<title>Proxima VAN, HTML5 para los no iniciados y curiosos</title>
		<link>http://feedproxy.google.com/~r/IdisposableThoughts/~3/NnZJ_GaEYs4/</link>
		<comments>http://cprieto.com/2011/12/13/proxima-van-html5-para-los-no-iniciados/#comments</comments>
		<pubDate>Tue, 13 Dec 2011 12:28:34 +0000</pubDate>
		<dc:creator>cristian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[alt.net]]></category>
		<category><![CDATA[evento]]></category>
		<category><![CDATA[van]]></category>
		<category><![CDATA[web dev]]></category>

		<guid isPermaLink="false">http://cprieto.com/2011/12/13/proxima-van-html5-para-los-no-iniciados/</guid>
		<description><![CDATA[Este sabado 17 de diciembre tendre el placer de compartir con la comunidad de Alt.Net Hispano el codiciado tema “HTML5 para los no iniciados”, si, eso que esta sonando por todos lados acerca de HTML5, que tan raro es? como se come? me curara la caries? Tantas preguntas, tanto&#160;material. HTML5 es muchisimo mas que un [...]]]></description>
			<content:encoded><![CDATA[<p>Este sabado 17 de diciembre tendre el placer de compartir con la comunidad de <a href="http://altnethispano.org/Inicio.aspx">Alt.Net Hispano</a> el codiciado tema “HTML5 para los no iniciados”, si, eso que esta sonando por todos lados acerca de HTML5, que tan raro es? como se come? me curara la caries? Tantas preguntas, tanto&nbsp;material.</p>
<p>HTML5 es muchisimo mas que un estandar, mucho mas que un simple buzz, va bastante mas alla de un simple lenguaje de markup. Tratare de explicar HTML5 desde el punto de vista de un desarrollador web, especialmente que implica para un developer de&nbsp;ASP.NET.</p>
<p>El evento pueden encontrarlo en el <a href="http://bit.ly/vZx2xk">link de Google Calendar</a>, no olviden hacer la transformacion en su huso&nbsp;horario.</p>
<img src="http://feeds.feedburner.com/~r/IdisposableThoughts/~4/NnZJ_GaEYs4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://cprieto.com/2011/12/13/proxima-van-html5-para-los-no-iniciados/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://cprieto.com/2011/12/13/proxima-van-html5-para-los-no-iniciados/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=proxima-van-html5-para-los-no-iniciados</feedburner:origLink></item>
		<item>
		<title>JustCode is not loading in Visual Studio 2011</title>
		<link>http://feedproxy.google.com/~r/IdisposableThoughts/~3/oUce_0__TVc/</link>
		<comments>http://cprieto.com/2011/11/06/justcode-is-not-loading-in-visual-studio-2011/#comments</comments>
		<pubDate>Sat, 05 Nov 2011 16:39:49 +0000</pubDate>
		<dc:creator>cristian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[2011]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[extensibility]]></category>
		<category><![CDATA[justcode]]></category>
		<category><![CDATA[mef]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://cprieto.com/index.php/2011/11/06/justcode-its-not-loading-in-visual-studio-2011/</guid>
		<description><![CDATA[Telerik’s JustCode it’s an awesome product, it’s a very lightweight extension that may lack some features (sorry, I won’t mention names) but it does its job, and that’s good. Almost a month ago Telerik announced JustCode support for Visual Studio 2011, that’s awesome, specially when I decided to try out Visual Studio 2011 in a [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.telerik.com/products/justcode.aspx">Telerik’s JustCode</a> it’s an <a href="http://blogs.telerik.com/justteam/posts.aspx">awesome product</a>, it’s a very lightweight extension that may lack some features (sorry, I won’t mention names) but it does its job, and that’s good. Almost a month ago <a href="http://blogs.telerik.com/justteam/posts/11-09-22/justcode-support-for-visual-studio-11.aspx">Telerik announced JustCode support for Visual Studio 2011</a>, that’s awesome, specially when I decided to try out Visual Studio 2011 in a pristine installation inside a virtual machine (and yeah, I know other extensions <a href="http://blogs.jetbrains.com/dotnet/2011/11/resharper-61-eap-opens-much-more-than-a-bugfix-release/">already announced</a> <a href="http://www.devexpress.com/Home/Announces/2011-coderush-vs-11-build.xml">the&nbsp;same</a>).</p>
<p><a href="http://cprieto.com/wp-content/uploads/2011/11/installer.png" rel="lightbox[731]"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="installer" border="0" alt="installer" src="http://cprieto.com/wp-content/uploads/2011/11/installer_thumb.png" width="416" height="322"></a></p>
<p>I downloaded the JustCode internal build and the installer correctly detected my Visual Studio 2011 installation, sweet, everything finished without any problem. Then when I started Visual Studio 2011 I realized JustCode didn’t load… and all what I get it’s a very verbose exception in the JustCode’s output&nbsp;window:</p>
<p><code class="console">ERROR 2011-10-23 00:23:38.842 :&nbsp; [HResult: 80131602] <br />System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.<br />&nbsp;&nbsp; at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)<br />&nbsp;&nbsp; at System.Reflection.RuntimeModule.GetTypes()<br />&nbsp;&nbsp; at System.Reflection.Assembly.GetTypes()<br />&nbsp;&nbsp; at System.ComponentModel.Composition.Hosting.AssemblyCatalog.get_InnerCatalog()<br />[and a lot of more&nbsp;lines...]</code></p>
<p>I submitted some bug tickets, write to some Telerik’s developers but no right answers, you know, the&nbsp;usual.</p>
<p>Well, I decided to see what’s happened, so I did what every other developer would do, attach your debugger to Visual Studio and then found the issue. JustCode is trying to load the assembly <strong>Microsoft.VisualStudio.CSharp.Services.Language, Version=10.0.0.0</strong> but <em>in a machine without Visual Studio 2010 this assembly didn’t exist</em>, it’s unique of a Visual Studio 2010 installation. Of course, I’m using a Virtual Machine snapshot, I don’t have a previous version installed. The assembly present in my VS2011 installation is&nbsp;<strong>Version=11.0.0.0</strong>.</p>
<p>The easy way to fix it? Go to a Visual Studio 2010 installation, copy the assembly Microsoft.VisualStudio.CSharp.Services.Language.dll from the Common7 directory and paste into your Telerik’s JustCode directory, that’s all, JustCode now it’s going to load. Maybe this would cause some other problems, but come on, it was my first attempt!&nbsp;=)</p>
<p>Probably a better way to fix it would be using <a href="http://msdn.microsoft.com/en-us/library/7wd6ex19.aspx">assembly binding redirection</a>, or taking care of the fact that <em>maybe</em> a previous installation it’s not present maybe in the installation process. I’m just&nbsp;saying!</p>
<p><strong>Note for developers in general</strong>: it’s a good idea to test your installation in a pristine installation before release it to the wild, just to see what’s happening, you know, just in case&nbsp;=)</p>
<img src="http://feeds.feedburner.com/~r/IdisposableThoughts/~4/oUce_0__TVc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://cprieto.com/2011/11/06/justcode-is-not-loading-in-visual-studio-2011/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://cprieto.com/2011/11/06/justcode-is-not-loading-in-visual-studio-2011/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=justcode-is-not-loading-in-visual-studio-2011</feedburner:origLink></item>
		<item>
		<title>El espejismo de la separacion por capas, toma dos</title>
		<link>http://feedproxy.google.com/~r/IdisposableThoughts/~3/8R9fcvHuOWo/</link>
		<comments>http://cprieto.com/2011/10/28/el-espejismo-de-la-separacion-por-capas-toma-dos/#comments</comments>
		<pubDate>Fri, 28 Oct 2011 03:13:40 +0000</pubDate>
		<dc:creator>cristian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[rant]]></category>

		<guid isPermaLink="false">http://cprieto.com/index.php/2011/10/28/el-espejismo-de-la-separacion-por-capas-toma-dos/</guid>
		<description><![CDATA[Hace varios meses escribí un blog post (que quise luego transformar en serie y como cosa rara en mi por tiempo nunca llegue a continuarlo) en el que indicaba mi falta de amor a la palabra &#8220;capas&#8221;&#8230;. El concepto de &#8220;capas&#8221; o &#8220;layers&#8221; me parece desde unos años para acá tan ortodoxo, viejo, fuera de [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://cprieto.com/wp-content/uploads/2011/10/app_3.gif" rel="lightbox[728]"><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px 6px 0px 0px; padding-left: 0px; padding-right: 0px; display: inline; float: left; border-top: 0px; border-right: 0px; padding-top: 0px" title="app_3" border="0" alt="app_3" align="left" src="http://cprieto.com/wp-content/uploads/2011/10/app_3_thumb.gif" width="244" height="155"></a>Hace varios meses escribí <a href="http://cprieto.com/index.php/2010/05/21/el_espejismo_de_la_separacion_por_capas/">un blog post</a> (que quise luego transformar en serie y como cosa rara en mi por tiempo nunca llegue a continuarlo) en el que indicaba mi falta de amor a la palabra &#8220;capas&#8221;&#8230;.
<p>El concepto de &#8220;capas&#8221; o &#8220;layers&#8221; me parece desde unos años para acá tan ortodoxo, viejo, fuera de lugar, obsoleto, mal aplicado, afuera totalmente de contexto. La idea de capas tenía mucho sentido hace décadas atrás (tampoco décadas pero fue hace tiempo) cuando los programadores cavernícolas (en los cuales me incluyo yo picando piedra) teníamos que depender fuertemente en la base de datos, hacíamos las consultas en plano SQL, insertábamos directamente en plano SQL, y si mi DB me la movían literalmente movían mi aplicación.
<p>Esto tenía todo el sentido del mundo en nuestras aplicaciones no tan complejas y sin mucha orientación lógica que hacíamos en aplicaciones desktops o web, o sea, en vez de escribir cientos de líneas SQL esparcidas por doquier en nuestro código de php (por ejemplo), mejor lo abstraíamos todo en un solo lugar donde estaba guardadito nuestro SQL, ahí en su cajita, donde nadie lo tocaba y si alguien lo tocaba era una vez (como que si tocar una consulta no involucrara cambiar algo&#8230; silly us). Esto se llevó un paso adelante y en vez de poner consultas como SELECT * FROM [tabla] mejor usamos SP&#8217;s, así que cambiamos eso por EXEC usp_MiConsulta, esto dio origen a otro problema, pero vamos a ir al grano primero.
<p>En ese tiempo la gente comenzó a percatarse de algo, si abstraigo las consultas a la DB, luego las llamadas a la DB en otro lado, puedo entonces poner la &#8220;lógica&#8221; de negocio en otro lado y sobre ella hacer la UI. Esto tenía mucho sentido y asi nació el concepto de &#8220;layers&#8221;&#8230; Tiene sentido, tenía sentido en ese tiempo, teníamos aplicaciones con el &#8220;típico&#8221; color aqua y un par de botones con iconos de puertas y equis tachadas en primera plana, con una grid para mostrar facturas y un botón donde agregábamos una factura nueva (generalmente con el icono más o con un lapicito que aun no entiendo porque aparecía ahí).
<p>Luego vino la moda SOA (que pareciera nunca acabar) y dijeron, va, ahora en vez de hablar directamente la lógica con la data, vamos a tener alguien en el medio que expone esa data por un servicio. Entonces hablamos de SOA&#8230; como ya no eran 3 capas si no 4 o más renombramos el modelo a n-Capas&#8230;. y aun me perfora el oído escucharlo&#8230;.
<p>He visto degeneraciones de este modelo, un &#8220;buen&#8221; ejemplo son las aplicaciones ejemplo de MS, donde abstraen todo a servicios que al final el mismo objeto desde el comienzo al fin es el mismo. Es increíble pero he visto a desarrolladores veteranos que aun insisten en usar su versión de servicio para exponer todo, pero esa es otra historia&#8230;
<p>Nuevamente recalco, eso tenía sentido *en ese tiempo* los ORM&#8217;s o no existían o eran sumamente rudimentarios, la mayoría de db devs que habían estaban aún acostumbrados a hacer _todo_ en la DB (no, en serio, una vez vi una app que hasta el proceso de pago de paypal era hecho internamente en la DB), tenía sentido cuando tu aplicacion era la tipica aplicación con botones grandes y background aqua&#8230; Tenía sentido cuando decías que abstraías el acceso a datos en una clase que por lo general comenzaba por una pequeña clase con un par de métodos y terminaba como cientos&#8230; porque tal cosa como reutilizar el acceso a datos se tornó un santo grial.
<p>Eso no tiene sentido HOY, cuando nuestros objetos son (o deberían ser) ricos en comportamiento, cuando modelamos en base a lo que _va a pasar y hacer nuestra aplicación_ no en cuanto a la data que va a contener la base de datos (puntos extras para el que comprenda la diferencia entre ambos approaches en la oración anterior). No tiene sentido hoy que nuestra &#8220;lógica de negocio&#8221; realmente puede ser embebida en el objeto del dominio o de negocio, donde hacemos una distinción entre lógica de negocio (o reglas del negocio) y lógica de presentación (que como dice el nombre solamente afecta la vista). No tiene sentido cuando no interactuamos contra solo una base de datos si no contra base de datos, archivos, servicios (y generalmente varios). No tiene sentido porque no le veo ni cara ni cuerpo a tener un ORM (por simple que sea) y envolver las mismas entidades y exponerlas mediante otras entidades que contienen los mismos símbolos, no tiene sentido hablar de capa de acceso a datos ya que tus Objetos de ORM no solamente viven ahí y pueden contener la lógica que tanto necesitas en la &#8220;siguiente&#8221; capa. No tiene sentido en un mundo donde el programador está acostumbrado (y hasta espera) que la consulta se genere automáticamente mediante Linq, no tiene sentido en un mundo donde ya no escribimos SQL a mano.
<p>¿No te gusta un ORM porque tiene demasiada carga para lo que necesitas? bueno usa un <a href="http://code.google.com/p/dapper-dot-net/">MicroORM</a>&#8230; y aun así sigues sin hablar de capa de datos, tal cosa ya no existe. Ni siquiera Microsoft con sus prácticas habla de layers&#8230;. Vamos, ahora ni en PHP puedes tener el coraje de decir que tienes que escribir SQL a mano, porque entonces abstraer todo en una “capa”, ¿quieren producir algo de misterio? Traten de preguntarle a un programador de Rails donde está su capa de datos, no existe, ¿porque?&#8230; No es necesaria tal separación.
<p>Ahora, lo que si debes distinguir es el concepto de <a href="http://en.wikipedia.org/wiki/Business_logic">Tiers</a>, una aplicación si va a tener varios Tiers, la base de datos (a menos que sea embebida) vivirá y es por definición un tier, ¿expones servicios? bueno, otro tier mas&#8230;. Un tier es una separación física de la cual no puedes deshacerte, una layer es una separación lógica que realmente no tiene sentido en un mundo ágil donde no usamos 6 meses &#8220;diseñando&#8221; la aplicación.
<p>Algún día ordenare todos mis pensamientos y terminare escribiendo un poco más sobre porque el concepto de layer sigue siendo obsoleto, por lo menos para mí.
<p><strong>NOTA</strong>: Este fue un largo correo en la lista de Alt.Net hispano que termino siendo tan largo que llego a ocupar un blog&nbsp;post.</p>
<img src="http://feeds.feedburner.com/~r/IdisposableThoughts/~4/8R9fcvHuOWo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://cprieto.com/2011/10/28/el-espejismo-de-la-separacion-por-capas-toma-dos/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		<feedburner:origLink>http://cprieto.com/2011/10/28/el-espejismo-de-la-separacion-por-capas-toma-dos/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=el-espejismo-de-la-separacion-por-capas-toma-dos</feedburner:origLink></item>
		<item>
		<title>Generating generic delegates with expression trees</title>
		<link>http://feedproxy.google.com/~r/IdisposableThoughts/~3/PO3649uxunA/</link>
		<comments>http://cprieto.com/2011/10/22/generating-generic-delegates-with-expression-trees/#comments</comments>
		<pubDate>Fri, 21 Oct 2011 14:58:51 +0000</pubDate>
		<dc:creator>cristian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[bdd]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[mfakes]]></category>
		<category><![CDATA[mspec]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://cprieto.com/index.php/2011/10/22/generating-generic-delegates-with-expression-trees/</guid>
		<description><![CDATA[A few weeks ago I was working in a patch for an awesome mocking meta framework named mfakes, a very awesome mocking meta-framework based in the spicy Machine Specification BDD testing framework, go, try it, you are going to love&#160;it!. Well, one of the awesome points in mfakes it’s to abstract mocking frameworks, so mfakes [...]]]></description>
			<content:encoded><![CDATA[<p>A few weeks ago I was working in a patch for an awesome mocking meta framework named <a href="https://github.com/BjRo/Machine.Fakes">mfakes</a>, a very awesome mocking meta-framework based in the spicy <a href="https://github.com/machine/machine.specifications">Machine Specification</a> BDD testing framework, go, try it, you are going to love&nbsp;it!.</p>
<p>Well, one of the awesome points in mfakes it’s to abstract mocking frameworks, so mfakes provides adapters for popular mocking frameworks like <a href="http://hibernatingrhinos.com/open-source/rhino-mocks">Rhino Mocks</a>, <a href="http://code.google.com/p/moq/">Moq</a>, <a href="http://nsubstitute.github.com/">NSubstitute</a> and <a href="http://code.google.com/p/fakeiteasy/">FakeItEasy</a>. So instead of thinking which one to use, just concentrate in the test.&nbsp;Simple.</p>
<p>Anyway, there was a feature lacking in mfakes, and as every developer when something it’s lacking a feature you just go ahead and implement it, nothing beats open source. The interesting point was trying to “wrap” different way to interact between every mocking framework, everyone has a different way to see the world, it’s not bad, but it’s different. I found a very interesting problem with FakeItEasy and constructor parameters in a&nbsp;Mock.</p>
<p>In most mocking frameworks there’s an easy way to specify constructor parameters for a mock, in Moq, for example, you just do something like&nbsp;this:</p>
<pre class="brush: csharp;">var foo = new Mock&lt;T&gt;("foo", "bar");

// Generate this it's easy, it's just a simple generic type
// with a parameter list

public object CreateFake(Type interfaceType, params object[] args) {
    var closedMockType = typeof(Mock&lt;&gt;).MakeGenericType(interfaceType);
    var objectProperty = closedMockType.GetProperty("Object", closedMockType);
    var instance = (args != null &amp;&amp; args.Length &gt; 0)
        ? Activator.CreateInstance(closedMockType, args) : Activator.CreateInstance(closedMockType);
    return objectProperty.GetValue(instance, null);
}
</pre>
<p>The problem it’s that FakeItEasy it’s magic, and uses a very nice strong typed way to do&nbsp;it</p>
<pre class="brush: csharp;">var foo = A.Fake&lt;FooClass&gt;(x =&gt;
    x.WithArgumentsForConstructor(
        new[] object {"foo", "bar"}));
// Another way to do it, more strongly-typed
var foo = A.Fake&lt;FooClass&gt;(x =&gt;
    x.WithArgumentsForConstructor(
        ()=&gt; new FooClass("foo", "bar")));
</pre>
<p>Well, if you think about that, there’s not a simple way to abstract a non-generic, non-typed expression with a generic, strong-typed, functional expression, well, not a simple way to do it at least you use the expressiveness of binary expression trees. How do we abstract this? well, let’s see the simple&nbsp;expression:</p>
<p>Now, let’s create a function to return that expression based in parameters, let’s abstract everything with the only knowlege of the type and the&nbsp;parameters:</p>
<pre class="brush: csharp;">// Transforming this:
var foo = A.Fake&lt;T&gt;(Action&lt;IFakeOptionsBuilder&lt;T&gt;&gt; opts)

// Implies something like this
public static Delegate CreateForType(Type type, object[] args) {
    var optType = typeof(IFakeOptionsBuilder&lt;&gt;).MakeGenericType(new[] { type });
    var actType = typeof(Action&lt;&gt;).MakeGenericType(new[] { optType });

// Now we have the type for the action and the options builder
// Let's use it to create an expression tree!

    var r = Expression.Parameter(optType, "r");
    var method = optType.GetMethod("WithArgumentsForConstructor", new[] { typeof(IEnumerable&lt;object&gt;) });
    var p = Expression.Constant(ctorArgs);
    var call = Expression.Call(r, method, p);
    var lambda = Expression.Lambda(actType, call, new[] { r });
    var exp = lambda.Compile();
}
</pre>
<p>And well, now that we have the function to call (we generated it), it&#8217;s time to create the&nbsp;fake</p>
<pre class="brush: csharp;">public object CreateFake(Type type, params object[] args) {
    var closedFakeType = typeof(Fake&lt;&gt;).MakeGenericType(interfaceType);
    var objectProperty = closedFakeType.GetProperty("FakedObject", interfaceType);

    var options = args != null &amp;&amp; args.Length &gt; 0
        ? FakeItEasyHelper.CreateForType(interfaceType, args) : null;

    var instance = args != null &amp;&amp; args.Length &gt; 0
        ? Activator.CreateInstance(closedFakeType, new object[] {options})
        : Activator.CreateInstance(closedFakeType);

    return objectProperty.GetValue(instance, null);
}
</pre>
<p>See? that’s the reason because Functional programming it’s so awesome, functions are just another variable, you can generate them, use them, modify them, use them. Next time you have a problem try to think in a functional way, you will see how awesome&nbsp;is!.</p>
<p>More about Expression Trees in the amazing book <a href="http://www.amazon.com/gp/product/1935182471/ref=as_li_ss_tl?ie=UTF8&amp;tag=idispthoug-20&amp;linkCode=as2&amp;camp=217145&amp;creative=399369&amp;creativeASIN=1935182471">C# in Depth, Second Edition</a><img style="border-bottom-style: none !important; margin: 0px; border-left-style: none !important; border-top-style: none !important; border-right-style: none !important" border="0" alt="" src="http://www.assoc-amazon.com/e/ir?t=idispthoug-20&amp;l=as2&amp;o=1&amp;a=1935182471&amp;camp=217145&amp;creative=399369" width="1" height="1"> by John Skeet or go and pick a functional language (like this <a href="http://www.amazon.com/gp/product/0596153643/ref=as_li_ss_tl?ie=UTF8&amp;tag=idispthoug-20&amp;linkCode=as2&amp;camp=217145&amp;creative=399369&amp;creativeASIN=0596153643">Programming F#</a><img style="border-bottom-style: none !important; margin: 0px; border-left-style: none !important; border-top-style: none !important; border-right-style: none !important" border="0" alt="" src="http://www.assoc-amazon.com/e/ir?t=idispthoug-20&amp;l=as2&amp;o=1&amp;a=0596153643&amp;camp=217145&amp;creative=399369" width="1" height="1">), study it, enjoy it, use it in your favourite non-functional&nbsp;language.</p>
<p>Happy&nbsp;coding!</p>
<p><strong>NOTE:</strong> the patch it’s already included in mfakes, no&nbsp;worries!</p>
<img src="http://feeds.feedburner.com/~r/IdisposableThoughts/~4/PO3649uxunA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://cprieto.com/2011/10/22/generating-generic-delegates-with-expression-trees/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://cprieto.com/2011/10/22/generating-generic-delegates-with-expression-trees/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=generating-generic-delegates-with-expression-trees</feedburner:origLink></item>
	</channel>
</rss>

