<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Felice Pollano Blog - CSharp</title>
    <link>http://www.felicepollano.com/</link>
    <description>The official Fatica Labs Blog!</description>
    <language>en-us</language>
    <copyright>Felice Pollano</copyright>
    <lastBuildDate>Wed, 25 Apr 2012 14:58:04 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>felice@felicepollano.com</managingEditor>
    <webMaster>felice@felicepollano.com</webMaster>
    <item>
      <trackback:ping>http://www.felicepollano.com/Trackback.aspx?guid=47000489-9142-4393-805f-4fdef6beb53f</trackback:ping>
      <pingback:server>http://www.felicepollano.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.felicepollano.com/PermaLink.aspx?guid=47000489-9142-4393-805f-4fdef6beb53f</pingback:target>
      <dc:creator>Felice Pollano</dc:creator>
      <wfw:comment>http://www.felicepollano.com/CommentView.aspx?guid=47000489-9142-4393-805f-4fdef6beb53f</wfw:comment>
      <wfw:commentRss>http://www.felicepollano.com/SyndicationService.asmx/GetEntryCommentsRss?guid=47000489-9142-4393-805f-4fdef6beb53f</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p align="justify">
Yesterday I had an interesting discussion with a colleague about using <strong>IoC</strong> in
the real world in a proper way, without falling back in the <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx" target="_blank">Service
Locator Antipattern</a>, and of course without having a reference to the container,
that is just so horrible to not worth any word. So we both found the solution being
the use of factories, supplied by the container, to create the on-the-fly requested
components. I was used to craft these factories by hand, but I know is a little silly,
especially when the colleague talked about the <a href="http://stw.castleproject.org/Windsor.Typed-Factory-Facility.ashx" target="_blank">Castle(Windsor)
typed factories</a>. So quite interesting, but since I choose NInject as my IoC (
Castle was the first container I saw, and my first love too ) I felt the challenge
to implement the same but… Fortunately ( well, for say it would be nice being the
implementer ) <a href="http://www.planetgeek.ch/author/remo-gloor/" target="_blank">Remo
Gloor</a> provided a <a href="https://github.com/ninject/ninject.extensions.factory" target="_blank">NInject
extension</a> that does almost the same for this other beautiful container. A nice
documentation is also available on the <a href="https://github.com/ninject/ninject.extensions.factory/wiki" target="_blank">Github
repository</a>. So thanks to a discussion I improved my programming knowledge, the
Ninject.extensios.factoy is added to my toolbox <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-openmouthedsmile" alt="A bocca aperta" src="http://www.felicepollano.com/public/Windows-Live-Writer/NInject-Type-Factory_EA20/wlEmoticon-openmouthedsmile_2.png" /></p>
        <img width="0" height="0" src="http://www.felicepollano.com/aggbug.ashx?id=47000489-9142-4393-805f-4fdef6beb53f" />
      </body>
      <title>NInject Typed Factory</title>
      <guid isPermaLink="false">http://www.felicepollano.com/PermaLink.aspx?guid=47000489-9142-4393-805f-4fdef6beb53f</guid>
      <link>http://www.felicepollano.com/2012/04/25/NInjectTypedFactory.aspx</link>
      <pubDate>Wed, 25 Apr 2012 14:58:04 GMT</pubDate>
      <description>&lt;p align="justify"&gt;
Yesterday I had an interesting discussion with a colleague about using &lt;strong&gt;IoC&lt;/strong&gt; in
the real world in a proper way, without falling back in the &lt;a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx" target="_blank"&gt;Service
Locator Antipattern&lt;/a&gt;, and of course without having a reference to the container,
that is just so horrible to not worth any word. So we both found the solution being
the use of factories, supplied by the container, to create the on-the-fly requested
components. I was used to craft these factories by hand, but I know is a little silly,
especially when the colleague talked about the &lt;a href="http://stw.castleproject.org/Windsor.Typed-Factory-Facility.ashx" target="_blank"&gt;Castle(Windsor)
typed factories&lt;/a&gt;. So quite interesting, but since I choose NInject as my IoC (
Castle was the first container I saw, and my first love too ) I felt the challenge
to implement the same but… Fortunately ( well, for say it would be nice being the
implementer ) &lt;a href="http://www.planetgeek.ch/author/remo-gloor/" target="_blank"&gt;Remo
Gloor&lt;/a&gt; provided a &lt;a href="https://github.com/ninject/ninject.extensions.factory" target="_blank"&gt;NInject
extension&lt;/a&gt; that does almost the same for this other beautiful container. A nice
documentation is also available on the &lt;a href="https://github.com/ninject/ninject.extensions.factory/wiki" target="_blank"&gt;Github
repository&lt;/a&gt;. So thanks to a discussion I improved my programming knowledge, the
Ninject.extensios.factoy is added to my toolbox &lt;img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-openmouthedsmile" alt="A bocca aperta" src="http://www.felicepollano.com/public/Windows-Live-Writer/NInject-Type-Factory_EA20/wlEmoticon-openmouthedsmile_2.png"&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.felicepollano.com/aggbug.ashx?id=47000489-9142-4393-805f-4fdef6beb53f" /&gt;</description>
      <comments>http://www.felicepollano.com/CommentView.aspx?guid=47000489-9142-4393-805f-4fdef6beb53f</comments>
      <category>CSharp</category>
      <category>Programming</category>
    </item>
    <item>
      <trackback:ping>http://www.felicepollano.com/Trackback.aspx?guid=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2</trackback:ping>
      <pingback:server>http://www.felicepollano.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.felicepollano.com/PermaLink.aspx?guid=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2</pingback:target>
      <dc:creator>Felice Pollano</dc:creator>
      <wfw:comment>http://www.felicepollano.com/CommentView.aspx?guid=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2</wfw:comment>
      <wfw:commentRss>http://www.felicepollano.com/SyndicationService.asmx/GetEntryCommentsRss?guid=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In this post I will show how to make testable something that ( at least me ) usually
left as untested. I’m talking about the preparing phase of a console app, the checking
arguments error reporting and so on. That logic is usually so simple that any good
cow boy programmer would probably leave outside any unit testing. Unfortunately we
should at least do some manually check that prove that logic working, and doing things
manually is always silly. In this post we assume we have a <a href="http://www.ndesk.org/Options" target="_blank">working
command line parsing library</a>, <a href="http://code.google.com/p/moq/" target="_blank">and
a mocking framework</a>. Let see the cowboy code:
</p>
        <pre lang="C#">        static void Main(string[] args)
        {
            string optA,optB;
            optA = optB = null;
            bool done = false;
            OptionSet set = new OptionSet();
            set.Add("a=", (k) =&gt; optA = k);
            set.Add("b=", (k) =&gt; optB = k);
            set.Add("h", (k) =&gt; { LongHelp(); done = true; });
            set.Parse(args);
            if (done)
                return;
            if (string.IsNullOrEmpty(optA) || string.IsNullOrEmpty(optB))
            {
                ShortHelp();
                return;
            }
            DoTheJob(optA,optB);
            
        }

        private static void DoTheJob(string optA, string optB)
        {
            //something interesting here
        }

        private static void LongHelp()
        {
            Console.Error.WriteLine("Long help here...");
        }

        private static void ShortHelp()
        {
            Console.Error.WriteLine("Short help here");
        }
    }
</pre>
        <p>
So nothing special, the example is actually very simple, we have two mandatory parameters,
a command line switch to print a long help. If one argument is missing a short help
line must be presented. If all the parameters are provided, the DoTheJob() method
should be called with the correct values. 
</p>
        <p>
Current code is not testable without hosting the console application as a process,
and looking at the stdout to see what happen. Even by this strategy, we can not punctually
check what is passed to DoTheJob. So we want to refactor the code, without adding
any complexity to the app. So here below the proposed refactoring:
</p>
        <pre lang="C#">    public class Program
    {
        static void Main(string[] args)
        {
            new Program().Run(args);
        }
        public virtual void Run(string[] args)
        {
            string optA, optB;
            optA = optB = null;
            bool done = false;
            OptionSet set = new OptionSet();
            set.Add("a=", (k) =&gt; optA = k);
            set.Add("b=", (k) =&gt; optB = k);
            set.Add("h", (k) =&gt; { LongHelp(); done = true; });
            set.Parse(args);
            if (done)
                return;
            if (string.IsNullOrEmpty(optA) || string.IsNullOrEmpty(optB))
            {
                ShortHelp();
                return;
            }
            DoTheJob(optA, optB);

        }

        public virtual void DoTheJob(string optA, string optB)
        {
            //something interesting here
        }

        public virtual void LongHelp()
        {
            Console.Error.WriteLine("Long help here...");
        }

        public virtual void ShortHelp()
        {
            Console.Error.WriteLine("Short help here");
        }
    }
