<?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 - Linq</title>
    <link>http://www.felicepollano.com/</link>
    <description>The official Fatica Labs Blog!</description>
    <language>en-us</language>
    <copyright>Felice Pollano</copyright>
    <lastBuildDate>Mon, 23 Jan 2012 16:05:16 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=93ee5be2-ebc6-427a-9974-679fafe3609e</trackback:ping>
      <pingback:server>http://www.felicepollano.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.felicepollano.com/PermaLink.aspx?guid=93ee5be2-ebc6-427a-9974-679fafe3609e</pingback:target>
      <dc:creator>Felice Pollano</dc:creator>
      <wfw:comment>http://www.felicepollano.com/CommentView.aspx?guid=93ee5be2-ebc6-427a-9974-679fafe3609e</wfw:comment>
      <wfw:commentRss>http://www.felicepollano.com/SyndicationService.asmx/GetEntryCommentsRss?guid=93ee5be2-ebc6-427a-9974-679fafe3609e</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
… without writing a LinqToSomething provider, of course. The <strong>Expression.&lt;Func&lt;T&gt;&gt;</strong> construction
is sometimes a little frightening since we suppose to have to write some complex tree
navigation in order to achieve the expression behavior, but this is not always true,
there is scenarios in which we can use it without any complex tree visit. In this
post we will see some real world examples using this strategy. 
</p>
        <h5>1) <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx" target="_blank">INotifyPropertyChanged</a> without
“magic strings”
</h5>
        <p>
This interface is implemented in its simplest form:
</p>
        <pre lang="C#">public string CustomerName
{
   get
   {
	   return this.customerNameValue;
   }
   set
   {
	   if (value != this.customerNameValue)
	   {
		   this.customerNameValue = value;
		   NotifyPropertyChanged("CustomerName");
	   }
   }
}
</pre>
        <p>
We can leverage Linq.Expression here by this simple base class:
</p>
        <pre lang="C#">class PropertyChangeBase: INotifyPropertyChanged
{
	protected void SignalChanged&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; exp)
	{
		if (exp.Body.NodeType == ExpressionType.MemberAccess)
		{
			var name = (exp.Body as MemberExpression).Member.Name;
			PropertyChanged(this, new PropertyChangedEventArgs(name));
		}
	   else
		   throw new Exception("Unexpected expression");
   }
   #region INotifyPropertyChanged Members
   public event PropertyChangedEventHandler PropertyChanged = delegate { };
   #endregion
}
</pre>
        <p>
By deriving our class from this one, we can easily notify a property change by writing:
</p>
        <pre lang="C#">SignalChanged(()=&gt;CustomerName);


</pre>
        <p>
This allow us to <strong>leverage intellisense, and it is refactoring friendly</strong>,
so we can change the name of our property without pain. The first project I seen using
this technique was <a href="http://caliburnmicro.codeplex.com/" target="_blank">Caliburn
Micro</a>, but I’m not sure is the only one and the first. <a href="http://blog.ploeh.dk/2009/08/06/AFluentInterfaceForTestingINotifyPropertyChanged.aspx" target="_blank">Same
technique is used here to test the INotifyPropertyChange behavior</a>.
</p>
        <h5>2) Argument Verification
</h5>
        <p>
Really similar to the problem above, we want to avoid:
</p>
        <pre lang="C#">static int DivideByTwo(int num) 
{
   // If num is an odd number, throw an ArgumentException.
   if ((num &amp; 1) == 1)
	   throw new ArgumentException("Number must be even", "num");

   // num is even, return half of its value.
   return num / 2;
}


</pre>
        <p>
In this case we are typing NUM, that is the name of the argument, as a literal string
which is bad. We would preferably write something like this:
</p>
        <pre lang="C#">public void DoSomething(int arg1)
{
	Contract.Expect(() =&gt; arg1)
       .IsGreatherThan(0)
       .IsLessThan(100);
;
}
</pre>
        <p>
        </p>
        <p>
