Tutorial :C#, Lokad.Shared: How to write custom rules to use with Enforce


I am trying out the Lokad Shared Libraries, and it is looking very interesting and useful. I am able to use for example:

Enforce.Arguments(() => arg1, () => arg2);  

to throw an exception if arg1 or arg2 are null. But I would like to check if an IEnumerable has at least one item. I could use:

Enforce.That(someSequence.Count() > 0);  

but that doesn't create a very useful error message. I have tried to look at the Sample code, etc., to find out how to write, and use, a custom rule. But I just can't seem to figure it out!

I have come this far (or short... to be more exact...):

  • I should create a class to collect my rules in.
  • I think I need to somehow create a Lokad.Rules.Rule<T> delegate?
  • Which perhaps need to do something with an IScope, whatever that is....
  • And then somehow use that rule with one of the Enforce methods, although I am not quite sure how...

So to sum up, this is what I want to end up with:

public static void DoStuff<T>(this IEnumerable<T> subjects)  {      Enforce.Argument(() => subjects);      // Somehow in an equally smooth way check that       // subjects contains at least one element        // Do stuff  }  

Anyone able to help?


Asked kind of the same question in a blog post of Rinat Abdullin. Got this answer:

Here's the simplest implementation with the usages:

    public static class EnumerableIs      {          public static void NotEmpty<T>(IEnumerable<T> collection, IScope scope)          {              if (!collection.Any())              {                  scope.Error("Enumerable can't be empty.");              }              scope.ValidateInScope(collection);          }      }        [Test, ExpectedException(typeof(ArgumentException))]      public void Test()      {          IEnumerable<object> t = null;          Enforce.Argument(() => t, EnumerableIs.NotEmpty);      }        [Test, ExpectedException(typeof(ArgumentException))]      public void Test2()      {          var t = new int[0];          Enforce.Argument(() => t, EnumerableIs.NotEmpty);      }        [Test, ExpectedException(typeof(ArgumentException))]      public void Test3()      {          var t = new[] { new object(), null };          Enforce.Argument(() => t, EnumerableIs.NotEmpty);      }  

And this actually do work. The test methods throws exceptions with these messages:

Test1: Object of type 'IEnumerable`1' should not be null. Parameter name: t

Test2: Enumerable can't be empty. Parameter name: t

Test3: Object of type 'Object' should not be null. Parameter name: t.1

Not quite sure where Test1 and Test3 got their messages from though... like, where it checked for that in the NotEmpty<T> method... so I have asked about that...

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »