Monday, September 7, 2015

Collection Interface In .NET

Introduction

.NET framework provides interfaces that implements by collections in language to provide functionality of iterating over objects in collection, adding and removing object from collection to randomly access object from collection.

As different interfaces provide different set of functionality most of the developers has problem when to use which interface to achieve functionality. The following post provides information about interfaces implemented by collection.

Interfaces

The following diagram is for relation between the interfaces.


Note:
  1. Class diagram are not having all the methods but contains important method that belongs to each collection interface.

  2. Collection interface is available in both generic and non-generic form, so in diagram obj type is object in nongeneric form and obj type is T(template type) in generic form.
Functionality Provided Read Count Add & Remove Index Based Read Index Based Add & Remove
IEnumerable
  1. Provide Read only Collection.
  2. Allow to read each object of collection in forward only mode.
Y N N N N
ICollection
  1. Allow to modify collection.
  2. Allow to get size of collection.
  3. Allow to Add and Remove object in/from collection.
Y
Inherited)
Y Y N N
IReadOnlyCollection
  1. Allow to read collection.
  2. Allow to get size of collection.
Y
(Inherited)
Y N N N
IList
  1. Allows to access collection by Index.
  2. Allow to Add and Remove object in/from collection by index.
Y
(Inherited)
Y
(Inherited)
Y
(Inherited)
Y Y
IReadOnlyList Allow to read collection by Index. Y
(Inherited)
Y
(Inherited)
N Y N

Note:
In above diagram (Inherited), the columns indicate that the features are inherited from parent and to find out from which parent one must look in the interface collection diagram.

So from above table three main interfaces functionality concluded in following way:

IEnumerable – interface provide minimum functionality which is Enumration.

ICollection – interface provide medium functionality which is getting size, adding, removing and clearing collection i.e. modification of collection. As it inherited from IEnumerable so includes functionality of IEnumerable.

IList – interface provide full functionality which is index base accessing of collection element, index base adding, index base removing from collection. As it inherited from ICollection it includes functionality of Enumerable and ICollection.

The following are some important things to know:
  1. IEnumerable interface under the hood make use of IEnumerator for providing reaonly and forward mode read.

  2. IReadOnly*** and IEnumerable are used for providing readonly collection. But difference is that IEnumerable allows collection to read in forward only mode where IReadOnly*** provide feature of Collection /List but only in readonly mode i.e. without modification feature like add & remove.

  3. IReadOnly is part of collection interface from framework 4.5.
Above table list down the features provided by each interface when collection gets converted to interface type or class implement interface to provide feature of collection.

Conclusion

It’s very important for developers to understand these interfaces because the rule says its always good to depend on interface rather than on the concrete type.

ContinueWith Vs await

TPL is new library introduced in C # 4.0 version to provide good control over thread, to make use of multicore CPU by mean of parallel execution on thread. Below discussion is not about TPL but its about ContinueWith function available on Task Class of TPL and await keyword introduced in C# 5.0 to support asynchronous calls.

ContinueWith - its method available on the task which allows executing code after task finished execution. In simple word it allows continuation.

Things to note here is ContinueWith also return one Task. That means you can attach ContinueWith on task return by this method.

Example :
public void ContinueWithOperation()
{
   Task<string> t = Task.Run(() => LongRunningOperation("Continuewith", 500));
   t.ContinueWith((t1) =>
   {
       Console.WriteLine(t1.Result);
   });
}

In above code new created task runs LongRunningOperation and once task execution completed ContinueWith execute operation on retuned task and print result of task.

ContinueWith operation thask get executed by default thread scheduler, one can also provide other scheduler for running task on it, this discussed in later in this article.

Note: below code is LongRunningOperation called by task. LongRunningOpertion here is just example in real program one cannot call long running operation on task, and if one want to call longrunning task than one need to pass TaskCreationOperation.LongRunning.

private string LongRunningOperation(string s, int sec)
{
  Thread.Sleep(sec);
  return s + " Completed";
}

await – its keyword that cause runtime to run operation on new task and cause executing thread to return and continue with execution (In most of the cases executing that is main thread of application). Once await operation get finished it returns to statement where is left of (i.e. returns to caller i.e. it returns according state saved) and start executing statements.

So await wait for newly created task to finish and ensures continuation once execution of waiting task is finished.

await keyword used with async to achieve asynchronous programming in C#. It’s called asynchronous programming because runtime capture state of program when it encounter await keyword (which is similar to yield in iterator) and restore state back once waited task finish so the continuation runs on correct context.

Example :

public async void AsyncOperation()
{
    string t = await Task.Run(() => LongRunningOperation("AsyncOperation", 1000));
    Console.WriteLine(t);
}

In above example new created task calls LongRunningOperation and execution left of once main thread encounter await keyword i.e. main thread return to caller of AsyncOpetion and execute further. Once LongRunningOpertaion completed than result of task get printed on console.

So here because state saved when await encountered flow returns on same context one operation on task executed.

Note: State is having detail about executioncontext/synchronizationcontext.

So form above its clear that both Task.ContinueWith and await Task wait for task to finish and allows continuation after task completion. But both works differently.