That again give us <strong>intellisense and refactoring awareness</strong>. <a href="https://bitbucket.org/Felice_Pollano/ncontracts" target="_blank">You
can find he code for this helper class here</a>, and a brief description <a href="http://www.felicepollano.com/2011/12/17/ASingleFileArgumentVerificationLibrary.aspx" target="_blank">in
this post</a>.
</p>
        <h5>3) The <a href="http://code.google.com/p/moq/" target="_blank">MoQ</a> mocking
library
</h5>
        <p>
The <a href="http://code.google.com/p/moq/" target="_blank">MoQ</a> library is a .NET
library for creating mock objects easy to use that internally leverage Linq.Expression
to achieve such a readable syntax:
</p>
        <pre lang="C#">   mock.Setup(framework =&gt; framework.DownloadExists("2.0.0.0"))
       .Returns(true)
       .AtMostOnce();
</pre>
        <p>
        </p>
        <h5>4) A generic Swap function:
</h5>
        <p>
The simplest way in creating a generic Swap function in c# is:
</p>
        <pre lang="C#">void Swap&lt;T&gt;(ref T a, ref T b)
{
   T temp = a;
   a = b;
   b = temp;
}

</pre>
        <p>
        </p>
        <p>
Unfortunately, this won’t work if we want swap two property of an object, or two elements
of an array. We would like to write something like this:
</p>
        <pre lang="C#">   var t = new Test_() { X = 0, Y = 1 };
   Swapper.Swap(() =&gt; t.X, () =&gt; t.Y);
   Assert.AreEqual(0, t.Y);
   Assert.AreEqual(1, t.X);
</pre>
        <p>
        </p>
        <p>
or with arrays:
</p>
        <pre lang="C#">    int[] array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    Swapper.Swap(() =&gt; array[0], () =&gt; array[1]);
    Assert.AreEqual(2, array[0]);
    Assert.AreEqual(1, array[1]);
</pre>
        <p>
        </p>
        <p>
We can achieve this by a simple helper class using <strong>Linq.Expression</strong>: 
</p>
        <pre lang="C#">public class Swapper
{
        public static void Swap<t>
(Expression&lt;Func&lt;T&gt;&gt; left, Expression&lt;Func&gt;T&gt;&gt; right) { var
lvalue = left.Compile()(); var rvalue = right.Compile()(); switch (left.Body.NodeType)
{ case ExpressionType.ArrayIndex: var binaryExp = left.Body as BinaryExpression; AssignTo(rvalue,
binaryExp); break; case ExpressionType.Call: var methodCall = left.Body as MethodCallExpression;
AssignTo(rvalue, methodCall); break; default: AssignTo(left, rvalue); break; } switch
(right.Body.NodeType) { case ExpressionType.ArrayIndex: var binaryExp = right.Body
as BinaryExpression; AssignTo(lvalue, binaryExp); break; case ExpressionType.Call:
var methodCall = right.Body as MethodCallExpression; AssignTo(lvalue, methodCall);
break; default: AssignTo(right, lvalue); break; } } private static void AssignTo&lt;T&gt;(T
value, MethodCallExpression methodCall) { var setter = GetSetMethodInfo(methodCall.Method.DeclaringType,methodCall.Method.Name);
Expression.Lambda&lt;action&gt;( Expression.Call(methodCall.Object, setter, Join(methodCall.Arguments,
Expression.Constant(value))) ).Compile()(); } private static Expression[] Join(ReadOnlyCollection&lt;expression&gt;
args,Expression exp) { List&lt;expression&gt; exps = new List&lt;expression&gt;();
exps.AddRange(args); exps.Add(exp); return exps.ToArray(); } private static MethodInfo
GetSetMethodInfo(Type target, string name) { var setName = Regex.Replace(name, "get",
new MatchEvaluator((m) =&gt; { return m.Value.StartsWith("g")?"set":"Set"; }) ,RegexOptions.IgnoreCase);
var setter = target.GetMethod(setName); if (null == setter) { throw new Exception("can't
find an expected method named:" + setName); } return setter; } private static void
AssignTo&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; left, T value) { Expression.Lambda&lt;Func&lt;T&gt;&gt;(Expression.Assign(left.Body,
Expression.Constant(value))).Compile()(); } private static void AssignTo&lt;T&gt;(T
value, BinaryExpression binaryExp) { Expression.Lambda&lt;Func&lt;T&gt;&gt;(Expression.Assign(Expression.ArrayAccess(binaryExp.Left,
binaryExp.Right), Expression.Constant(value))).Compile()(); } } 
</t></pre>
        <p>
This code leverages a samples by <a href="https://github.com/takeshik" target="_blank">Takeshi
Kiriya</a>, I just added the ability in handling array to <a href="https://gist.github.com/387230" target="_blank">his
own the original code</a>.
</p>
        <h5>5) Unit testing the presence of an attribute
</h5>
        <p>
          <a href="http://thomasardal.com" target="_blank">Thomas Ardal</a> talks in <a href="http://thomasardal.com/2011/06/28/unit-testing-attribute-decorations/" target="_blank">this
post</a> about how to easily unit test the presence of an attribute on a method of
a class,  useful for example in MVC scenarios, or in others AOP circumstances.
</p>
        <p>
A test leveraging his strategy is written as below:
</p>
        <pre lang="C#">    var controller = new HomeController();
    controller.ShouldHave(x =&gt; x.Index(), typeof(AuthorizeAttribute));

</pre>
        <p>
So we show five different simple application, I hope you find here some inspiration
for your works, and feel free to write about your own ideas and enrich the list.
</p>
        <img width="0" height="0" src="http://www.felicepollano.com/aggbug.ashx?id=93ee5be2-ebc6-427a-9974-679fafe3609e" />
      </body>
      <title>(5) Interesting uses of Linq.Expression</title>
      <guid isPermaLink="false">http://www.felicepollano.com/PermaLink.aspx?guid=93ee5be2-ebc6-427a-9974-679fafe3609e</guid>
      <link>http://www.felicepollano.com/2012/01/23/5InterestingUsesOfLinqExpression.aspx</link>
      <pubDate>Mon, 23 Jan 2012 16:05:16 GMT</pubDate>
      <description>&lt;p&gt;
… without writing a LinqToSomething provider, of course. The &lt;strong&gt;Expression.&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt;&lt;/strong&gt; construction
is sometimes a little frightening since we suppose to have to write some complex tree
navigation in order to achieve the expression behavior, but this is not always true,
there is scenarios in which we can use it without any complex tree visit. In this
post we will see some real world examples using this strategy. 
&lt;/p&gt;
&lt;h5&gt;1) &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx" target="_blank"&gt;INotifyPropertyChanged&lt;/a&gt; without
“magic strings”
&lt;/h5&gt;
&lt;p&gt;
This interface is implemented in its simplest form:
&lt;/p&gt;
&lt;pre lang="C#"&gt;public string CustomerName
{
   get
   {
	   return this.customerNameValue;
   }
   set
   {
	   if (value != this.customerNameValue)
	   {
		   this.customerNameValue = value;
		   NotifyPropertyChanged("CustomerName");
	   }
   }
}
&lt;/pre&gt;
&lt;p&gt;
We can leverage Linq.Expression here by this simple base class:
&lt;/p&gt;
&lt;pre lang="C#"&gt;class PropertyChangeBase: INotifyPropertyChanged
{
	protected void SignalChanged&amp;lt;T&amp;gt;(Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; exp)
	{
		if (exp.Body.NodeType == ExpressionType.MemberAccess)
		{
			var name = (exp.Body as MemberExpression).Member.Name;
			PropertyChanged(this, new PropertyChangedEventArgs(name));
		}
	   else
		   throw new Exception("Unexpected expression");
   }
   #region INotifyPropertyChanged Members
   public event PropertyChangedEventHandler PropertyChanged = delegate { };
   #endregion
}
&lt;/pre&gt;
&lt;p&gt;
By deriving our class from this one, we can easily notify a property change by writing:
&lt;/p&gt;
&lt;pre lang="C#"&gt;SignalChanged(()=&amp;gt;CustomerName);


&lt;/pre&gt;
&lt;p&gt;
This allow us to &lt;strong&gt;leverage intellisense, and it is refactoring friendly&lt;/strong&gt;,
so we can change the name of our property without pain. The first project I seen using
this technique was &lt;a href="http://caliburnmicro.codeplex.com/" target="_blank"&gt;Caliburn
Micro&lt;/a&gt;, but I’m not sure is the only one and the first. &lt;a href="http://blog.ploeh.dk/2009/08/06/AFluentInterfaceForTestingINotifyPropertyChanged.aspx" target="_blank"&gt;Same
technique is used here to test the INotifyPropertyChange behavior&lt;/a&gt;.
&lt;/p&gt;
&lt;h5&gt;2) Argument Verification
&lt;/h5&gt;
&lt;p&gt;
Really similar to the problem above, we want to avoid:
&lt;/p&gt;
&lt;pre lang="C#"&gt;static int DivideByTwo(int num) 
{
   // If num is an odd number, throw an ArgumentException.
   if ((num &amp;amp; 1) == 1)
	   throw new ArgumentException("Number must be even", "num");

   // num is even, return half of its value.
   return num / 2;
}


&lt;/pre&gt;
&lt;p&gt;
In this case we are typing NUM, that is the name of the argument, as a literal string
which is bad. We would preferably write something like this:
&lt;/p&gt;
&lt;pre lang="C#"&gt;public void DoSomething(int arg1)
{
	Contract.Expect(() =&amp;gt; arg1)
       .IsGreatherThan(0)
       .IsLessThan(100);
;
}
&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
That again give us &lt;strong&gt;intellisense and refactoring awareness&lt;/strong&gt;. &lt;a href="https://bitbucket.org/Felice_Pollano/ncontracts" target="_blank"&gt;You
can find he code for this helper class here&lt;/a&gt;, and a brief description &lt;a href="http://www.felicepollano.com/2011/12/17/ASingleFileArgumentVerificationLibrary.aspx" target="_blank"&gt;in
this post&lt;/a&gt;.
&lt;/p&gt;
&lt;h5&gt;3) The &lt;a href="http://code.google.com/p/moq/" target="_blank"&gt;MoQ&lt;/a&gt; mocking
library
&lt;/h5&gt;
&lt;p&gt;
The &lt;a href="http://code.google.com/p/moq/" target="_blank"&gt;MoQ&lt;/a&gt; library is a .NET
library for creating mock objects easy to use that internally leverage Linq.Expression
to achieve such a readable syntax:
&lt;/p&gt;
&lt;pre lang="C#"&gt;   mock.Setup(framework =&amp;gt; framework.DownloadExists("2.0.0.0"))
       .Returns(true)
       .AtMostOnce();
&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;h5&gt;4) A generic Swap function:
&lt;/h5&gt;
&lt;p&gt;
The simplest way in creating a generic Swap function in c# is:
&lt;/p&gt;
&lt;pre lang="C#"&gt;void Swap&amp;lt;T&amp;gt;(ref T a, ref T b)
{
   T temp = a;
   a = b;
   b = temp;
}

&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
Unfortunately, this won’t work if we want swap two property of an object, or two elements
of an array. We would like to write something like this:
&lt;/p&gt;
&lt;pre lang="C#"&gt;   var t = new Test_() { X = 0, Y = 1 };
   Swapper.Swap(() =&amp;gt; t.X, () =&amp;gt; t.Y);
   Assert.AreEqual(0, t.Y);
   Assert.AreEqual(1, t.X);
&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
or with arrays:
&lt;/p&gt;
&lt;pre lang="C#"&gt;    int[] array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    Swapper.Swap(() =&amp;gt; array[0], () =&amp;gt; array[1]);
    Assert.AreEqual(2, array[0]);
    Assert.AreEqual(1, array[1]);