</pre>
        <p>
 
</p>
        <p>
So pretty easy, we provide a non static method Run(), and all the internal function
are declared virtual. This is a five minutes modification we could probably apply
to any other code like this we have. The difference is that we can write some unit
test, lets see how:
</p>
        <pre lang="C#">        [TestMethod]
        public void ShouldDisplayShortHelp()
        {
            var moq = new Mock<program>
(); moq.CallBase = true; moq.Setup(k=&gt;k.DoTheJob(It.IsAny<string>
(),It.IsAny<string>
())) .Throws(new InvalidProgramException("Should not call")); moq.Object.Run(new string[0]);
moq.Verify(k =&gt; k.ShortHelp()); } [TestMethod] public void ShouldDisplayLongHelp()
{ var moq = new Mock<program>
(); moq.CallBase = true; moq.Setup(k =&gt; k.DoTheJob(It.IsAny<string>
(), It.IsAny<string>
())) .Throws(new InvalidProgramException("Should not call")); moq.Object.Run(new string[]{"-h"});
moq.Verify(k =&gt; k.LongHelp()); } [TestMethod] public void ShouldInvokeWithProperParameters()
{ var moq = new Mock<program>
(); moq.CallBase = true; moq.Setup(k =&gt; k.DoTheJob("p1", "p2")).Verifiable(); moq.Object.Run(new
string[] { "-a=p1","-b=p2" }); moq.Verify(); } 
</program></string></string></program></string></string></program></pre>
        <p>
 
</p>
        <p>
I used the MoQ library, please note the Callbase set to true, because we are using
the same object for driving and for expect calls. So in conclusion, we achieve a real
unit test of something we sometimes left apart, we did that in memory, and even if
the example is really trivial, the concept can be used in complex scenarios too. What
about testing the inside part of DoTheJob()? well, if a good testing strategy is used,
the internal part should be testable outside somewhere else, here we are  proving
we can test the shell.  
</p>
        <img width="0" height="0" src="http://www.felicepollano.com/aggbug.ashx?id=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2" />
      </body>
      <title>From Untestable to Testable Console App</title>
      <guid isPermaLink="false">http://www.felicepollano.com/PermaLink.aspx?guid=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2</guid>
      <link>http://www.felicepollano.com/2012/02/29/FromUntestableToTestableConsoleApp.aspx</link>
      <pubDate>Wed, 29 Feb 2012 21:47:36 GMT</pubDate>
      <description>&lt;p&gt;
In this post I will show how to make testable something that ( at least me ) usually
left as untested. I’m talking about the preparing phase of a console app, the checking
arguments error reporting and so on. That logic is usually so simple that any good
cow boy programmer would probably leave outside any unit testing. Unfortunately we
should at least do some manually check that prove that logic working, and doing things
manually is always silly. In this post we assume we have a &lt;a href="http://www.ndesk.org/Options" target="_blank"&gt;working
command line parsing library&lt;/a&gt;, &lt;a href="http://code.google.com/p/moq/" target="_blank"&gt;and
a mocking framework&lt;/a&gt;. Let see the cowboy code:
&lt;/p&gt;
&lt;pre lang="C#"&gt;        static void Main(string[] args)
        {
            string optA,optB;
            optA = optB = null;
            bool done = false;
            OptionSet set = new OptionSet();
            set.Add("a=", (k) =&amp;gt; optA = k);
            set.Add("b=", (k) =&amp;gt; optB = k);
            set.Add("h", (k) =&amp;gt; { LongHelp(); done = true; });
            set.Parse(args);
            if (done)
                return;
            if (string.IsNullOrEmpty(optA) || string.IsNullOrEmpty(optB))
            {
                ShortHelp();
                return;
            }
            DoTheJob(optA,optB);
            
        }

        private static void DoTheJob(string optA, string optB)
        {
            //something interesting here
        }

        private static void LongHelp()
        {
            Console.Error.WriteLine("Long help here...");
        }

        private static void ShortHelp()
        {
            Console.Error.WriteLine("Short help here");
        }
    }
&lt;/pre&gt;
&lt;p&gt;
So nothing special, the example is actually very simple, we have two mandatory parameters,
a command line switch to print a long help. If one argument is missing a short help
line must be presented. If all the parameters are provided, the DoTheJob() method
should be called with the correct values. 
&lt;/p&gt;
&lt;p&gt;
Current code is not testable without hosting the console application as a process,
and looking at the stdout to see what happen. Even by this strategy, we can not punctually
check what is passed to DoTheJob. So we want to refactor the code, without adding
any complexity to the app. So here below the proposed refactoring:
&lt;/p&gt;
&lt;pre lang="C#"&gt;    public class Program
    {
        static void Main(string[] args)
        {
            new Program().Run(args);
        }
        public virtual void Run(string[] args)
        {
            string optA, optB;
            optA = optB = null;
            bool done = false;
            OptionSet set = new OptionSet();
            set.Add("a=", (k) =&amp;gt; optA = k);
            set.Add("b=", (k) =&amp;gt; optB = k);
            set.Add("h", (k) =&amp;gt; { LongHelp(); done = true; });
            set.Parse(args);
            if (done)
                return;
            if (string.IsNullOrEmpty(optA) || string.IsNullOrEmpty(optB))
            {
                ShortHelp();
                return;
            }
            DoTheJob(optA, optB);

        }

        public virtual void DoTheJob(string optA, string optB)
        {
            //something interesting here
        }

        public virtual void LongHelp()
        {
            Console.Error.WriteLine("Long help here...");
        }

        public virtual void ShortHelp()
        {
            Console.Error.WriteLine("Short help here");
        }
    }
&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
So pretty easy, we provide a non static method Run(), and all the internal function
are declared virtual. This is a five minutes modification we could probably apply
to any other code like this we have. The difference is that we can write some unit
test, lets see how:
&lt;/p&gt;
&lt;pre lang="C#"&gt;        [TestMethod]
        public void ShouldDisplayShortHelp()
        {
            var moq = new Mock&lt;program&gt;
(); moq.CallBase = true; moq.Setup(k=&amp;gt;k.DoTheJob(It.IsAny&lt;string&gt;
(),It.IsAny&lt;string&gt;
())) .Throws(new InvalidProgramException("Should not call")); moq.Object.Run(new string[0]);
moq.Verify(k =&amp;gt; k.ShortHelp()); } [TestMethod] public void ShouldDisplayLongHelp()
{ var moq = new Mock&lt;program&gt;
(); moq.CallBase = true; moq.Setup(k =&amp;gt; k.DoTheJob(It.IsAny&lt;string&gt;
(), It.IsAny&lt;string&gt;
())) .Throws(new InvalidProgramException("Should not call")); moq.Object.Run(new string[]{"-h"});
moq.Verify(k =&amp;gt; k.LongHelp()); } [TestMethod] public void ShouldInvokeWithProperParameters()
{ var moq = new Mock&lt;program&gt;
(); moq.CallBase = true; moq.Setup(k =&amp;gt; k.DoTheJob("p1", "p2")).Verifiable(); moq.Object.Run(new
string[] { "-a=p1","-b=p2" }); moq.Verify(); } 
&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
I used the MoQ library, please note the Callbase set to true, because we are using
the same object for driving and for expect calls. So in conclusion, we achieve a real
unit test of something we sometimes left apart, we did that in memory, and even if
the example is really trivial, the concept can be used in complex scenarios too. What
about testing the inside part of DoTheJob()? well, if a good testing strategy is used,
the internal part should be testable outside somewhere else, here we are&amp;nbsp; proving
we can test the shell.&amp;nbsp; 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.felicepollano.com/aggbug.ashx?id=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2" /&gt;</description>
      <comments>http://www.felicepollano.com/CommentView.aspx?guid=ceb5a0ad-03d4-48e8-81fa-865a8b3e65d2</comments>
      <category>CodeProject</category>
      <category>CSharp</category>
      <category>Programmin</category>
    </item>
    <item>
      <trackback:ping>http://www.felicepollano.com/Trackback.aspx?guid=9b711bcd-fc88-4925-bc5c-9bb23238d5d9</trackback:ping>
      <pingback:server>http://www.felicepollano.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.felicepollano.com/PermaLink.aspx?guid=9b711bcd-fc88-4925-bc5c-9bb23238d5d9</pingback:target>
      <dc:creator>Felice Pollano</dc:creator>
      <wfw:comment>http://www.felicepollano.com/CommentView.aspx?guid=9b711bcd-fc88-4925-bc5c-9bb23238d5d9</wfw:comment>
      <wfw:commentRss>http://www.felicepollano.com/SyndicationService.asmx/GetEntryCommentsRss?guid=9b711bcd-fc88-4925-bc5c-9bb23238d5d9</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I would like to present here a little argument verification library that does not
require you to type any string for specifying the name of the parameter you are checking.
This lets the library faster to use, not intrusive in the actual method code, and
refactor friendly. As a bonus you can use it by just embedding a single file. We can
see below an example, just to get immediately to the point:
</p>
        <script src="https://bitbucket.org/Felice_Pollano/ncontracts/src/fbae7759ea72/NContracts/Demo.cs?embed=t">
        </script>
        <p>
As we can see, there is no magic string at all. All the argument name are guessed
thanks to the metadata contained in the linq Expression we use. For example the method
at <strong>line 14</strong> if called with a null value will report:
</p>
        <p>
          <font face="Courier New" size="2">Value cannot be null.<br />
Parameter name: arg1</font>
        </p>
        <p>
The same happens to the more complex check we do at line 46, when we write:
</p>
        <p>
          <font face="Courier New" size="2">Contract.Expect(() =&gt; array).Meet(a =&gt; a.Length
&gt; 0 &amp;&amp; a.First() == 0);</font>
        </p>
        <p>
We have a complex predicate do meet, described by a lambda, standing that the input
array should have first element zero, and non zero length. Notice that the name of
the parameter is array, but we need to use another name for the argument of the lambda
( in this case I used ‘a’ ), the library is smart enough to <font style="background-color: #ffff00">understand
that ‘a’ actually refers to array</font>, and the error message will report it correctly
if the condition does not meet. Just to clarify, the message in case of failure would
be:
</p>
        <p>
          <font face="Courier New" size="2">Precondition not verified:((array.First() == 0)
AndAlso (ArrayLength(array) &gt; 1))<br />
Parameter name: array</font>
        </p>
        <p>
Well it is not supposed to be a message to an end real user, it is a programmer friendly
message, but such validation error are supposed to be reported to a developer ( an
end user should not see method validation errors at all, should he ? )
</p>
        <p>
Well Meet is a cutting edge function we can use for complex validations. Out of the
box, for simpler cases we have some functions too, as we can see on the IContract
interface definition:
</p>
        <script src="https://gist.github.com/1490175.js?file=IContract.cs">
        </script>
        <p>
An interesting portion of the codebase proposed is the one renaming the parameter
on the lambda expression, to achieve the reported message reflect the correct offending
parameter. It is not so easy because plain string replacement would not work:we can
have a parameter named ‘a’, seen in any place in the expression string representation
and a plain replacement would resolve in a big mess, furthermore Expressions are immutable.
So I found help on <a href="http://stackoverflow.com" target="_blank">StackOverflow</a>,
and a <a href="http://stackoverflow.com/questions/8540954/changing-parameter-name-in-a-lambdaexpression-just-for-display" target="_blank">reply
to this question solved the problem</a>, let see the “Renamer” at work ( Thanks to <a href="http://stackoverflow.com/users/115650/phil-klein" target="_blank">Phil</a> ):
</p>
        <script src="https://gist.github.com/1490197.js?file=PredicateRewriter.cs">
        </script>
        <p>
Basically is a reusable class that take the new name of the parameter and returns
a copy of the input expression with the (single) argument changed.
</p>
        <p>
To improve the library or just use it, please <a href="https://bitbucket.org/Felice_Pollano/ncontracts/overview" target="_blank">follow/check
out the project on Bitbucket</a>, suggestions and comments are always welcome.
</p>
        <img width="0" height="0" src="http://www.felicepollano.com/aggbug.ashx?id=9b711bcd-fc88-4925-bc5c-9bb23238d5d9" />
      </body>
      <title>A single file argument verification library</title>
      <guid isPermaLink="false">http://www.felicepollano.com/PermaLink.aspx?guid=9b711bcd-fc88-4925-bc5c-9bb23238d5d9</guid>
      <link>http://www.felicepollano.com/2011/12/17/ASingleFileArgumentVerificationLibrary.aspx</link>
      <pubDate>Sat, 17 Dec 2011 13:24:25 GMT</pubDate>
      <description>&lt;p&gt;
I would like to present here a little argument verification library that does not
require you to type any string for specifying the name of the parameter you are checking.
This lets the library faster to use, not intrusive in the actual method code, and
refactor friendly. As a bonus you can use it by just embedding a single file. We can
see below an example, just to get immediately to the point:
&lt;/p&gt;
&lt;script src="https://bitbucket.org/Felice_Pollano/ncontracts/src/fbae7759ea72/NContracts/Demo.cs?embed=t"&gt;&lt;/script&gt;
&lt;p&gt;
As we can see, there is no magic string at all. All the argument name are guessed
thanks to the metadata contained in the linq Expression we use. For example the method
at &lt;strong&gt;line 14&lt;/strong&gt; if called with a null value will report:
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New" size="2"&gt;Value cannot be null.&lt;br&gt;
Parameter name: arg1&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
The same happens to the more complex check we do at line 46, when we write:
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New" size="2"&gt;Contract.Expect(() =&amp;gt; array).Meet(a =&amp;gt; a.Length
&amp;gt; 0 &amp;amp;&amp;amp; a.First() == 0);&lt;/font&gt; 
&lt;/p&gt;
&lt;p&gt;
We have a complex predicate do meet, described by a lambda, standing that the input
array should have first element zero, and non zero length. Notice that the name of
the parameter is array, but we need to use another name for the argument of the lambda
( in this case I used ‘a’ ), the library is smart enough to &lt;font style="background-color: #ffff00"&gt;understand
that ‘a’ actually refers to array&lt;/font&gt;, and the error message will report it correctly
if the condition does not meet. Just to clarify, the message in case of failure would
be:
&lt;/p&gt;
&lt;p&gt;
&lt;font face="Courier New" size="2"&gt;Precondition not verified:((array.First() == 0)
AndAlso (ArrayLength(array) &amp;gt; 1))&lt;br&gt;
Parameter name: array&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
Well it is not supposed to be a message to an end real user, it is a programmer friendly
message, but such validation error are supposed to be reported to a developer ( an
end user should not see method validation errors at all, should he ? )
&lt;/p&gt;
&lt;p&gt;
Well Meet is a cutting edge function we can use for complex validations. Out of the
box, for simpler cases we have some functions too, as we can see on the IContract
interface definition:
&lt;/p&gt;
&lt;script src="https://gist.github.com/1490175.js?file=IContract.cs"&gt;&lt;/script&gt;
&lt;p&gt;
An interesting portion of the codebase proposed is the one renaming the parameter
on the lambda expression, to achieve the reported message reflect the correct offending
parameter. It is not so easy because plain string replacement would not work:we can
have a parameter named ‘a’, seen in any place in the expression string representation
and a plain replacement would resolve in a big mess, furthermore Expressions are immutable.
So I found help on &lt;a href="http://stackoverflow.com" target="_blank"&gt;StackOverflow&lt;/a&gt;,
and a &lt;a href="http://stackoverflow.com/questions/8540954/changing-parameter-name-in-a-lambdaexpression-just-for-display" target="_blank"&gt;reply
to this question solved the problem&lt;/a&gt;, let see the “Renamer” at work ( Thanks to &lt;a href="http://stackoverflow.com/users/115650/phil-klein" target="_blank"&gt;Phil&lt;/a&gt; ):
&lt;/p&gt;
&lt;script src="https://gist.github.com/1490197.js?file=PredicateRewriter.cs"&gt;&lt;/script&gt;
&lt;p&gt;
Basically is a reusable class that take the new name of the parameter and returns
a copy of the input expression with the (single) argument changed.
&lt;/p&gt;
&lt;p&gt;
To improve the library or just use it, please &lt;a href="https://bitbucket.org/Felice_Pollano/ncontracts/overview" target="_blank"&gt;follow/check
out the project on Bitbucket&lt;/a&gt;, suggestions and comments are always welcome.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.felicepollano.com/aggbug.ashx?id=9b711bcd-fc88-4925-bc5c-9bb23238d5d9" /&gt;</description>
      <comments>http://www.felicepollano.com/CommentView.aspx?guid=9b711bcd-fc88-4925-bc5c-9bb23238d5d9</comments>
      <category>CodeProject</category>
      <category>CSharp</category>
      <category>Linq</category>
      <category>Recipes</category>
    </item>
  </channel>
</rss>