NCover Code Quality Metrics

Code Coverage Analysis is very crucial to writing better code and improving quality of software applications.Code Coverage Analysis Tools helps us in automated analysis of code and pinpoints the untested lines of code or areas which has become extremely complex and prone to error/performance bottlenecks.In this post I will discuss about NCover – a leading .NET Code Coverage Tool.

NCover tracks the following code metrices:

  • Symbol Coverage – Symbols Coverage measures how many sequence points are executed within the code.Sequence points are where a VS Studio Debugger highlights during step debugging a code.This avoids the chance of any partial execution but there can be single statement which can be executed multiple times e.g. a for loop.To test the results I have used the following block of code:
class Program
{
static void Main(string[] args)
{
Test(false);

Console.Read();
}
static void Test(bool x)
{

if (x)
{
Console.WriteLine("1");
}
else
{
Console.WriteLine("2");
}

}
}

Here NCover gives me the following output:

It shows the maximum visit count against each line i.e the maximum number of times the line can be executed.

The Symbol Coverage of the method Test is (3/4) i.e 75% .Here we have 4 sequence points marked as 1,2,3,4 in the figure above in blue.But in this code the only three sequence points can be possibly executed as the condition if(x) will always evaluate to false i.e the statement highlighted in red will be never executed.

  • Branch Coverage – Branch Coverage takes into consideration the number of basic blocks executed in the control flow graph.Branch Coverage provides a little higher level view than symbol coverage as it takes into consideration the if blocks which were evaluated to true as well as false.However the branch coverage statistics is generated based on IL opcodes and might not match with what we understand from source code.For the method Test we have 2 basic blocks in the Control Flow Graph and Branch Coverage is 100%.
  • Cyclomatic Complexity – This is the number of independent path from start to end of execution.For the method Test cyclomatic complexity will be 3
  • Method Coverage – This is a module level metrics and is the measure of actual number of methods executed vs actual number of methods in the module.In this it should be 100% but NCover shows 66.67% as it considers the constructor of Program class as one unused method.
Posted in Framework & Libraries | Leave a comment

Code Contract in .NET

Code Contracts is Microsoft’s implementation of Design by Contract(DbC) philosophy.It has been released as a MSDN Dev Labs project and will be a part of .NET Framework 4.0 hence present in VS 2010 Beta 1.Before getting into details of Code Contracts let us quickly cover DbC to set things in context.

The concept of DbC was proposed by Bertrand Meyer and was supported by his programming language Eiffel.In real world when two parties are working together, the contract between the two specifies a set of rules and regulations both must follow to ensure smooth operation.Similarly in object oriented parlance when one object is passing message (invoking method) to another there should be a fixed set of rules to ensure correctness of the operation.DbC focuses on clean documentation and verification of these contracts.The three key ingredients of this contract are:

  • Precondition – This refers to conditions that must be satisfied for the method to be invoked.These are mostly conditions that method arguments must satisfy.
  • Postcondition – This refers to the conditions that must be satisfied after the method has finished execution.These are mostly conditions to be satisfied by the return values.
  • Object Invariant – These are conditions that must hold true for the class before and after the method call.A common textbook example will be a BankAccount class with a property AccountNumber, where the condition AccountNumber!=null must always hold true.

The classes/attributes related to Code Contracts are all present in the System.Diagnostics.Contractsnamespace.Let us consider the following example:

public class BankAccount
 {
 private double balance;
 public string AccountNumber{get;set;}

 public double Balance
 {
 get
 {
 Contract.Ensures(balance > 0, "Balance Cannot Be Negative");
 return balance;
 }
 set
 {
 balance = value;
 }
 }

 public void Withdraw(double amount)
 {
 Contract.Requires(amount > 0, "Deposited Amount Cannot Be Negative");
 Balance -= amount;
 }
 [ContractInvariantMethod]
 public void CheckInvariants()
 {
 Contract.Invariant(this.AccountNumber !=null, "Account Number Cannot Be Null");
 }

 }

While withdrawing amount from an account the amount always has to be positive.So in the method Withdraw we are using Contract.Require to check this precondition.

The account balance can never be negative so in the getter block of Balance we are checking the postcondition using Contract.Ensures.

This BankAccount class has a AccountNumber which cannot be null for any valid banking operation.So this is an invariant.To check the invariants we need to separate method checking the individual conditions using Contract.Invariant method and this method needs to be marked with ContractInvariantMethod attribute.Here the method CheckInvariants method is doing this task.

After executing this method in VS2010 with values breaking the contract I found that no error message was shown.What happened?Are we missing something?Yes.We have to setup the Code Analysis tab in project properties.

Now an assertion error message is shown whenever the contract is broken.

Here I am using Visual Studio Standard Edition so only Runtime contract checking can be done.However with VS Team Edition static checking of the code contracts is also possible.

Apart from verifying the contracts another key aspect of DbC documentation.This can be done by checking the “Build a Contract Reference Assembly” and “Emit contracts into XML doc file” checkboxes in Code Analysis tab.Also the “XML Documentation File” in Build Tab needs to be checked.On compilation this will generate a XML file with name <<assemblyname>>.xml.In this XML contracts information is documented as shown below:

<?xml version="1.0"?>
<doc>
 <assembly>
 <name>CodeContractsDemo</name>
 </assembly>
 <members>
 <member name="T:CodeContractsDemo.BankAccount">
 <invariant description="Account Number Cannot Be Null">this.AccountNumber !=null</invariant>
 </member>
 <member name="M:CodeContractsDemo.BankAccount.Withdraw(System.Double)">
 <requires description="Deposited Amount Cannot Be Negative">amount > 0</requires>
 </member>
 <member name="P:CodeContractsDemo.BankAccount.Balance">
 <getter>
 <ensures description="Balance Cannot Be Negative">balance > 0</ensures>
 </getter>
 </member>
 </members>
</doc>
Posted in Framework & Libraries | Leave a comment

Parallel Computing in .NET 4.0 – Overview

In the last 20-30 years we have seen a tremendous growth in processing power where the average speed of the processor has increased year by year.But over the last couple of years we are observing a shift in this trend.Instead of increase in processor speed the number of processors on a single chip are increasing.We are very fast moving from dual core to quad core to eight core processors.So we are gradually shifting towards a multicore processor architecture.But most of our present applications are still of sequential nature and not capable of leveraging the performance benefits offered by multicore processors.This is because parallel/concurrent programming involves threads,locks,mutexes etc. which are difficult to program and also hard to maintain because of lack of tools for profiling and debugging those applications.So we needed a set of libraries and tools which

  • Makes concurrent programming easier where developers need not care much details of threads and locks.
  • Makes profiling and debugging concurrent applications easier
  • Enables the applications to scale up without any code as number of cores increases
  • Allows existing applications to be easily parallelized.

Here comes Parallel Extensions in .NET 4.0 which provides a set of libraries and tools to achieve the above mentioned objectives.This supports two paradigms of parallel computing

  • Data Parallelism – This refers to dividing the data across multiple processors for parallel execution.e.g we are processing an array of 1000 elements we can distribute the data between two processors say 500 each.This is supported by the Parallel LINQ (PLINQ) in .NET 4.0
  • Task Parallelism – This breaks down the program into multiple tasks which can be parallelized and are executed on different processors.This is supported by Task Parallel Library (TPL) in .NET 4.0

A high level view of this framework is shown below:

The key components are:

  • Coordinated Data Structures (CDS) – These are set of APIs added to the BCL which provides a set of thread safe collection classes, lightweight synchronization classes and lazy initializers.The concurrent collections are added in the new System.Collections.Concurrent namespace and others are added to the System.Threading namespace.These are cross cutting components used by the other three as shown in the figure above.
  • Scheduler – This is a new Scheduler which is capable of querying the OS and get information about the number of processors, memory architecture of the processors (i.e UMA/NUMA) and accordingly schedule the tasks.This component is used by the Task Parallel Library for task scheduling.This is the component which makes the applications scalable with growing number of cores in the machine.
  • Task Parallel Library (TPL) – These are set of APIs present in System.Threading and System.Threading.Task namespace which provides facilities for Task Parallelism.The System.Threading.Parallel class provides a method Invoke which can accept an array of delegates thus enabling parallel execution of multiple methods.The methods Parallel.For and Parallel.ForEach enable parallel execution of loops thus supporting data parallelism.These are used by PLINQ.
  • Parallel LINQ (PLINQ) – PLINQ provides a parallel implementation of LINQ and supports all the standard query operators.This is achieved by the System.Linq.ParallelEnumerable class which provides a set of extension methods on IEnumerable interface.Developers can opt-in for parallelism by invoking the AsParallel method of ParallelEnumerable class on the data source.Using PLINQ we can combine sequential and parallel queries and it also supports ordered/unordered execution.
Posted in Framework & Libraries | Leave a comment

Coordination Data Structures – BlockingCollections

In my last post about Parallel Extensions in .NET I had mentioned about the Coordination Data Structure(CDS) , the new set of thread safe collections that are introduced in the System.Collections.Concurrent namespace.In this post we will discuss about the new BlockingCollection<T> class which is introduced to cater for the standard Producer/Consumer pattern.Producer/Consumer pattern is the most common concurrent programming pattern.Here we have producers and consumers sharing a common buffer, producer is adding items to the buffer and consumer is removing them.The main challenge is to ensure that producer does not add item when the buffer is full and similarly consumer does not try to remove item when buffer is empty.

The class BlockingCollection implements the new interaface

  • System.Collections.Concurrent.IProducerConsumerCollection<T>
  • System.Collections.Generic.IEnumerable<T>
  • System.Collections.Generic.ICollection<T>.

IProducerConsumerCollection<T> specifies the following two operations:

  • bool TryAdd(T item) – This method tries to add an item to the collection and returns false if the collection is full
  • bool TryTake(out T item) – This method tries to take an item from the collection and returns false if the collection is empty.

Let us consider the following example:

<pre>

class Program
    {
        static BlockingCollection buffer = new BlockingCollection
<int/>(10);
        static void Main(string[] args)
        {
            Produce();
            Consume();
            Console.Read();
        }
        private static void Produce()
        {
            Console.WriteLine("Produce::Invoked");
            for (int i = 0; i &lt; 11; i++)
            {
                if (buffer.TryAdd(i)) Console.WriteLine("Added " + i);
                else Console.WriteLine("Could Not Add");
            }
        }
        private static void Consume()
        {
            int j = 0;
            Console.WriteLine("Consume::Invoked");
            for (int i = 0; i &lt; 11; i++)
            {
                if (buffer.TryTake(out j)) Console.WriteLine("Taken " + j);
                else Console.WriteLine("Could Not Take");
            }
        }
    }
</pre>

Here we have a BlockingCollection of capacity 2and we are trying to add and remove 3 items to the collection.The add/take 3rd item will return false and program output will be:

Produce::Invoked 
Added 0 
Added 1 
Could Not Add 
Consume::Invoked 
Taken 0 
Taken 1 
Could Not Take

So TryTake and TryAdd are non blocking methods and if the Collection is full/empty it allows the producer/consumer to proceed with it’s own job.Let us change the code a bit as shown below.Here instead of TryAdd and TryTake we are using Add and Take methods of BlockingCollection class.

<pre>
   class Program
    {
        static BlockingCollection
<int/> buffer = new BlockingCollection
<int/>(2);
        static void Main(string[] args)
        {
            Produce();
            Consume();
            Console.Read();
        }
        private static void Produce()
        {
            Console.WriteLine("Produce::Invoked");
            for (int i = 0; i &lt; 3; i++)
            {
                //if (buffer.TryAdd(i)) Console.WriteLine("Added " + i);
                //else Console.WriteLine("Could Not Add");

                buffer.Add(i);
            }
        }
        private static void Consume()
        {
            int j = 0;
            Console.WriteLine("Consume::Invoked");
            for (int i = 0; i &lt; 3; i++)
            {
                //if (buffer.TryTake(out j)) Console.WriteLine("Taken " + j);
                //else Console.WriteLine("Could Not Take");
                buffer.Take();
            }
        }
    }
</pre>

Here the program output will be:

Produce::Invoked

This is because after 2 elements the method Add is trying to Add the 3 rd item and finds that the buffer is full.So it blocks the producer thread and waits for the buffer capacity to reduce.This will be interesting to observe where Producer/Consumer is running in two different threads as shown below:

<pre>
   class Program
    {
        static BlockingCollection buffer = new BlockingCollection
<int/>(2);
        static void Main(string[] args)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(Produce));
            ThreadPool.QueueUserWorkItem(new WaitCallback(Consume));

            Console.Read();
        }
        private static void Produce(object obj)
        {
            Console.WriteLine("Produce::Invoked");
            for (int i = 0; i &lt; 3; i++)
            {
                //if (buffer.TryAdd(i)) Console.WriteLine("Added " + i);
                //else Console.WriteLine("Could Not Add");
                Thread.Sleep(1000);
                buffer.Add(i);
                Console.WriteLine("Item Added::" + i);

            }
        }
        private static void Consume(object obj)
        {
            int j = 0;
            Console.WriteLine("Consume::Invoked");
            for (int i = 0; i &lt; 3; i++)
            {
                //if (buffer.TryTake(out j)) Console.WriteLine("Taken " + j);
                //else Console.WriteLine("Could Not Take");
                Console.WriteLine("Item Taken::" + buffer.Take());
            }
        }
    }
</pre>

Here we have slowed up the producer using Thread.Sleep.So the consumer thread is blocked by Take method until producer adds one item in the buffer.That’s why program output is :

Produce::Invoked 
Consume::Invoked 
Item Added::0 
Item Taken::0 
Item Added::1 
Item Taken::1 
Item Added::2 
Item Taken::2

Posted in Framework & Libraries | Leave a comment

Parallel For Loop

In my earlier post on Parallel Programming I have explained about Task and Data Parallelism.In this post we will go into a little more deep into the API and discuss about Parallel For loop in .NET Framework 4.0.The static method For of class System.Threading.Tasks.Parallel class allows us to execute for loops where several iterations might run in parallel.There are couple of overloads of Parallel.For.We will discuss about the simplest one here as shown below:

public static ParallelLoopResult For(int fromInclusive,int toExclusive,Action<int> body)

  • fromInclusive – This is the start index (inclusive)
  • toExclusive – This is the end index (exclusive)
  • body – This is the delegate of type Action<int>that will be invoked once per iteration.The input to this delegate is the counter of the iteration.

Simple implementation of Parallel.For is shown below:

Parallel.For(0, arr.Length, i =>
{
arr[i] = arr[i] + 1;
}
);

I really wanted to test how parallel for loop is behaving compared to simple sequential for loops.I used the code shown below:

private static void ParallelForLoop(int[] arr)
{
     Parallel.For(0, arr.Length, i =>
         {
             arr[i] = arr[i] + 1;
         }
     );
}
private static void SequentialForLoop(int[] arr)
{
     for (int i = 0; i < arr.Length; i++)
     {
         arr[i] = arr[i] + 1;
     }
}

static void Main()
      {

          Stopwatch sw = new Stopwatch();

          int[] arr = new int[100000];
          sw.Start();
          SequentialForLoop(arr);
          sw.Stop();
          Console.WriteLine(sw.ElapsedMilliseconds);

          arr = new int[100000];
          sw.Reset();
          sw.Start();
          ParallelForLoop(arr);
          sw.Stop();
          Console.WriteLine(sw.ElapsedMilliseconds);

          Console.ReadKey();
      }

But to my surprise in my dual core PC Parallel.For was taking more time compared to the sequential loop.Why So?

Regarding Parallel.For, the bad performance you experienced is due to two issues.  First, each iteration requires a delegate invocation.  Usually, this is insignificant, but when the loop body is small, it becomes more noticeable.  Second, Parallel.For’s partitioning scheme is designed for fine-grained load-balancing of larger, more complex workloads.  Each thread worker grabs a relatively small number of iterations to process at a time; this requires synchronization that is, again, more significant when the loop body is small and constant.  Both of these issues cause Parallel.For to perform badly in the following scenario, where parallelism can yield benefit: large number of iterations, small loop body.  Your example (one million add-store operations) fits this category exactly.
We have recently done something about this.  The solution (as you’ve realized in your hand-coded approach) is to use range partitioning and have each worker thread take a much larger chunk of the iteration range.

So I wrote another method where I partitioned the array data based on number processors and invoked Parallel.For iterating once for each partition.This resulted in reduced number of delegate invocation.

private static void ParallelForWithRange(int[] arr)
  {
      int partitions = System.Environment.ProcessorCount;
      int increment = arr.Length / partitions;

      Parallel.For(0, partitions, i =>
      {
          int a = i * increment;
          int b = (i == partitions - 1) ? arr.Length : a + increment;

          for (int j = a; j < b; j++)
          {
              arr[j] = arr[j] + 1;
          }

      });
  }

Now got the desired result.

One point I skipped earlier is the return value of Parallel.For, it is a structure ParallelLoopResult.The IsCompleted property of this structure returns true if all the iterations are successfully completed.

We will discuss about this in more details in next post along with stopping/breaking from a loop.

Posted in Framework & Libraries | Leave a comment

Parallel For Loop : Break Or Stop

In my last post I had discussed about Parallel For loops and in what situation it can be useful compared to a sequential loop.In this post we will take a look at how to break or exit from a Parallel For loop.We can use the break or exit keywords for this purpose as Parallel For loop is not programming language construct but a method of the System.Threading.Tasks.Parallel class.To break or exit we need to use any one of the following overloads of Parallel.For method:

  • public static ParallelLoopResult For(int fromInclusive,int toExclusive,Action<int, ParallelLoopState> body)
  • public static ParallelLoopResult For(long fromInclusive,long toExclusive,Action<long, ParallelLoopState> body)
  • public static ParallelLoopResult For(int fromInclusive,int toExclusive,ParallelOptions parallelOptions,Action<int, ParallelLoopState> body)
  • public static ParallelLoopResult For(long fromInclusive,long toExclusive,ParallelOptions parallelOptions,Action<long, ParallelLoopState> body)

The key here is the ParallelLoopState that is passed as input to the Action delegate.ParallelLoopState class has two methods:

  • Break – This method notifies that all iterations higher than the iteration from which Break is called will be stopped however the lower iterations will be still completed.
  • Stop – This method notifies that all the iterations will be stopped.

Let’s consider the following code sample:

static void Main(string[] args)
{
    List<int> list = new List<int>(); 

    Console.WriteLine("Loop Start");
    Parallel.For(0, 10000, (i, loopState) =>
        {
            if (i == 850)
            {
                loopState.Break();
            } 

            list.Add(i);
        }
    );
    Console.WriteLine("Loop End");
    foreach (int i in list)
    {
        Console.WriteLine(i);
    }
    Console.Read();
}

Here the output will show that last entry in the loop is always 850 or less.This is because Break is called at iteration 850 no iteration higher than 850 is executed but lower than 850 are still completed.

Now let’s tweak the above code a bit and use it for Stop as shown below:

static void Main(string[] args)
      {
          List<int> list = new List<int>(); 

          Console.WriteLine("Loop Start");
          Parallel.For(0, 10000, (i, loopState) =>
              {
                  if (i == 850)
                  {
                      loopState.Stop();
                  } 

                  list.Add(i);
              }
          );
          Console.WriteLine("Loop End");
          foreach (int i in list)
          {
              Console.WriteLine(i);
          }
          Console.Read();
      }

Here in some of the runs you might see that last entry in List<int> is higher than 850.

However after Stop or Break is called there might be some of the threads still running for sometime.Here we can use the IsStopped property of ParallelLoopState class to check if the loop is stopped by some other iteration.

That’s all for now.In the next post we will take a look at exception handling in Parallel For loops.

Posted in Framework & Libraries | Leave a comment

A Deeper Look Into Javascript – Part I

Javascript has been around since the early days of Web and is already embedded into the millions of web pages for performing client(browser) side actions.But because of some reason it was never taken too seriously in the initial days compared to the languages that were used for server side programming.Back in 2000 when I started my programming career, Javascript was a language that you need not learn much , use it for some validations, copy/paste as much as you can….With the gradual advent of Web 2.0 concept and AJAX as a technology it was very clear that you cannot neglect javascript and it is here to stay, as we need more interactive and responsive web applications.

The “Java” in javascript is really a misnomer and misguiding.Javascript has absolutely nothing to do with Java.It was developed by Netscape as “LiveScript” and was later renamed to javascript.Later javascript was standardized by ECMA.The greatest power of Javascript is it’s simplicity and ease of use.Along with this it has the following powerful language features:

  • Object Oriented Prototype Based – Javascript is an object oriented language but differs from other OO languages like C# or Java in the fact that it does support class based object orientation.In class based object orientation we have classes defining the attributes and behavior and objects are unique instances of those classes.In prototype based languages there is no notion of classes, everything is an object.For reuse/inheritance we need to create copy of an existing object and alter it’s properties and behavior.This is very flexible as compared to class based inheritance where you might end up designing a rigid class hierarchy.
  • Dynamic – Javascript is a dynamically typed language and type of the variables are determined at runtime based on value it is holding.
  • Functional – Javascript treats functions as objects and supports higher order functions,anonymous methods and closures.
  • Imperative and Structured – Javascript allows to write programs in imperative and procedural style as well.

Javascript needs a runtime to execute and interact with HTML DOM.This is where the javascript engines embedded in the browsers come into picture.Initially these were not much efficient and error prone.But over time the javascript engines have improved.Lately the interest and enthusiasm shown by the OEMs for improving javascript performance in their browsers is a positive sign.May be we will see lots of improvement in recent times.The javascript engines of the major browsers are listed below:

  • Chrome V8 Javascript Engine – V8 is a high performance javascript engine which compiles javascript source directly to machine code bypassing any byte code or intermediate interpreter.V8 promises faster property access using a class transition technique,direct machine code generation and a generational garbage collection.
  • Firefox SpiderMonkey – SpiderMonkey provides a compiler which compiles javascript source to byte code, interpreter which consumes the byte code and a mark and sweep garbage collector.
  • IE JScript Engine – This has a byte code interpreter with a mark and sweep garbage collector.
  • Safari Nitro – Safari’s Nitro is based on WebKit’s SquirrelFish. It is a high performance byte code interpreter.SquirrelFish Extreme comes with byte code optimizations, Context Threading, a property cache, and a regular expression JIT.

This is good to start with.Next post onwards we start exploring the individual language features of javascript.

Posted in Programming & Languages | Leave a comment

Microsoft AJAX Library Preview 6 & DataView

Yesterday I came to know about Microsoft AJAX Library Preview 6 from Scott Guthrie’s post.I have not taken look into this library earlier.The rich set of JavaScript API looked very impressive to me.I became a fan of DataView control very quickly.I am sure this will be extremely useful and productive for ASP.NET developers who are conversant with the concept of server controls like DataGrid/GridView.In this post we will take a look into how to use this control.As the support for  imperative programming is added in Preview 6 I will be sticking to that style only.

First we need to add the following script reference in our page:

<script src="Scripts/MicrosoftAjax/start.debug.js" type="text/javascript"></script>

This is the reference to the Client Script Loader.This component loads all the client scripts required by the page automatically and in parallel.It makes sure that each script is loaded only once and also supports lazy loading i.e. loading the scripts when they are required.

I have also added the following style:

    .sys-template { visibility:hidden; display:none; }

This style is used by the AJAX Library (MicrosoftAjaxTemplates.js) to decide whether a control is a templated control or not.The initial html I have used is shown below:

<body xmlns:sys="javascript:Sys">
    <form id="form1" runat="server">
    <div>
        <h4>Delivery Header</h4>
        <table id="tblOrders" class="sys-template" border="1">
            <tr>
                <td>
                </td>
                <td>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>

The intention here is to display the Delivery Order information in this table and data will be provided by ASMX Script Service as shown below:

public class Delivery
{
    public string OrderNumber { get; set; }
    public string DeliveryDate { get; set; }
    public DeliveryDetail[] DeliveryDetails { get; set; }
}
public class DeliveryDetail
{
    public string SKU { get; set; }
    public string Quantity { get; set; }
}

  [WebMethod]
   public Delivery[] GetDeliveryItems()
   {

     ...........

   }

Now how to populate data in this table.One way is to invoke the script service and then loop through the object and dynamically add rows in the table.But now we have another better way as shown in the script block below:

<script type="text/javascript">
   Sys.require([Sys.components.dataView, Sys.scripts.WebServices]); 

   Sys.onReady(function() {
       var master = Sys.create.dataView("#tblOrders",
            { 

                dataProvider: "/Services/AJAXPreview6Demos.asmx",
                fetchOperation: "GetDeliveryItems",
                autoFetch: "true",
                initialSelectedIndex: 0
            }
        ); 

   });
</script>

The call to Sys.Require ensures that scripts required for proper functioning of Sys.components.dataView, Sys.scripts.WebServices is properly loaded.

Sys.onReady is invoked when DOM is properly loaded and ready quite similar to jQuery ready event.

Sys.create.dataView creates an instance of the DataView control on the table tblOrders.As shown above we have to just specify the script service url (dataProvider) and webmethod (fetchOperation).The autoFetch property determines whether data will be populated by default or not.

We need to add following lines of code in the table markup as shown below:

<table id="tblOrders" class="sys-template" border="1">
    <tr class="row">
        <td>
            {{OrderNumber}}
        </td>
        <td>
            {{DeliveryDate}}
        </td>
    </tr>
</table>

{{OrderNumber}} means that first cell will contain the value of OrderNumber field of Delivery class returned by the script service.As we are getting an array Delivery objects from the service, each item in the array will result in each row of table rendered by the library.

This will work fine but we have no column headers.This we can do quickly using rendered event of the DataView.This event is fired when data is about to be rendered in the data view.

var master = Sys.create.dataView("#tblOrders",
     { 

         dataProvider: "/Services/AJAXPreview6Demos.asmx",
         fetchOperation: "GetDeliveryItems",
         autoFetch: "true",
         initialSelectedIndex: 0,
         rendered: RenderDeliveryHeader
     }
 );

function RenderDeliveryHeader(sender, args)
{
    var tbl = Sys.get('#tblOrders');
    var row = tbl.insertRow(0);
    var cell = row.insertCell(0);
    cell.innerHTML = "Delivery No.";
    cell = row.insertCell(1);
    cell.innerHTML = "Delivery Date";
}

Suppose we have to also implement a rule that if DeliveryDate is not in current month then font of that row will be red.Here we have to check the value of each data item and then alter the rendering.We can use the itemRendered event as shown below.This event is triggered after each item is rendered.

var master = Sys.create.dataView("#tblCities",
     { 

         dataProvider: "/Services/AJAXPreview6Demos.asmx",
         fetchOperation: "GetDeliveryItems",
         autoFetch: "true",
         initialSelectedIndex: 0,
         rendered: RenderDeliveryHeader,
         itemRendered: ItemRenderedDeliveryHeader
     }
 );

function ItemRenderedDeliveryHeader(sender, args)
{
    var deliverymonth =  parseInt(args.dataItem.DeliveryDate.split("/")[0]);
    var deliveryyear  = parseInt(args.dataItem.DeliveryDate.split("/")[2]);
    var currentyear   = new Date().getFullYear();
    var currentmonth = new Date().getMonth() + 1;
    if (deliveryyear!= currentyear || deliverymonth!=currentmonth)
    {
        Sys.UI.DomElement.addCssClass(Sys.get('#tblCities').rows[args.index], "row");
    }
}

So far we have seen how render a single DataView and in the next post we will cover DataViews with Master/Detail relationship.

Posted in Web App | Leave a comment

ModelValidator in ASP.NET MVC 2 Preview 2 – Part 2

In my last post we have discussed about the ModelMetaData and related classes along with a sample code.In this post we will discuss about ModelValidator and ModelValidatorProvider and extend the sample library.

  • ModelValidator – This is the abstract base class and implemented by custom validators to perform the model validation.It has a constructor as shown below:
    • protected ModelValidator(ModelMetadata metadata,ControllerContext controllerContext) – This is normally invoked from the classes implementing ModelValidator.It maintains a reference to the ControllerContext and ModelMetadata and exposes them as properties.

          The other important method of this class is:

  • public abstract IEnumerable<ModelValidationResult> Validate(Object container) – This is implemented by the derived class to validate the object.

Now let us look at the ConfigRequiredFieldValidator class my implementation of ModelValidator

    public class ConfigRequiredFieldValidator : ModelValidator
    {
        public ValidationMetaData  ValidationMetaInfo { get; set; }
        public ConfigRequiredFieldValidator(ConfigModelMetaData configmetadata,ControllerContext context,ValidationMetaData valmetadata)
            :base(configmetadata,context)
        {
            ValidationMetaInfo = valmetadata;
        }

        public override IEnumerable<ModelValidationResult> Validate(object container)
        {
            bool error = false;
            ConfigModelMetaData metadata = Metadata as ConfigModelMetaData;
            object val = metadata.Model;
            if (val != null)
            {
                if (this.Metadata.ModelType == typeof(System.String) && val.ToString().Length == 0)
                {
                    error = true;
                }
            }
            else
            {
                error = true;
            }
            if (error) yield return new ModelValidationResult{Message=ValidationMetaInfo.ErrorMessage};

        }
    }

In addition to the properties defined by ModelValidator I have maintained a reference to ValidationMetaData object and this is used set the Message property of ModelValidationResult if the validation fails.

Now to plugin this validator we need to take a look into the ModelMetaDataProvider class.This is another abstract base class with an abstract method:

  • public abstract IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata,ControllerContext context) – This method returns the ModelValidator’s based on ModelMetaData as shown in the sample implementation below:
     public class ConfigModelValidatorProvider : ModelValidatorProvider
    {
        public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
        {
            List<ModelValidator> results = new List<ModelValidator>();
            ConfigModelMetaData configmetadata = metadata as ConfigModelMetaData;
            if (configmetadata.Validations  != null)
            {
                foreach (ValidationMetaData validation in configmetadata.Validations)
                {
                    if (validation.ValidationType == "Required")
                        results.Add(new ConfigRequiredFieldValidator(
                                    configmetadata,
                                    context,
                                    validation));
                }
            }
            return results;
        }
    }

Now the last thing that remains is to attach this custom validation provider at runtime.This is done by setting an instance of ConfigModelValidatorProvider to the Current property of ModelValidatorProviders class as shown below:

ModelValidatorProviders.Current = new ConfigModelValidatorProvider();

In the next post we will see how to use this plugin in an ASP.NET MVC Web Application

Posted in Web App | Leave a comment

ModelValidator in ASP.NET MVC 2 Preview 2 – Part 1

While going through the new features of ASP.NET MVC 2 Preview 2, one feature seemed quite interesting to me.There are a set of classes, using which we can build a custom validation framework for the model.ASP.NET MVC framework by default provides a Data Annotation(classes present in System.ComponentModel.DataAnnotations namespace) based  model validation.This makes use of attributes added in the model class.But this can be overridden by custom implementations with great ease.In the next series of posts I will discuss about the main classes related to model validation along with the sample code that I have written to build a XML config based validator.

First let us discuss about ModelMetaData and ModelMetaDataProvider classes in System.Web.Mvc namespace.

  • ModelMetaData – This class represents the metadata for a particular model class/property.While implementing custom metadata validator this can be extended to store any additional metadata.
  • ModelMetaDataProvider – This is the abstract base class for metadata provider which needs to be implemented by the custom metadata providers.The three abstract methods are
    • public abstract IEnumerable<ModelMetadata> GetMetadataForProperties(Object container,Type containerType) – This class retrieves metadata for the properties of a model.
    • public abstract ModelMetadata GetMetadataForProperty(Object model,Type containerType,string propertyName)- This class retrieves metadata for a property of a model.
    • public abstract ModelMetadata GetMetadataForType(Object model,Type modelType) – This class retrieves metadata for the class of a model.

I have developed a sample application to explore these classes.These sample validator uses a xml file to store metadata information as shown below.To keep it simple for a sample for every property I have only  defined validator of type Required along with corresponding error message.

<?xml version="1.0" encoding="utf-8" ?>
<models>
  <model type="SB.App.Books.Models.Book">
    <properties>
      <property name="Title" datatype="System.String">
        <validators>
          <validator type="Required" message="Title cannot be blank"/>
        </validators>
      </property>
      <property name="Author" datatype="System.String">
        <validators>
          <validator type="Required" message="Author cannot be blank"/>
        </validators>
      </property>
      <property name="Publisher" datatype="System.String">
        <validators>
          <validator type="Required" message="Publisher cannot be blank"/>
        </validators>
      </property>
    </properties>
  </model>
</models>

I have used the following classes as an abstraction of this configuration data.

    /// <summary>
    /// Provide abstraction for the "model" node
    /// </summary>
    public class ModelConfig
    {
        public string ModelType {get;set;}
        public Dictionary<string,PropertyConfig> PropertyConfigs { get; set; }
    }
    /// <summary>
    /// Provide abstraction for the "propertynode" node
    /// </summary>
    public class PropertyConfig
    {
        public string Name { get; set; }
        public Type  DataType { get; set; }
        public List<ValidatorConfig> ValidatorConfigs { get; set; }
    }
    /// <summary>
    /// Provide abstraction for the "validatornode" node
    /// </summary>
    public class ValidatorConfig
    {
        public string Type { get; set; }
        public string Message { get; set; }
    }

There is a class called ModelConfigManager which reads the config file and initializes and caches the configuration data in an Dictionary object as shown below:

  public class ModelConfigManager
    {
        //Stores the Config Information

        private static Dictionary<string, ModelConfig> Config = new Dictionary<string, ModelConfig>();

        public static string ConfigLocation { get; set; }
        /// <summary>
        /// Reads and Initializes The Config Object Model
        /// </summary>
        public static void Initialize()
        {
            ModelConfig modelconfig = null;
            PropertyConfig propertyconfig = null;
            ValidatorConfig validatorconfig = null;
            XElement config = XElement.Load(ConfigLocation);
            var models = from el in config.Elements()
                         select el;
            foreach(var model in models)
            {
                modelconfig = new ModelConfig();
                modelconfig.ModelType = model.Attribute("type").Value;
                modelconfig.PropertyConfigs = new Dictionary<string, PropertyConfig>();
                foreach (var property in model.Descendants("properties").Descendants<XElement>("property"))
                {
                    propertyconfig = new PropertyConfig();
                    propertyconfig.Name = property.Attribute("name").Value;
                    propertyconfig.DataType = Type.GetType(property.Attribute("datatype").Value);
                    propertyconfig.ValidatorConfigs = new List<ValidatorConfig>();
                    foreach (var validator in property.Descendants("validators").Descendants<XElement>("validator"))
                    {
                        validatorconfig = new ValidatorConfig();
                        validatorconfig.Type = validator.Attribute("type").Value;
                        validatorconfig.Message = validator.Attribute("message").Value;
                        propertyconfig.ValidatorConfigs.Add(validatorconfig);
                    }

                    modelconfig.PropertyConfigs.Add(propertyconfig.Name, propertyconfig);
                }
                Config.Add(modelconfig.ModelType, modelconfig);
            }
        }
        /// <summary>
        /// Returns Model Configuration for a given type
        /// </summary>
        /// <param name="modelType">Model Type</param>
        /// <returns>Model Configuration</returns>
        public static ModelConfig GetModelConfig(string modelType)
        {

                return Config[modelType];
        }
    }

The class ValidationMetaData stores the type of validation and error message.The ValidatorConfig class could have been reused.But to keep the metadata and config hierarchies separate I have created this one.This can be refactored later.

    public class ValidationMetaData
    {
        public string ValidationType { get; set; }
        public string ErrorMessage { get; set; }
    }

ConfigModelMetaData is the custom metadata class which extends ModelMetaData class.Since one property can have multiple validations it maintains a reference to List of ValidationMetaData objects as shown below:

    public class ConfigModelMetaData : ModelMetadata
    {
        public List<ValidationMetaData> Validations { get; set; }
        public ConfigModelMetaData(ModelMetadataProvider provider,
                                   Type containerType,
                                   Func<object> model,
                                   Type modelType,
                                   string propertyName,
                                   List<ValidationMetaData> validations
            ): base (provider,containerType,model,modelType,propertyName)
        {
            this.Validations = validations;
        }

    }

The ConfigModelMetaDataProvider is the custom model metadata provider class.It reads the config values from ModelConfigManager cache and creates ConfigModelMetaData objects as shown below:

   public class ConfigModelMetaDataProvider : ModelMetadataProvider
    {
        public override IEnumerable<ModelMetadata> GetMetadataForProperties(object container, Type containerType)
        {
           foreach(PropertyInfo property in containerType.GetProperties())
           {
               //Get MetaData for a single property
               yield return GetMetadataForProperty(new Func<object>(()=>property.GetValue(container,null)), containerType, property.Name);
           }
        }

        public override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName)
        {
            ValidationMetaData valmetadata = null;
            List<ValidationMetaData> valmetadatalist = null;
            //Get Config Value for a property
            PropertyConfig propconfig = ModelConfigManager.GetModelConfig(containerType.FullName)
                                                                .PropertyConfigs[propertyName];
            foreach(ValidatorConfig valconfig in propconfig.ValidatorConfigs)
            {
                valmetadata = new ValidationMetaData();
                valmetadata.ValidationType = valconfig.Type;
                valmetadata.ErrorMessage=valconfig.Message;
                if(valmetadatalist==null) valmetadatalist = new List<ValidationMetaData>();
                valmetadatalist.Add(valmetadata);
            }
            //Create metadata for a property
            ConfigModelMetaData configmetadata = new ConfigModelMetaData
                                                (this, containerType, modelAccessor,
                                                 propconfig.DataType, propertyName,
                                                 valmetadatalist);
            return configmetadata;
        }

        public override ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType)
        {
            return new ConfigModelMetaData(this, null, modelAccessor,
                                           modelType, null,
                                           null);
        }
    }

The framework class ModelMetaDataProviders class exposes the property Current.This by default refers to DataAnnotationModelMetadataProvider.This needs to be changed in order to plugin the custom model metadata provider as shown below:

 ModelMetadataProviders.Current = new ConfigModelMetaDataProvider();

In the next post we will discuss about developing custom ModelValidator and ModelValidator provider.

Posted in Web App | Leave a comment