&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
We can achieve this by a simple helper class using &lt;strong&gt;Linq.Expression&lt;/strong&gt;: 
&lt;/p&gt;
&lt;pre lang="C#"&gt;public class Swapper
{
        public static void Swap&lt;t&gt;
(Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; left, Expression&amp;lt;Func&amp;gt;T&amp;gt;&amp;gt; right) { var
lvalue = left.Compile()(); var rvalue = right.Compile()(); switch (left.Body.NodeType)
{ case ExpressionType.ArrayIndex: var binaryExp = left.Body as BinaryExpression; AssignTo(rvalue,
binaryExp); break; case ExpressionType.Call: var methodCall = left.Body as MethodCallExpression;
AssignTo(rvalue, methodCall); break; default: AssignTo(left, rvalue); break; } switch
(right.Body.NodeType) { case ExpressionType.ArrayIndex: var binaryExp = right.Body
as BinaryExpression; AssignTo(lvalue, binaryExp); break; case ExpressionType.Call:
var methodCall = right.Body as MethodCallExpression; AssignTo(lvalue, methodCall);
break; default: AssignTo(right, lvalue); break; } } private static void AssignTo&amp;lt;T&amp;gt;(T
value, MethodCallExpression methodCall) { var setter = GetSetMethodInfo(methodCall.Method.DeclaringType,methodCall.Method.Name);
Expression.Lambda&amp;lt;action&amp;gt;( Expression.Call(methodCall.Object, setter, Join(methodCall.Arguments,
Expression.Constant(value))) ).Compile()(); } private static Expression[] Join(ReadOnlyCollection&amp;lt;expression&amp;gt;
args,Expression exp) { List&amp;lt;expression&amp;gt; exps = new List&amp;lt;expression&amp;gt;();
exps.AddRange(args); exps.Add(exp); return exps.ToArray(); } private static MethodInfo
GetSetMethodInfo(Type target, string name) { var setName = Regex.Replace(name, "get",
new MatchEvaluator((m) =&amp;gt; { return m.Value.StartsWith("g")?"set":"Set"; }) ,RegexOptions.IgnoreCase);
var setter = target.GetMethod(setName); if (null == setter) { throw new Exception("can't
find an expected method named:" + setName); } return setter; } private static void
AssignTo&amp;lt;T&amp;gt;(Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; left, T value) { Expression.Lambda&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt;(Expression.Assign(left.Body,
Expression.Constant(value))).Compile()(); } private static void AssignTo&amp;lt;T&amp;gt;(T
value, BinaryExpression binaryExp) { Expression.Lambda&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt;(Expression.Assign(Expression.ArrayAccess(binaryExp.Left,
binaryExp.Right), Expression.Constant(value))).Compile()(); } } 
&lt;/t&gt;
&lt;/pre&gt;
&lt;p&gt;
This code leverages a samples by &lt;a href="https://github.com/takeshik" target="_blank"&gt;Takeshi
Kiriya&lt;/a&gt;, I just added the ability in handling array to &lt;a href="https://gist.github.com/387230" target="_blank"&gt;his
own the original code&lt;/a&gt;.
&lt;/p&gt;
&lt;h5&gt;5) Unit testing the presence of an attribute
&lt;/h5&gt;
&lt;p&gt;
&lt;a href="http://thomasardal.com" target="_blank"&gt;Thomas Ardal&lt;/a&gt; talks in &lt;a href="http://thomasardal.com/2011/06/28/unit-testing-attribute-decorations/" target="_blank"&gt;this
post&lt;/a&gt; about how to easily unit test the presence of an attribute on a method of
a class,&amp;nbsp; useful for example in MVC scenarios, or in others AOP circumstances.
&lt;/p&gt;
&lt;p&gt;
A test leveraging his strategy is written as below:
&lt;/p&gt;
&lt;pre lang="C#"&gt;    var controller = new HomeController();
    controller.ShouldHave(x =&amp;gt; x.Index(), typeof(AuthorizeAttribute));

&lt;/pre&gt;
&lt;p&gt;
So we show five different simple application, I hope you find here some inspiration
for your works, and feel free to write about your own ideas and enrich the list.
&lt;/p&gt;
&gt;&lt;img width="0" height="0" src="http://www.felicepollano.com/aggbug.ashx?id=93ee5be2-ebc6-427a-9974-679fafe3609e" /&gt;</description>
      <comments>http://www.felicepollano.com/CommentView.aspx?guid=93ee5be2-ebc6-427a-9974-679fafe3609e</comments>
      <category>C#</category>
      <category>CodeProject</category>
      <category>Linq</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>