Difference between ContinueWith and await
  1. Saving Sate for And return on Execution context
    ContinueWith doesn’t save any kind of state, continuation operation attached using ContinueWith run on default thread scheduler in case not scheduler provided.

    await – on encounter of this keyword state get saved and once task on which await done get completed execution flow pick up saved state data and start execution statement after await. (Note: State is having detail about executioncontext/synchronizationcontext.)

  2. Posting Completed Task result on UI Control
    Below is example with ContinueWith and await to display completion task result on UI control.

    ContinueWith :

    Consider below code which display result of completed task on UI label.

    public void ContinueWithOperation()
           {
             CancellationTokenSource source = new CancellationTokenSource();
             source.CancelAfter(TimeSpan.FromSeconds(1));
             Task<string> t = Task.Run(() => LongRunningOperation("Continuewith", 500
    ));
    
                t.ContinueWith((t1) =>
                {
                    if (t1.IsCompleted && !t1.IsFaulted && !t1.IsCanceled)
                        UpdateUI(t1.Result);
                });
    }
    
    private void UpdateUI(string s)
           {
             label1.Text = s;
    }
    Note : LogRunningOperation is already given above.

    When above code is get executed below runtime exception occurs.



    This exception occurs because Continuation operation UpdateUI operation runs on different thread, in this case thread will be provided by default threadschedular which is ThreadPool and it doesn’t have any information about Synchronization context on which to run.

    To avoid exception, one must need to pass thread scheduler which pass data on UI SynchronizationContenxt. In below code TaskScheduler.FromCurrentSynchronizationContext() method pass UI related thread scheduler.

    t.ContinueWith((t1) =>
                {
                    if (t1.IsCompleted && !t1.IsFaulted && !t1.IsCanceled)
                        UpdateUI(t1.Result);
                }, TaskScheduler.FromCurrentSynchronizationContext());


    await :

    Consider below code which display result of completion on UI.

    public async void AsyncOperation()
    {
        try
        {
           string t = await Task.Run(() => LongRunningOperation("AsyncOperation",
                            10000));
           UpdateUI(t);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }


    Code written with await doesn’t throw any exception when posting data to UI control, No special code required for await. This happens because as discussed in 1 point of difference , on encounter of await state data get saved which has information about SynchronizationContext.

    So if one need to post data on UI than await is good option because there is no need of extra care/code to post data on UI.


  3. Handling Exception and Cancellation
    Consider below example code for ContinueWith and await method for handing exception and cancelled task.

    ContinueWith

    Below is example code how the exception/cancellation handled using ContinueWith.

    public void ContinueWithOperationCancellation()
           {
                CancellationTokenSource source = new CancellationTokenSource();
                source.Cancel();
    
                Task<string> t = Task.Run(() =>
                    LongRunningOperationCancellation("Continuewith", 1500,
                        source.Token), source.Token);
    
                t.ContinueWith((t1) =>
                {
                    if (t1.Status == TaskStatus.RanToCompletion)
                        Console.WriteLine(t1.Result);
                    else if (t1.IsCanceled)
                        Console.WriteLine("Task cancelled");
                    else if (t.IsFaulted)
                    {
                        Console.WriteLine("Error: " + t.Exception.Message);
                    }
                });
    }

    In above code cancellation/exception in continuation handled with by using TaskStatus. Other way to do same thing by making use of TaskContinuationOptions.OnlyOnRanToCompletion

    t.ContinueWith(
        (antecedent) => {  },
         TaskContinuationOptions.OnlyOnRanToCompletion);

    await

    Below is example code how the exception/cancellation handled using await.

    public async void AsyncOperationCancellation()
           {
             try
             {
               CancellationTokenSource source = new CancellationTokenSource();
               source.Cancel();
               string t = await Task.Run(() =>
                   LongRunningOperationCancellation("AsyncOperation", 2000, source.Token),
                       source.Token);
                    Console.WriteLine(t);
             }
             catch (TaskCanceledException ex)
             {
                    Console.WriteLine(ex.Message);
             }
             catch (Exception ex)
             {
                    Console.WriteLine(ex.Message);
             }
    }


    Above code doesn’t make use of task status as continuewith, it makes use of try ..catch block to handle exception. To handle cancellation there is need of catch block with TaskCanceledException.

    So from above example my view is cancellation/exception handling is done very clean way when one use continuation.

    Below is code for LongRunningOperationCancellation method.

    private string LongRunningOperationCancellation(string s, int sec,CancellationToken ct)
           {
             ct.ThrowIfCancellationRequested();
             Thread.Sleep(sec);
             return s + " Completed";
    }


    Above three cases shows difference of coding between ContinueWith and await. But below one shows why await is better than ContinueWith.

  4. Complex flow
    Consider below function which used for calculation factorial of number

       public KeyValuePair<int, string> Factorial(int i)
            {
                KeyValuePair<int, string> kv;
                int fact = 1;
                for (int j = 1; j <= i; j++)
                    fact *= j;
                string s = "factorial no " + i.ToString() + ":" + fact.ToString();
                kv = new KeyValuePair<int, string>(i, s);
                return kv;
            }
    Above function calculate factorial of number and return KeyValuePair to caller to display calculation.

    Now problem statement is above function to calculate factorial of number 1 to 5.

    ContinueWith

    Below is code to calculate factorial of numbers between 1 to 5. Expectation from the code below is calculating factorial of number, display it in order and once it completed “Done” message will get printed on the console.

    public void ContinueWithFactorial()
           {
                for (int i = 1; i < 6; i++)
                {
                    int temp = i;
                    Task<KeyValuePair<int, string>> t = Task.Run(() => Factorial(temp));
                    t.ContinueWith((t1) =>
                    {
                        KeyValuePair<int, string> kv = t1.Result;
                        Console.WriteLine(kv.Value);
                    });
                }
                Console.WriteLine("Done");
    }


    Once code get executed one will find that “Done” message get printed immediately i.e. first than factorial of number get displayed on screen. One more problem is number factorial is not get displayed in order. Below is output of the code execution.



    So to resolve problem with above code , code need to be refactored like this

    public void FactContinueWithSeq(int i)
    {
                Task<KeyValuePair<int, string>> t = Task.Run(() => Factorial(i));
                var ct = t.ContinueWith(((t1) =>
                {
                    KeyValuePair<int, string> kv = t1.Result;
                    int seed = kv.Key;
                    if (seed < 6)
                    {
                        Console.WriteLine(kv.Value);
                        seed++;
                        FactContinueWithSeq(seed);
                    }
                    else
                    {
                        Console.WriteLine("Done");
                        return;
                    }
                }));
    }


    Above function will be called like this p.FactContinueWithSeq(1).

    In above code to maintain sequence, task need to be fired one by one. And for that once one task completes its execution Contuation on it with the help of ContinueWith method call function again. It’s like doing recursive calling to function.

    And to display “Done” message at the end need to check for the seed to function. Which checks seed value increases 6 or not.



    But now there is need for attaching continuation on completion of FactContinueWithSeq, to achieve this code need to be done as below.

    TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
            public Task<string> FactAsyncTask { get { return tcs.Task; } }
            public void FactContinueWithSeqAsync(int i)
            {
                Task<KeyValuePair<int, string>> t = Task.Run(() => Factorial(i));
                var ct = t.ContinueWith(((t1) =>
                {
                    KeyValuePair<int, string> kv = t1.Result;
                    int seed = kv.Key;
                    if (seed < 5)
                    {
                        Console.WriteLine(kv.Value);
                        seed++;
                        FactContinueWithSeqAsync(seed);
                    }
                    else
                    {
                        tcs.SetResult("Execution done");
                    }
                }));
            }

  5. Call to above function

    p.FactContinueWithSeqAsync(1);
                Task<string> t = p.FactAsyncTask;
                t.ContinueWith((t1)=> Console.WriteLine(t.Result));


    In above code TaskCompletionSource is used to achieve the code of providing continutation on completion of factorial calculation.

    So one need to do lot of code for providing expected result, which is calculating factorial in sequence, waiting on calculation and once calculation get completed “Done” message get printed on console.

    await

    Now same code with help of await can be done like this

    public async void AwaitWithFactorial()
    {
       for (int i = 1; i < 6; i++)
       {
           int temp = i;
           Task<KeyValuePair<int, string>> t = Task.Run(() => Factorial(temp));
           await t;
           Console.WriteLine(t.Result.Value);
          }
          Console.WriteLine("Done");
     
    }


    Above code is simple and clean there is no need of doing whole big refactoration which required when doing same thing with ContinueWith.

Summary

From above difference/comparison of ContinueWith vs await it clear that in many scenario using and await is very helpful.
But there is also scenario where more complex things not required with proper error/cancellation handling in that case continuewith is helpful. But this scenario is very rare.

It’s always good to go with simple, easy and clear solution, for this my suggestion is always go with await rather than ContinueWith.

Flyweight Design Pattern

The Flyweight Design Pattern is one of the structural patterns introduced by the GOF. The Flyweight Pattern is about creating a pool of objects that allows sharing already existing objects and causing the application to consume less memory.

So this pattern does the following two things because the pattern creates objects once and then saves them to a pool:
  1. Increases application performance in terms of object creation since there is no requirement of creating an object for every request.
  2. Causes the application to consume less memory, since the object already exists in memory and no new object must be created because of the pool.
Ultimately flyweight patterns make the application efficient in terms of memory and processing.

Basic UML class Diagram of Design Pattern

The following image shows the class diagram of the basic Flyweight Design Pattern.



UML class Diagram
  • IFlyweight: Basic contract to be implemented by derived types, in other words by concrete flyweight.
  • FlyweightFactory: It's a factory class used by a client class to get the data from the concreate flyweight. This class is also responsible for creating the pool of an existing object. So when the request for data come that is already requested it returns data from the pool.
  • ConcerateSharedFlyweight1: It's a concreate implementation of the flyweight interface. As the name suggests, an object returned by this class will be shared among the clients of it.
  • ConcerateUnSharedFlyweight1: It's a concreate implementation of the flyweight interface. As the name suggests an object returned by this class will be unshared. That means that every time the client requires a new object.
  • Client: uses the concreate implementation, it creates an instance of Decorate and uses the functionality of it.
Note:UnSharedFlyweight is not always required, it depends on requirements, but SharedFlyweight is always required when you use the flyweight pattern.

The following code is the implementation of the Flyweight Design Pattern and the Class Diagram was shown above.

namespace BasicFlyweightPattern
{
    #region basic implementation
    public class FlyweightFactory 
    {
        public static List<Item> GetStaticItemList(string key)
        {
            IFlyWeight flyWeight = null;
            ICacheManager _objCacheManager = CacheFactory.GetCacheManager();

            if (key == "A")
            {
                if (_objCacheManager.Contains("A"))
                {
                    return _objCacheManager["A"] as List<Item>;
                }
                else
                {
                    flyWeight = new ConcerateSharedFlyweight1();
                }
            }
            else if (key == "B")
            {
                if (_objCacheManager.Contains("B"))
                {
                    return _objCacheManager["B"] as List<Item>;
                }
                else
                {
                    flyWeight = new ConcerateSharedFlyweight2();
                }
            }

            var list = flyWeight.GetList();
            _objCacheManager.Add(key, list);
            return list;
        }
    }

    interface IFlyWeight
    {
        List<Item> GetList();
    }

    public class Item
    {
        public int id { get; set; }
        public string desc { get; set; }
    }

    public class ConcerateSharedFlyweight1 : IFlyWeight
    {
        private List<Item> ItemList;

        public ConcerateSharedFlyweight1()
        {
            ItemList = new List<Item>();
        }

        public List<Item> GetList()
        {
            ItemList.Add(new Item { id = 1, desc = "A1" });
            ItemList.Add(new Item { id = 2, desc = "A2" });
            ItemList.Add(new Item { id = 3, desc = "A3" });
            return ItemList;
        }
    }

    public class ConcerateSharedFlyweight2 : IFlyWeight
    {
        private List<Item> ItemList;

        public ConcerateSharedFlyweight2()
        {
            ItemList = new List<Item>();
        }

        public List<Item> GetList()
        {
            ItemList.Add(new Item { id = 1, desc = "B1" });
            ItemList.Add(new Item { id = 2, desc = "B2" });
            ItemList.Add(new Item { id = 3, desc = "B3" });
            return ItemList;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Item> list =FlyweightFactory.GetStaticItemList("A");
     //List<Item> list = FlyweightFactory.GetStaticItemList("B");            
     foreach (var item in list)
            {
                Console.WriteLine(item.id.ToString() + "  " + item.desc );
           }

            Console.ReadLine();
        }
    }

}
      
The following are points to remember about the preceding code implementation:
  1. The client asks for data from FlyweightFactory by calling GetStaticItemList and passing the key as argument for getting the data.
  2. FlyweightFactory has a static method GetStaticItemList that creates an instance of concrete and gets data if the request is for the first time, for a later request it returns an existing object.
  3. FlyweightFacotry maintains a pool of existing objects using an Enterprise library caching block for sharing data among the clients, in other words different objects.
  4. In the concrete implementation of flyweight, a hardcoded list is returned but in an actual scenario this will be replaced by data from a data source.
  5. Item is a poco class, the list of which is returned from flyweight concrete classes. This class is represented by different items. The following actual scenario provides more detail.
Output



Here the output shows the result of A's same will use the result of B's. If the call comes a second time then the data is retuned from the cache.

Flyweight Design Pattern Example In an Actual Application

Problem Statement

A web application having a dropdown for displaying a list of Country, displaying a list of State, displaying a list of Product and so on in the dropdown and the dropdowns are part of multiple screens that are accessed by multiple users.

In this scenario, to display another kind of list for multiple user requests, the server must connect with the database server multiple times. This reduces the performance of the application and also consumes memory for creating and storing these lists.

Solution

The solution to the preceding problem is to use the Flyweight Design Pattern.

The following is a class diagram of the Flyweight pattern used in the application.


 
Mapping with Basic Implementation.
  • IFlyweightManager is equals to IFlyweight.
  • StaticDataListFlyweightFactory is equal to FlyweightFactory.
  • CountryStaticListManager and ProductStaticListManager is equal to ConcerateSharedFlyweight1 and ConcerateSharedFlyweight2.
  • StaticItem is equal to Item.
namespace FlyWeightPattern
{
    class Program
    {
        static void Main(string[] args)
        {

            List<StaticItem> countrylist = StaticDataListFlyWeidhtFactory.GetStaticItemList("Country");
            foreach (var item in countrylist)
            {
                Console.WriteLine(item.id.ToString() + "  " + item.Code + "  " + item.Description);
            }

            Console.ReadLine();
        }
    }
 public class StaticDataListFlyWeidhtFactory
    {
        public static List<StaticItem> GetStaticItemList(string key)
        {
            IFlyWeightManager manager = null;
            ICacheManager _objCacheManager = CacheFactory.GetCacheManager();

            if (key == "Country")
            {
                if (_objCacheManager.Contains("Country"))
                {
                    return _objCacheManager["Country"] as List<StaticItem>;
                }
                else
                {
                    manager = new CountryStaticListManager();
                }
            }
            else if (key == "ProductType")
            {
                if (_objCacheManager.Contains("ProductType"))
                {
                    return _objCacheManager["ProductType"] as List<StaticItem>;
                }
                else
                {
                    manager = new ProductTypeStaticListManager();
                }
            }

            var list = manager.GetList();
            _objCacheManager.Add(key, list);
            return list;
        }
    }

    interface IFlyWeightManager
    {
        List<StaticItem> GetList();
    }

    public class CountryStaticListManager : IFlyWeightManager
    {
        private List<StaticItem> StaticItemList;

        public CountryStaticListManager()
        {
            StaticItemList = new List<StaticItem>();
        }

        public List<StaticItem> GetList()
        {
            StaticItemList.Add(new StaticItem { id = 1, Code = "IND", Description = "India" });
            StaticItemList.Add(new StaticItem { id = 2, Code = "SRL", Description = "Sri Lanka" });
            StaticItemList.Add(new StaticItem { id = 3, Code = "SA", Description = "South Africa" });
            return StaticItemList;
        }
    }

    public class ProductTypeStaticListManager : IFlyWeightManager
    {
        private List<StaticItem> StaticItemList;

        public ProductTypeStaticListManager()
        {
            StaticItemList = new List<StaticItem>();
        }

        public List<StaticItem> GetList()
        {
            StaticItemList.Add(new StaticItem { id = 1, Code = "0123", Description = "Watch" });
            StaticItemList.Add(new StaticItem { id = 2, Code = "0234", Description = "Shoes" });
            StaticItemList.Add(new StaticItem { id = 3, Code = "0345", Description = "" });
            return StaticItemList;
        }
    }

    public class StaticItem
    {
        public int id { get; set; }
        public string Code { get; set; }
        public string Description { get; set; }
    }
}

Output
 


So the preceding code works the same as already described in the basic implementation of pattern. In the code another type of the list is fetched by passing a different key. For this implementation the keys are Country and Product. In a real application one can have more than this.

The preceding implementation follows the SOLID principle, just one exception is the Factory class that must be modifed when one wants to add a new key so it breaks the rule of single responsibility.

Note: Here the country and product list are hardcoded but in an actual program it is fetched from the database.

Conclusion

This pattern is very helpful in the scenario where one wants to create a pool of objects and share them among the clients (the clients are software programs or classes or web applications as in this example).

Note: This is my point of view regarding patterns. Please provide your feedback regarding it and also provide feedback if something you find is wrong in this.

Sunday, July 26, 2015

Visual Studio Generate Class From JSON or XML

Introduction 

Below Article is on, one of the cool feature available in visual studio which helps/save effort of developer to generate class structure from json/xml string.

There is cases application written using .Net Framework written by developer received json/xml string from the web service or from the other 3rd party application it calling. After receiving xml/json string data there is need of further processing received data, which requires to deserialize received xml/json in .Net object. And for that .Net class structure need to be created which match with json/xml string data so that json/xml string deserialize correctly.

Problem Statement

For example:

Program receives following json string by calling webservice or 3rd party program.

JSON

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

XML

  <employees>
    <employee>
        <firstName>John</firstName> <lastName>Doe</lastName>
    </employee>
    <employee>
        <firstName>Anna</firstName> <lastName>Smith</lastName>
    </employee>
    <employee>
        <firstName>Peter</firstName> <lastName>Jones</lastName>
    </employee>
</employees>

And now there is need for deserializing received json/xml string to .Net object, so further process will be done based on received data or on received data.

Approach 1: Do it manually

In this approach developer need to have knowledge of json/xml so that he/she can understand received json/xml string and it structure. Once getting detail of xml/json and received xml/json string, developer has to convert json/xml string into meaningful class structure so desterilization done without any issue/error.

So problem with this approach is lot of work need to be done by developer like
  1. Require knowledge of json/xml
  2. Understand jso/xmln string sent by exteranl program
  3. create class strucutre for json/xml structure, which is trial and error approch because most of the time created structure doesn't work in first go
  4. If json/xml string having complex structure than its difficult as well as require time to create class structure to deserialize json/xml string
Approach 2 : Automated using Visual Studio

In this approach make use of Visual studio to generate class just by copy pasting xml/json string.

Following steps need to be done for generating class
  1. Copy json/xml string

    JSON


    XML


  2. Go to Edit>Past Sepcial > Paste JSON As Classes or Paste XML As Classes



  3. Visual studio generate Class structure for developer as below

    Below is example of class structure created by copy and pasting JSON string

        public class EmployeeList
        {
            public Employee[] employees { get; set; }
        }
    
        public class Employee
        {
            public string firstName { get; set; }
            public string lastName { get; set; }
        }
    
    

    Below is example of class structure created by copy and pasting XML string

    /// 
        [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
        [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
        public partial class employees
        {
    
            private employeesEmployee[] employeeField;
    
            /// 
            [System.Xml.Serialization.XmlElementAttribute("employee")]
            public employeesEmployee[] employee
            {
                get
                {
                    return this.employeeField;
                }
                set
                {
                    this.employeeField = value;
                }
            }
        }
    
        /// 
        [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
        public partial class employeesEmployee
        {
    
            private string firstNameField;
    
            private string lastNameField;
    
            /// 
            public string firstName
            {
                get
                {
                    return this.firstNameField;
                }
                set
                {
                    this.firstNameField = value;
                }
            }
    
            /// 
            public string lastName
            {
                get
                {
                    return this.lastNameField;
                }
                set
                {
                    this.lastNameField = value;
                }
            }
        }
    



As you see in above code it will generate correct attribute for xml on class so deserialization done without any issue/error.

Advantage of this solution
  1. No need to understand xml/json
  2. No effort require for creating class
Summary

Visual studio feature of creating class based on string really helpful to developer because understanding json/xml string and creating class structure requires efforts and sometime very frustrating.

Monday, July 13, 2015

SOLID Principle In Detail

SOLID principles are the set of principle fist given by Robert.C.Martin. SOLID principle as name given its set of principle that allows building SOLID software system (i.e. Application, Application Module), if one implement software according to this set of principle.

SOLID software system means its allows to build system that is
  • Easy to maintain
  • Easy to extend
  • Easy to understand
  • Easy to implement
  • Easy to explain
SOLID principles are related with the design and maintenance of software system. Most of the developer mix SOLID principles with OOD principles and Design patterns. Below image that removes confusion of OOD principles and Design patterns
Note: This is my interpretation of the arranging thigs.

So as per image

  1. OOD Principle (Abstraction, Encapsulation, Inheritance, Polymorphism)
  2. SOLID principle
  3. Software Design Patterns (GOF patterns, Dependency injection & patterns)
  4. Martin Flower’s Enterprise Application Architectures Pattern (additional but required)
  5. Domain Driven Design Architecture (additional but required)
S.O.L.I.D is acronym for

  1. Single Responsibility Principle

    Principle is related to Designing software module, class or function that should perform only one task. So this principle is about Creation.


    In Detail Read : Single Responsibility Principle In Detail

  2. Open/Close Principle

    Principle is applied after 1 (Single Responsibility Principle), again this principle is related to Designing module, class or function. But it about closing already designed thing for modification but opening designed thing for extension i.e. extending functionality. So this principle is about extension.


    In Detail Read : Open Closed Principle
  3. Liskov Substitution Principle

    Principle is related to substitution of child in place of its parent. So principle is about relationship i.e. inheritance.


    In Detail Read : Liskov Substitution Principle
  4. Interface Segregation Principle

    Principle is related to designing of interfaces as one of the basic rules of designing says depends on abstraction. Principle is about design interface such a way, so that client of interface not force to implement not required things. So principle is about efficient interface design.



    In Detail Read : Interface Segregation Principle

  5. Dependency Inversion Principle

    Principle is related to designing decoupling modules, classes of software system. This principle mostly applied after 4 (Interface Segregation principle) because interface are one form of abstraction and this principle is related to Details (module/class) should depend on abstraction, and abstraction should not depend on detail. So this principle is about creating loosely coupled system.


    In Detail Read : Dependency Inversion Principle

Dependency Inversion Principle

The Dependency Inversion Principle is one of the SOLID principles defined by Robert C. Martin. This principle is about dependencies among the components (such as two modules, two classes) of the software.

The principle says that high-level modules should depend on abstraction, not on the details, of low level modules, in other words not the implementation of the low level module. Abstraction should not depend on details. Details should depend on abstraction. In simple words the principle says that there should not be a tight coupling among components (in other words two modules, two classes) of software and to avoid that, the components should depend on abstraction, in other words a contract (interface or abstract class).

Dependency Inversion Principle in Real life

To understand the second problem better way, let's see a real life scenario of a computer or laptop.




As you can see in the preceding image we have a port for each external device to which I can associate an external device and do our work.

But the problem with this is, I cannot attach my keyboard to a printer port and vice versa. The same problem occurs with the other devices. So this is like a tight coupling, that I cannot change my external device on the given interface, in other words on which I depend.

Solution to this is USB port.

If I have a USB port then I can easily attach any device to my machine and perform my task.



Example of Dependency Inversion Principle in Application Development

The following is a class diagram of tight coupling that does not follow the principle.



Public Class Customer  
{  
    CustomerRepository CustomerRepository;  
    Public Customer  
    {  
        CustomerRepository = new CustomerRpository();  
}  
  
Public bool Save()  
{  
    CustomerRepository.Save();  
}  
}  
  
Public class CustomerRepository  
{  
    Public bool Save(dattype data)  
{  
              //Sql Connection object and Save data in Sql server   
}  
}  

The preceding code is tightly coupled because the current repository deals with the SQL server. So if the requirement is to use an Oracle server then there is modification required for the Customer class.

So to avoid that, make the customer class depend on abstraction. The following is an image of a class diagram where the customer depends on abstraction and supports both SQL and Oracle servers.



Public Class Customer   
{  
    CustomerRepository CustomerRepository;  
    Public Customer   
    {  
        CustomerRepository = new CustomerRpository();  
    }  
  
    Public bool Save()   
    {  
        CustomerRepository.Save();  
    }  
}  
  
Public class CustomerRepository   
{  
    Public bool Save(dattype data)   
    {  
        //Sql Connection object and Save data in Sql server     
    }  
} 

So in the preceding code the customer class depends on ICustomerRepository abstraction, in other words an interface. Another thing is here the customer class receives a dependency via consumption of the customer class or using a dependency container.

Note: Here is an example of the class but the same goes for the modules designed in software because dependency inversion is about providing a set of abstraction policies on which the details depend and the policy that provides flexibility in the software system.

Disadvantages

Application modules become tightly coupled, that means:
  1. The testability of the module becomes difficult.
  2. Parallel development of the module becomes difficult.
  3. Many changes are required when there is modification in the module and when there are changes in the module it depends on. 
Read more Dependency Injection talks about the disadvantages and advantages of using dependency inversion.

Note: Dependency Injection is not the same as Dependency Inversion because Dependency Inversion is about defining an abstraction policy for the software module whereas Dependency Injection is a set of patterns to supply dependency.

Interface Segregation Principle

The Interface Segregation Principle is one of the SOLID principles defined by Robert C. Martin. It is one of the rules of software development that says to always code according to a contract, in other words an interface, not against the implementation, in other words a concrete class, because coding against an interface provides advantages like flexibility, loose coupling, testable code and so on. This principle is related to creating an interface for implementation.

The principle says “Client (class implementation interface) should not force to implement Interface that they don't use.” In simple words the principle is saying, do not design a big fat interface that forces the client to implement a method that is not required by it, instead design a small interface. So by doing this class only implement the required set of interface(s).

If there is big fat interface then break it into a set of small interfaces with the related method(s) in it. It's similar to normalizing our database like normalizing database from 1NF to 3NF where a big table is broken into tables with related columns.

Interface Segregation Principle in Real life

In terms of the violation of the ISP, the following image shows a big dustbin for throwing all kinds of garbage away without any kind of segregation.



With ISP, the following image is a good example of segregation in our real life.




That is an image of a waste bin segregation that shows which one to use for throwing away trash we use.

Example of ISP in Application Development

Here is an example of a banking customer for a bank with the following types of customers:
  1. Corporate customer: For corporate people.
  2. Retail customer: For individual, daily banking.
  3. Potential customer: They are just a bank customer that does not yet hold a product of the bank and it is just a record that is different from corporate and retail.
The developer of a system defines an interface for a customer as in the following that doesn't follow the ISP rule.



It looks OK at first glance but it's a big fat interface for the customer with problem since it forces the client class to implement methods that are not required.
  1.  A potential customer as described taht does not hold any product is forced to implement a product property. 
  2. A potential customer and a retail customer both are forced to have a Customer Structure property but in a real scenario a Corporate customer has a Customer Structure that describes a customer hierarchy. 
  3. A potential customer and a retail customer both are forced to implement a BusinessType but that just belongs to a corporate customer. 
  4. A corporate customer and a potential customer are forced to implement an Occupation property that is just a blog to a retail customer. 
A solution to the preceding problem is to split the fat interface into meaningfull parts, in other words small interfaces, so the customer type only implements the interface that is required by it.

The following is an image that follows the ISP:



Disadvantages
  1.  Deliver big fat interface that forces the client to implement a method that is not required.
  2. The client ends up implementing a usefuless method, in other words a method that has no meaning to the client. This decreases the readability of the code and also confuses the developer using the client code.
  3. The client interface ends up violating SRP sometime since it might perform some action that is not related to it.

Liskov Substitution Principle

Liskov Substitution Principle – is one of the SOLID principles defined by Barbara Liskov. Principle is based on the parent-child relationship in other words inheritance features of OOD (Object Oriented Design). Principle says “When class S is a subtype of class T then an object of type T can be replaced by an object of type S without affecting functionality/correctness of the implementation or program”.

In simple words it says “Places in implementation (Class/Function) that use a base class, in other words consume a service of a base class, must work correctly when the base class object is replaced by a child class (derived class) object.”

Liskov Substitution Principle in Real life 

The following is an example of an electric bulb that actually violates substitution. When the bulb fails it is replaced with a new bulb. Here in this example the old bulb is replaced with the new bulb.

Perfect Substitution


Note:
Here in this example in the family of bulbs, considering the old bulb to be a parent of all bulb types and a CFG bulb is a child of the same family inherited from it.

When one replaces a failed bulb, in other words in programming terms substitutes the old with the new, it must provide light that is provided by the old bulb, in other words works without affecting correctness or functionality (provides a constant light in the house). In the preceding example the substitution worked perfectly since there is no modification in functionality.

Violation Example



The preceding image shows the violation of the principle. Since replacing with a decoration bulb (that provides light in the form of decoration) instead of a bulb meant for just providing light in the house. That actually is a violation in the sense of modifying the functionality because a decoration bulb does not provide the same functionality for the consumer.

Example of not following Principle in Application Development



Continuing with bank savings account that is already explained in previous articles about the Open-Closed Principle.
 
Interface ISavingAccount   
{   
   //Other method and property and code   
   bool Withdrwal(decimal amount);   
}   
   
Public Class RegularSavingAccount : ISavingAccount   
{   
  //Other method and property and code related to Regular Saving account   
   
   Public bool Withdrwal ()   
  {   
    Decimal moneyAfterWithdrawal = Balance-amount;   
if(moneyAfterWithdrawal >= 1000)   
{   
    //update balace    
    return true;   
}   
else   
  return false;   
  }   
}   
   
Public Class SalarySavingAccount : ISavingAccount   
{   
  //Other method and property and code related to Salary Saving account`   
   Public bool Withdrwal ()   
  {   
    Decimal moneyAfterWithdrawal = Balance-amount;   
    if(moneyAfterWithdrawal >= 0)   
    {   
       //update balace    
       return true;   
    }   
    else   
      return false;   
  }   
}   
Public Class FixDepositSavingAccount : ISavingAccount   
{   
  //Other method and property and code related to Salary Saving account`   
   Public bool Withdrwal ()   
  {   
    Throw New Excpetion(“Not supported by this account type”);   
  }   
}   

In the preceding code the IsavingAccount interface is implemented by a different kind of savings account of the bank, like Regular, Salary and FixDeposit savings account.

But as per the banking rules, a FixDeposit savings account doesn't provide a withdrawal facility whereas another bank account might provide a withdrawal facility.

So the developer might write code to raise an exception when an attempt is made to withdraw from a FixDeposit savings account.

Now consider the following method in a class calling a withdrawal by casting the actual object to the parent class type.

Public class AccountManager   
{   
    Public bool WithdrawFromAccount(IsavingAccount account)   
    {   
         account.Withdraw(amount);   
    }   
}   

The following code calls the method,

//works ok  
AccountManager.WidhdrawFromAccount(new RegularSavingAccount());  
//works ok  
AccountManager.WidhdrawFromAccount(new SalarySavingAccount());  
//throws exception as withdrawal is not supported  
AccountManager.WidhdrawFromAccount(new FixDepositSavingAccount()); 

Violation of Liskov Substitution Rule

So the preceding code breaks the Liskov Substitution rule since the inherited FixDepositSavingAccount class is modifying the functionality of the withdrawal. Because the savings account should provide functionality to withdraw an amount without throwing any error.

How to stop violating the rule

To stop violating the rule one must verify the inheritance tree, in other words child classes inherited from the parent class should not break the functionality when the child class object replaces the parent class object.

So the class must inherit from the proper parent class in such a way that when the child class replaces the parent, it doesn't break the actual functionality provided by the parent class.

Note
It's not always true that one must make changes in the inheritance tree but making changes at the class and method level also resolves problems. To get such kind of example click on the link: Object Menter (Square and rectangle example).



In the preceding image the new classes WithWithdrawal and WithoutWithdrawal are created and the child classes are inherited from the respective parent class.

So in the preceding code:

Interface ISavingAccount   
{}   
Public Class SavingAccountWithWithdrawal : ISavingAccount   
{   
    Public virtual bool Withdrwal () {}   
}   
Public Class SavingAccountWithoutWithdrawal : ISavingAccount   
{   
}   
Public Class RegularSavingAccount : SavingAccountWithWithdrawal   
{    
  Public bool Withdrwal ()   
  { //implementation   
  }   
}   
Public Class SalarySavingAccount : SavingAccountWithWithdrawal   
{    
  Public bool Withdrwal ()   
  {//implementation   
  }   
}   
Public Class FixDepositSavingAccount : SavingAccountWithoutWithdrawal   
{   
}   

Now using it:

Public class AccountManager   
{   
    Public bool WithdrawFromAccount(SavingAccountWithWithdrawal account)   
    {   
       account.Withdraw(amount);   
    }   
}   


Now the following code to call method:

//works ok  
AccountManager.WidhdrawFromAccount(new RegularSavingAccount());  
//works ok  
AccountManager.WidhdrawFromAccount(new SalarySavingAccount());  
//compiler gives error   
AccountManager.WidhdrawFromAccount(new FixDepositSavingAccount());  

Disadvantage of not following the Liskov Substitution Principle
  • Developed code throws a run time error or exception or also might not work as expected and that leads to program failure or incorrect results.
  • The preceding discussion shows an example of throwing an exeption by a child class for a not supported method.
  • Read link: Object Mentor that shows an example (square and rectangle example) of giving incorrect results when not following the principle.
So the biggest advantage of not following this rule is: it causes problems at runtime rather than causes application failure or incorrect results.

Open Closed Principle

The Open Closed Principle is one of the SOLID principles defined by Robert C. Martin. The principle says “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”.

So in simple words it says that an implementation (of a class or function), once created, should be closed for further modification, in other words one should not modify an implementation (of a class or function) of logic and/or functionality. One can do refactoring or resolve errors of implementation (of a class or function) but the implementation (of a class or function) is open for extension, in other words one can extend the implementation (of a class or function) of logic and/or functionality.

Real Life Example of Open Closed Principle

An electric adapter is a good example of this principle.



As you can see in the image:
  1. An adapter in the wall is always closed for modification, in other words we cannot change it once it is fitted or extended if we want more.
  2. But an adapter always provides a method of extension, so we can plug in an extension board of an adapter for more adaptation.
  3. So you plug in an extension board and extend an existing electric adapter fitted in wall.
Example of not following the principle in Application Development

A bank offers various types of the savings accounts (Salary Saving, Regular Saving and so on) that meet the needs of many types of customers. A bank has differing sets of rules and each savings account type has a different set of rules to calculate interest.

To calculate the interest of an account, developers have developed the following class with methods to calculate interest.

Public class SavingAccount   
{   
    //Other method and property and code   
    Public decimal CalculateInterest(AccountType accountType)   
    {   
        If(AccountType==”Regular”)   
        {   
            //Calculate interest for regular saving account based on rules and    
            // regulation of bank   
            Interest = balance * 0.4;   
            If(balance < 1000) interest -= balance * 0.2;   
            If(balance < 50000) interest += amount * 0.4;   
        }   
        else if(AccountType==”Salary”)   
        {   
            //Calculate interest for saving account based on rules and regulation of    
            //bank   
            Interest = balance * 0.5;   
        }   
    }   
}  

So in the preceding code the SavingAccount class's CalculateInterest method does a calcualtion based on the account type like Salary and Regular.

So the implementation is not following the Open Closed principle because if tomorrow the bank introduces a new SavingAccount type then there is a requirement to modify this method for adding a new case for the new account type. An example is if the bank introduces a “Child Savings Account type” requiring a new condition for calculating the interest for this account type. That means that the method is always open for modification.

One more thing to note here is that the method is also not following the Single Responsibility Principle. Since here the method is doing more than one thing, like calculating interest for more than one type.

How to Implement the Open Closed Principle

Inheritance is only one way to implement the Open Closed Principle. Because inheritance is only an Object Oriented Design (OOD) basic pillar that allows extension of functionality of an existing class.

To implement the Open Closed Principle one can use interface, an abstract class, abstract methods and virtual methods than inherit them when you want to extend functionality.

So the preceding problem of a Savings Account can be resolved as in the following.


 
Interface ISavingAccount   
{   
   //Other method and property and code   
   decimal CalculateInterest();   
}   
Public Class RegularSavingAccount : ISavingAccount   
{   
  //Other method and property and code related to Regular Saving account   
  Public decimal CalculateInterest()   
  {   
    //Calculate interest for regular saving account based on rules and    
    // regulation of bank   
    Interest = balance * 0.4;   
    If(balance < 1000) interest -= balance * 0.2;   
    If(balance < 50000) interest += amount * 0.4;   
  }   
}   
   
Public Class SalarySavingAccount : ISavingAccount   
{   
  //Other method and property and code related to Salary Saving account`   
  Public decimal CalculateInterest()   
  {   
    //Calculate interest for saving account based on rules and regulation of    
    //bank   
    Interest = balance * 0.5;   
  }   
}  

In the preceding code two new classes are created, RgularSavingAccount and SalarySavingAccount, that is inherited from IsavingAccount.

So if there is a new account added by the bank than there is no need to modify the logic of exiting classes, just extend the functionality by inheriting an interface.

Finally the preceding example implements the Open Closed Principle since there is no need to modify the existing implemented logic and it allows extension for adding new logic.

And the preceding example also implements the Single Responsibility Principle since each class or function is doing only one task.

Note : An interface is created here just as an example. There could be an abstract class of SavingAccount that is implemented by a new savings account type.

Read: Decorate design pattern that also helps to understand.

Disadvantage of not following Open Closed Principle
  1. Since a class or function always allows the addition of new logic, whenever new logic is added it is always necessary to test for full functionality. That requires the addition of a new test case for the added functionality and might also require the modification of an existing test case that fails because of added functionality.
  2. It also breaks the Single Responsibility Principle since a class or function might end up doing multiple tasks.
  3. Class or function maintenance becomes difficult since a class or function can become thousands of lines of code that is difficult to understand.
How to Identify not following Single Responsibility Principle

A class or function is always open for modification, in other words always allows adding more logic to it. Like in the preceding example.

Monday, April 20, 2015

Single Responsibility Principle In Detail

Single Responsibility Principle – is one of the SOLID principles defined by Rober.C.Martin. Principle says “Implementation (Class/ Function) should perform only one task or Implementation (Class/Function) should change for only one reason”.

So in simple word it says “Whatever developer implements (Class/Function) in code during development should perform only one task and developer should only have one reason to change implementation (Class/Function).”

Wrong interpretation of the Principle:


Most of developer interprets it as “Class should perform only one task”. But it’s not only class, function you implement in code during development should also need to perform only one task. So one should interpret it as “Implementation(Class/Function) should perform only one task”

Real Life Example of not following Single Responsibility Principle


What happens when one can do more than one tasks. Below is image example of it



One can able to perform multiple tasks there is no question in it, but it’s not going to provide quality /better output. So to get good quality/better output of work, one should do one task at time.

Example of not following Principle in Application Development


In programming i.e. during developing code as below Order class not following principle

Public class OrderManager
{
 Public List<string> ValidateOrder()
 {
  //Code for validation
 }

 Public bool SaveOrder(OrderInfo order)
 {
  //Code for saving order
 } 

 Public void NotifyCustomer()
 {
  //Code for notification 
 }
}

Above order class having following responsibility
  1. ValidateOrder - Validating Order placed by customer and return error message if any
  2. SaveOrder – Saving Order placed by Customer and return true/false
  3. NotifyCustomer – Notify customer order is placed 

Method not following principle


Public int SumOfAllCustomerOrder(int customerId)
{
            int sum =0;
  var query= “Select * from order where customerid =” + customerid;;
           //query orders
          foreach(Order in OrderCollection)
          {
  If(Order.Items.Count > 5)
             Sum += Order.Price;            
          } 
  return sum;
}

Above method having following responsibility
  1. Method first all the order
  2. It went through all order in collection and do some of that 

Following Single Responsibility Principle


To make class or function to following Single Responsibility Principle, divide responsibility by creating new classes or function

Public Class OrderValidator
{
   Public List<string> Validate(Order order) { //code for validation}
}

Public Class Notifier
{
   Public void Notify(string emailId) { //code for notification}
}

Public Class OrderManager
{
  Private readonly OrderValidator orderValidator;
  Private readonly Notifier notifier;
  Public OrderManager(OrderValidator oValidator, Notifier nFier)
  {
 orderValidator = oValidator;
   notifier = nFier;
  }

   Public bool SaveOrder(OrderInfo orderInfo) 
  { 
     //Validate order 
  orderValidator.Validate(orderInfo);
        //code for saving order //this might be call to repository to save order 
        //notify after successful saving
        notifier.Notify(orderInfo.EmailId)
  }

   Public List<orderinfo> GetOrders(int customerId) { //code for getting order by cusotmerid}
}

Above code shows the three classes which is having only single responsibility to perform.

For method it will be like

Public List<orderinfo> GetOrder(int customerId)
{
            int sum =0;
  var query= “Select * from order where customerid =” + customerid;;
           //query orders
          return ordercollection;
}

Public int SumOfAllCustomerOrder(int customerId)
{
          var OrderCollection = GetOrder(customerId);
          foreach(Order in OrderCollection)
          {
  If(Order.Items.Count > 5)
             Sum += Order.Price;            
          } 
  return sum;
}

Note:

Following Single Responsibility doesn’t mean one can create class with one method.

Disadvantage of not following Single Responsibility Principle


In programming if developer write a class/function that performs more than one task always cause problem in providing good quality. Following problems related to class perform more than one task
  1. It’s very difficult for the other developer (i.e. who is not having any knowledge of class) to understand class/function.
  2. It’s difficult for the other developer to maintain the class/function or change the class/function.
  3. Writing test cases for the class/function also becomes difficult. 

How to Identify not following Single Responsibility Principle


  1. Try to write one line description of the class or method, if description contains word like (and, or, but, if). Example description of the class listed above where not following single resposiblity is: 
  2. “Order class that performs order saving, notification to customer and validate order”.
  3. Class constructor taking more than three argument or Method contains too many parameters.
  4. Class or Method is too long implementation.
  5. Class is low cohesive. Read more about cohesion : http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29


Ref. From: Clean code – Robert .C. Martin

Saturday, March 7, 2015

Validation in any type Application using DataAnnotation

DataAnotation NameSpace

System.ComponentModel. DataAnnotation namespace that provides set of attributes classes used for decorating class property with it, which is useful for validating class object. Besides attribute classes it also provide set of class which is helpful for validating class (Ex. Validator, ValidationContext, VlidationResult i.e. all classes with start with Validat**** ).

Below image show the all classes provided by DataAnnotation



Image shows the all classes not related to validation.

Find more about each class on MSDN : https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations%28v=vs.95%29.aspx

How to use Attribute

Before start look this for creating custom attribute : Custom Validation Attribute Specific to Entity

Now to use Attribute in your entity you need to decorate your property of entity with attribute as below :

    public class BankAccount
    {

        public enum AccountType
        {
            Saving,
            Current
        }

        [Required(ErrorMessage="First Name Required")]
        [MaxLength(15,ErrorMessage="First Name should not more than 1`5 character")]
        [MinLength(3,ErrorMessage="First Name should be more than 3 character")]
        public string AccountHolderFirstName { get; set; }

        [Required(ErrorMessage="Last Name Required")]
        [MaxLength(15,ErrorMessage="Last Name should not more than 1`5 character")]
        [MinLength(3,ErrorMessage="Last Name should be more than 3 character")]
        public string AccountHolderLastName { get; set; }

        [Required]
        [RegularExpression("^[0-9]+$", ErrorMessage = "Only Number allowed in AccountNumber")]
        public string AccountNumber { get; set; }

        public AccountType AcType { get; set; }

        [AccountBalaceCheckAttribute]
        public double AccountBalance { get; set; }
    } 

As in above code BankAccount entity property decorated with the Attribute and also provided with the proper error message.

In code AccountBalance is property is decorated with Entity Specific custom validation attribute. To read about more please refer custom attribute link listed above.

How to validate

To validate entity DataAnnotation provides class called Validator, which allow to validate entity as listed in below code.

public class GenericValidator 
    {
        public static bool TryValidate(object obj, out ICollection results)
        {
            var context = new ValidationContext(obj, serviceProvider: null, items: null);
            results = new List();
            return Validator.TryValidateObject(
                obj, context, results,
                validateAllProperties: true
            );
        }
    }

Above code shows code for GenericValidator class , which is class to validate any entity. Class used to avoid writing code again and again when doing validation.

Above code class make use of Validator class with it TryValidateObject method which takes ValidationContext class object as input.

Below code shows how to use GenericValidator class for validating entity.

static void Main(string[] args)
        {
            var bankAccount = new BankAccount();
            ICollection lstvalidationResult;

            bool valid = GenericValidator.TryValidate(bankAccount, out lstvalidationResult);
            if (!valid)
            {
                foreach (ValidationResult res in lstvalidationResult)
                {
                    Console.WriteLine(res.MemberNames +":"+ res.ErrorMessage);
                }
                
            }
            Console.ReadLine();
        }

Output 

Conclusion

ValidationAttribute is doing one way to achieve Validation (Aspect Oriented Programming) with the help of attribute. And validation attribute provided in DataAnnotation namespace can be used in any time of application to do validation of entity.

Complex Custom Validation Attribute Specific to Entity

System.Componentmodel.DataAnnotation NameSpace

System.Componentmodel.DataAnnotation is namespace in .net framework provide set of the attribute classes. This attribute classes used for decorating property of the user defined entity and validate entity.

Find more about each class on MSDN : https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations%28v=vs.95%29.aspx

ValidationAttribute: -

Most of all required attributes for validation is provided in the DataAnnotation namespace but there are some complex validation required to validate entity required to define by developer of itself.

ValidationAttribute is class in DataAnnotation namespace allow to create custom attribute as per the need to developer to validate entity.

Following is implementation of custom validation attribute:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class AccountBalaceCheckAttribute : ValidationAttribute
{
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult result = ValidationResult.Success;
            string[] memberNames = new string[] { validationContext.MemberName };

            decimal val = Convert.ToDecimal(value);

            BankAccount account = (BankAccount)validationContext.ObjectInstance;

            if (account.AcType == BankAccount.AccountType.Saving && val < 500)
                result = new ValidationResult(string.Format(this.ErrorMessage, 500),memberNames);
            else if (account.AcType == BankAccount.AccountType.Current && val < 1000)
                result = new ValidationResult(string.Format(this.ErrorMessage, 1000), memberNames);


            return result;
        }
} 

How to use it

 
public class BankAccount
{

   public enum AccountType
   {
      Saving,
      Current
   }

   public AccountType AcType { get; set; }

   [AccountBalaceCheckAttribute(ErrorMessage = "Account Balance should have value more than {0}")]
   public double AccountBalance { get; set; }
}

In this example attribute is defined for the specific entity BankAccount entity. Requirement for defining this attribute is “Based on value of AccountType , account should hold minimum balance.”

So for that here, BankAccount object is accessed in IsValid method and then by checking value of the Account type attribute validates AccountBalance value.

Other Things to note here are :
  1. Attribute class is Sealed and Derived from the ValidationAttribute.
  2. Custom attribute class override IsValid method of the base ValidationAttribute class.
  3. Attribute can be used for property and not allowed to define attribute multiple time on property.
To find how to define attribute not specific to entity follow MSDN: https://msdn.microsoft.com/en-us/library/cc668224%28v=vs.140%29.aspx

Random Number in MultiThreading

Random Number in MultiThreading 

 Random Number

Random number class in .net framework used for generating random numbers. Random number class allows creating random number instance by following two constructors
  1. Random() – it make use of system clock as seed value and create instance.
    As random make use of System clock as input when creating two instances as below
                Random rand = new Random();
                Random rand1 = new Random();
    
    It use same system clock input so output of above when doing below code
                Console.WriteLine(rand.Next());
                Console.WriteLine(rand1.Next());
    
    generate same random number. Example both line of code write 10 on console.

  2. Random(int32 seed) – it make use of input integer value and create instance.
    As random make use integer value as input when creating two instance with different input
                  Random rand = new Random(30);
                  Random rand1 = new Random(40);
    
    so output of above when writing below code
           Console.WriteLine(rand.Next());
                  Console.WriteLine(rand1.Next());
    
    Generate different random number.

So by above two way of creating random instance shows that seed value plays important role in creating random number instance.

Random In Multi-Threading

Following is line of code that used as simulator i.e following line of code used to generate which used by other application.
        static void Main(string[] args)
        {   
            Program program = new Program();
            
            char[] publish = new char[] { 'r', 'v'};

            List<Task> tasks = new List<Task>();
            while (true)
            {
                Console.WriteLine("Press any key to publish new data and 'n' to exit");
                char rchar = Convert.ToChar(Console.Read());
                Console.ReadLine();
                if (rchar == 'n')
                    break;

                foreach (char c in publish)
                {
                    if (c == 'r')
                        tasks.Add(Task.Run(() =>program.PublishRateOrVolume(c)));
                    else if (c == 'v')
                        tasks.Add(Task.Run(() =>program.PublishRateOrVolume(c)));
                }

                try
                {
                    Task.WaitAll(tasks.ToArray());
                    foreach (Task<string> t in tasks)
                        Console.WriteLine(t.Result);
                }
                catch (AggregateException ae)
                {
                    Console.WriteLine(ae.ToString());
                }
                tasks.Clear();
            }
            tasks = null;
        }

Above line of code create two tasks in that one task generates rate date and another task generates volume data for publishing data. Things to note in above code is both the task calling same method but with the different input value ‘r’ (rate) and ‘v’ (volume).

        private string PublishRateOrVolume(char publishChar)
        {
            StringBuilder sb = new StringBuilder();
            char[] inputchar = new char[] { '1', '2'};
            string clientName = string.Empty;
            
            var random = new Random();

            try
            {
                foreach (char c in inputchar)
                {
                    if (c == '1')
                        clientName = "Test 1";
                    if (c == '2')
                        clientName = "Test 2";
                 
                    var data = random.NextDouble() * random.Next(0, 500);
                    
                    if (publishChar == 'v')
                        sb.AppendLine("VOLUME Data Publish by Client :" + clientName + " Volume :" + data);
                    else if (publishChar == 'r')
                       sb.AppendLine("RATE Data Publish by Client :" + clientName + " Rate :" + data);
                }
                return sb.ToString();
            }
            finally
            {
                random = null;
                inputchar = null;
                sb = null;
            }
        }

Above code function, called by different task with respected argument to generate volume and rate data. Each task generates volume and rate data for two clients (test 1 and test 2). Things to note in code function creates Random class instance for generating random data.

Above line of code generate following output



Problem with the output is Program generate same data for volume and rate for each client which is not expected, expected result is it generate different random values of rate and value for each client.

What is the issue?

Issue with above code is random number instance get created by two different task almost with the same seed value, as the seed value for both random instance is same it generate same values. It’s already discussed above in random class constructor example.

Following is solution to the problem of random number in multithreading environment
  1. Add Delay between creating two task
    As random instance make use of system clock value adding delay between creation of two task gives different seed value to default random class instance.
    So the code for this is
      foreach (char c in publish)
      {
         if (c == 'r')
            tasks.Add(Task.Run(() =>program.PublishRateOrVolume(c)));
         else if (c == 'v')
            tasks.Add(Task.Run(() =>program.PublishRateOrVolume(c)));
         Thread.Sleep(50);
      }
    

    With the Thread.Sleep small delay is get added between creating of task and as there is delay two instance of random number receive different seed.

    But problem with this solution is it requires to add delay, so if there are more than two task it will create problem, also it cause problem in mission critical application where time is important.

  2. Use only one instance of random class
    According to this solution only one instance of random number class get created and shared between multiple threads. So the code is
     
           static void Main(string[] args)
           {
      Random random = new Random();
      // code as it is
      foreach (char c in publish)
                    {
                        if (c == 'r')
                            tasks.Add(Task.Run(() => program.PublishRateOrVolume(c, random)));
                        else if (c == 'v')
                            tasks.Add(Task.Run(() => program.PublishRateOrVolume(c, random)));
                    }
              }
                 //code as it is
            }
    private string PublishRateOrVolume(char publishChar, Random random)
           {
      //code as it is 
    }
    

    As in code one random instance is created in main method and same instance used by both task to generate random number.

    But problem with this solution is one random number instance is shared between two tasks and random number class is not thread safe.
    As random number instance is not thread safe when two thread call next() method at same time it will generate 0 as output and then afterwards random number generates 0 and not useful. To check try below example
     
                Random rand = new Random();
    
                Parallel.For(0, 1000000, (i, loop) =>
                {
                    if (rand.Next() == 0) loop.Stop();
         });
    

     To avoid problem make use of lock when accessing random instance via it methods like next(), netxtDouble().
     object lockobj = new object();
            lock (lockobj)
            {
                 data= rand.NextDouble() * rand.Next(0, 500);
            }
    

    It resolves issue but problem is lock statement slow down application when there are more number of threads.

  3. Make use of ThreaLocal<T> with the different seed value
    This solution make use of ThreaLocal<T> class, it allows creating local variable for each thread/task. Read more about ThreadLocal class : https://msdn.microsoft.com/en-us/library/dd642243%28v=vs.110%29.aspx
    So the code with ThreaLocal<T> as below
    private string PublishRateOrVolume(char publishChar)
    {
         var random = new ThreadLocal<Random>(() => new
                          Random(Guid.NewGuid().GetHashCode()));
        //code as it is 
        var data = random.Value.NextDouble() * random.Value.Next(0, 500); 
       //code as it is
    }
    
    In code random instance created using ThreaLocal<T> class means each task receive its own local instance of Random class.
    Another thing to note in code is seed value passed when creating Random instance. Seed value is HashCode value of the Guid instance i.e. each time new instance receives new seed value.

Conclusion

Random class is not thread safe and above is three solution to make it thread safe but out of three the third solution is perfect and fits as thread safe solution.

Please find attached code which having all three solution.