Monday, May 7, 2012

Design Pattern : Iterator Pattern Implementation

Iterator pattern allows sequential access of elements with out exposing the inside code. Let’s understand what it means. Let’s say you have a collection of records which you want to browse sequentially and also maintain the current place which recordset is browsed, then the answer is iterator pattern. It’s the most common and unknowingly used pattern. Whenever you use a ‘foreach’ (It allows us to loop through a collection sequentially) loop you are already using iterator pattern to some extent.

Figure: - Iterator business logic

In figure ‘Iterator business logic’ we have the ‘clsIterator’ class which has collection of customer classes. So we have defined an array list inside the ‘clsIterator’ class and a ‘FillObjects’ method which loads the array list with data. The customer collection array list is private and customer data can be looked up by using the index of the array list. So we have public function like ‘getByIndex’ ( which can look up using a particular index) , ‘Prev’ ( Gets the previous customer in the collection , ‘Next’ (Gets the next customer in the collection), ‘getFirst’ ( Gets the first customer in the collection ) and ‘getLast’ ( Gets the last customer in the collection).

So the client is exposed only these functions. These functions take care of accessing the collection sequentially and also it remembers which index is accessed.

Below figures ‘Client Iterator Logic’ shows how the ‘ObjIterator’ object which is created from class ‘clsIterator’ is used to display next, previous, last, first and customer by index.


Figure: - Client Iterator logic

Reference:

Design Pattern : Mediator Pattern Implementation

Many a times in projects communication between components are complex. Due to this the logic between the components becomes very complex. Mediator pattern helps the objects to communicate in a disassociated manner, which leads to minimizing complexity.
Figure: - Mediator sample example

Let’s consider the figure ‘Mediator sample example’ which depicts a true scenario of the need of mediator pattern. It’s a very user-friendly user interface. It has three typical scenarios.
Scenario 1:- When a user writes in the text box it should enable the add and the clear button. In case there is nothing in the text box it should disable the add and the clear button.
Figure: - Scenario 1

Scenario 2:- When the user clicks on the add button the data should get entered in the list box. Once the data is entered in the list box it should clear the text box and disable the add and clear button.
Figure: - Scenario 2

Scenario 3:- If the user click the clear button it should clear the name text box and disable the add and clear button.
Figure: - Scenario 3

Now looking at the above scenarios for the UI we can conclude how complex the interaction will be in between these UI’s. Below figure ‘Complex interactions between components’ depicts the logical complexity.
Figure: - Complex interactions between components

Ok now let me give you a nice picture as shown below ‘Simplifying using mediator’. Rather than components communicating directly with each other if they communicate to centralized component like mediator and then mediator takes care of sending those messages to other components, logic will be neat and clean.
Figure: - Simplifying using mediator
Now let’s look at how the code will look. We will be using C# but you can easily replicate the thought to JAVA or any other language of your choice. Below figure ‘Mediator class’ shows the complete code overview of what the mediator class will look like.

The first thing the mediator class does is takes the references of the classes which have the complex communication. So here we have exposed three overloaded methods by name ‘Register’. ‘Register’ method takes the text box object and the button objects. The interaction scenarios are centralized in ‘ClickAddButton’,’TextChange’ and ‘ClickClearButton’ methods. These methods will take care of the enable and disable of UI components according to scenarios.
Figure: - Mediator class

The client logic is pretty neat and cool now. In the constructor we first register all the components with complex interactions with the mediator. Now for every scenario we just call the mediator methods. In short when there is a text change we can the ‘TextChange’ method of the mediator, when the user clicks add we call the ‘ClickAddButton’ and for clear click we call the ‘ClickClearButton’.
Figure: - Mediator client logic

Reference:
 

C# Iterations: IEnumerator, IEnumerable and Yield

Directly using IEnumerator for iterations

Enumerators are used to read data in the collection. The foreach statement hides the complexity of the enumerators, but you can directly manipulate IEnumerator for customized iterations. Let's do an example:

Code:
List<string> myList = new List<string>();for (int i = 0; i < 10; i++)
{
    myList.Add("Item " + i.ToString());
}
IEnumerator<string> myEnum = myList.GetEnumerator();

myEnum.Reset();           
myEnum.MoveNext();
myEnum.MoveNext();
myEnum.MoveNext();
System.Console.WriteLine(myEnum.Current);
myEnum.MoveNext();
myEnum.MoveNext();
System.Console.WriteLine(myEnum.Current);
myEnum.Reset();
myEnum.MoveNext();
System.Console.WriteLine(myEnum.Current);

Output:
Item 2
Item 4
Item 0

In order to reach the first element, you should run MoveNext method of Enumerator. Initial Position of Enumerator does not point the first element.

Implementing IEnumerable and IEnumerator on your custom objects

IEnumerable interface should be implemented in order to use your custom objects in the form of a collection (series of values or objects). Which means you can use it directly with the foreach statement. IEnumerable interface has a method called GetEnumerator() which returns an object implemented IEnumerator. Let's do an example: PowersOfTwo class implements IEnumerable so any instance of this class can be accessed as a collection.
class PowersOfTwo : IEnumerable<int>
{      
    public IEnumerator<int> GetEnumerator()
    {
        return new PowersOfTwoEnumerator();
    }       
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }       
}
Test:
PowersOfTwo p2 = new PowersOfTwo();foreach (int p in p2)
{
    System.Console.WriteLine(p);
}


Output:

2 4 8 16 32 64 128 256 512 1024


Actually the magic trick lies in the PowersOfTwoEnumerator Class
    class PowersOfTwoEnumerator : IEnumerator<int>
    {
        private int index = 0;
        public int Current
        {
            get { return (int)System.Math.Pow(2, index); }
        }

        object System.Collections.IEnumerator.Current
        {
            get { return Current; }
        }
        public bool MoveNext()
        {
            index++;
            if (index > 10)
                return false;
            else                return true;
        }
        public void Reset()
        {
            index = 0;
        }
        public void Dispose()
        {
        }
    }


Current returns the same element until MoveNext is called. Initial index is zero each MoveNext method incriments the index by 1 up to 10 then it returns false. When the enumerator is at this position, subsequent calls to MoveNext also return false. If the last call to MoveNext returned false, Current is undefined. You cannot set Current to the first element of the collection again; you must create a new enumerator instance instead. IEnumerator inherits IDisposible for performance only.

Using The Yield Keyword

yield keyword is introduced by C# 2.0 in order to implement iteartion easier. On the other hand it has some disadventages. Let's first look at the yield keyword.
public IEnumerable<int> GetPowersofTwo()
{
   for (int i = 1; i < 10; i++)       yield return (int)System.Math.Pow(2, i);   yield break;
}


Yield is not a feature of the .Net runtime. It is just a C# language feature. During compilation Compiler converts yield method and its class to instances of IEnumerable and IEnumerator implemented classes.

Criticism of the keyword "yield"

"yield" has a couple of drawbacks first of all it is designed to simplify implementing iterations. But it can be used to write very ill designed code (like goto). There are many bad examples therefore I am not going to write one here. But using it for other than the intended purpose will make your code hard to follow.

Second problem is that "yield" does not make sense in Object Oriented paradigm just like delegates. I believe as long as languages stick to a single paradigm they become more understandable and structured. When Microsoft introduced C# they decided to use delegates as an event mechanism, instead of interfaces. Delegates are function pointers and have no meaning in OOP. A similar problem exists for yield too, when you look at the above example, the method signature tells you that GetPowersofTwo will return an object implemented IEnumerable. But it is not the case.

Example 2 


In the .NET Framework, there are two interfaces designed to allow you to iterate easily over collections of objects as you would typically do in a for loop. Many classes in the .NET Framework have implemented these interfaces and do their work behind the scenes so you don’t have to worry about how it is done. However, sometimes you want to have the control to do this yourself.
Maybe you have the need to create a custom class that holds a collection of objects, and you want to be able to iterate over them. It’s pretty straightforward to do this in C# or VB.NET. You have to implement two interfaces called IEnumerable and IEnumerator. Below is a trivial example (because it’s already possible to do this with the List class) that illustrates how you would go about implementing these to iterate over a collection of string objects:

using System;
using System.Collections.Generic;
using System.Collections;
 
namespace Demo
{
 public class TestOverride : IEnumerable<string>
 {
                private List<string> _values;
 
                public TestOverride(List<string> values)
                {
                    _values = values;
                }
 
  public IEnumerator<string> GetEnumerator()
  {
      return new TestOverrideEnumerator(_values);
  }
 
  IEnumerator IEnumerable.GetEnumerator()
  {
   return GetEnumerator();
  }
 
  protected class TestOverrideEnumerator : IEnumerator<string>
  {
   private List<string> _values;
   private int _currentIndex;
 
   public TestOverrideEnumerator(List<string> values)
   {
    _values = new List<string>(values); 
    Reset();
   }
 
   public string Current
   {
    get { return _values[_currentIndex]; }
   }
 
   public void Dispose() {}
 
   object IEnumerator.Current
   {
    get { return Current; }
   }
 
   public bool MoveNext()
   {
    _currentIndex++;
    return _currentIndex < _values.Count;
   }
 
   public void Reset()
   {
    _currentIndex = -1;
   }
  }
 }
}
I’m sure there’s a better way to do this, but it should help you get started. Note that you have to implement both classes and that the most work is done in the class that implements IEnumerator. Also note that you can use generics (in this case force it to iterate only over string objects).
You would invoke this functionality this way:

List<string> collection = new List<string>();
collection.Add("abc");
collection.Add("def");
collection.Add("ghi");
 
TestOverride collectionWrapper = new TestOverride(collection);
 
foreach (string x in collectionWrapper)
    Console.Out.WriteLine(x);
 
 
 
 

C# : Yield Statement

Used in an iterator block to provide a value to the enumerator object or to signal the end of iteration. It takes one of the following forms:
yield return <expression>;
yield break;
 
You will want to use the yield keyword in methods that return the
type IEnumerable (without any angle brackets), or the type IEnumerable<Type>
with a type parameter in the angle brackets. You need to reference the System.Collections
namespace for the first version, and the System.Collections.Generic namespace for
the second. 

Example1:
In the following example, the yield statement is used inside an iterator block, which is the method Power(int number, int power). When the Power method is invoked, it returns an enumerable object that contains the powers of a number. Notice that the return type of the Power method is IEnumerable, an iterator interface type.

// yield-example.cs
using System;
using System.Collections;
public class List
{
    public static IEnumerable Power(int number, int exponent)
    {
        int counter = 0;
        int result = 1;
        while (counter++ < exponent)
        {
            result = result * number;
            yield return result;
        }
    }

    static void Main()
    {
        // Display powers of 2 up to the exponent 8:
        foreach (int i in Power(2, 8))
        {
            Console.Write("{0} ", i);
        }
    }
}

Output

 
2 4 8 16 32 64 128 256 
 
 
Example 2: 

using System;
using System.Collections.Generic;
 
    class ExampleYieldReturn
    {
        static void Main(string[] args)
        {
            //with every call it goes to where it left till it encounters yield return
            foreach(int n in GetNumbers())
            {
                Console.WriteLine(n);
            }
 
            Console.ReadLine();
        }
 
    public static IEnumerable<int> GetNumbers()
        {
            Console.WriteLine("Print number 52");
            yield return 52; // will go back to the caller ie foreach
 
            Console.WriteLine("Print number 63");
            yield return 63;// again will go back to the caller ie foreach
 
            Console.WriteLine("Print number 72");
            yield return 72;// again will go back to the caller ie foreach
 
        }
 
    }
 
Output:
Print number 52
52
Print number 63
63
Print number 72
72
Example 3:
 
How to use C# yield to easily return an IEnumerable collection
Using "yield return" instead of "return", you can create IEnumerable collection which you can easily consume in foreach loops and query with LINQ. Notice also that you can just write the method that you want and Visual Studio will allow you to create a stub for it, very convenient.
using System;
using System.Collections.Generic;
using System.Linq;

namespace TestYield
{
    class Program
    {
        static void Main(string[] args)
        {
            //use with foreach
            Console.WriteLine("All ASCII numbers:");
            foreach (int asciiNumber in GetAsciiNumberCollection("This is a test."))
            {
                Console.WriteLine(asciiNumber);
            }

            //use with linq
            Console.WriteLine("Low ASCII numbers:");
            var lowNumbers = from n in GetAsciiNumberCollection("This is a test.")
                             where n <= 90
                             select n;
            foreach (int asciiNumber in lowNumbers)
            {
                Console.WriteLine(asciiNumber);
            }

            Console.ReadLine();
        }

        private static IEnumerable<int> GetAsciiNumberCollection(string line)
        {
            foreach (char letter in line)
            {
                yield return (int)letter;
            }
        }
    }
}

Friday, April 27, 2012

ASP.NET: Data access Layer - Retriving Output Param Value

 public GetAllPermissionResponse GetAllPermission(GetAllPermissionRequest request)
        {
            GetAllPermissionResponse response = new DataContract.GetAllPermissionResponse();

            try
            {

                Database db = DatabaseFactory.CreateDatabase(ConstantManager.CONNECTION_NAME);
                using (DbCommand dbCommand = db.GetStoredProcCommand(ConstantManager.SP_PERMISSION_GETALL))
                {
                    db.AddInParameter(dbCommand, "PageNumber", DbType.Int32, request.PageNumber);
                    db.AddInParameter(dbCommand, "Pagesize", DbType.Int32, request.Pagesize);
                    db.AddInParameter(dbCommand, "SortColumn", DbType.String, request.SortColumn);
                    db.AddInParameter(dbCommand, "SortOrder", DbType.String, request.SortOrder);
                    db.AddOutParameter(dbCommand, "RowCount", DbType.Int32, 5);
                  //  db.AddOutParameter(dbCommand, "PageCount", DbType.Int32, 5);

                    PermissionCollection collection = new DataContract.PermissionCollection();
                    PermissionList list = new DataContract.PermissionList();
                    using (IDataReader dataReader = db.ExecuteReader(dbCommand))
                    {

                        while (dataReader.Read())
                        {
                            Permission obj = new DataContract.Permission();
                            if (dataReader["PermissionID"] != DBNull.Value) { obj.PermissionID = Convert.ToInt64(dataReader["PermissionID"]); }
                            if (dataReader["PermissionName"] != DBNull.Value) { obj.PermissionName = Convert.ToString(dataReader["PermissionName"]); }
                            if (dataReader["PermissionDescription"] != DBNull.Value) { obj.PermissionDescription = Convert.ToString(dataReader["PermissionDescription"]); }
                            if (dataReader["IsActive"] != DBNull.Value) { obj.IsActive = Convert.ToBoolean(dataReader["IsActive"]); }
                            if (dataReader["CreatedDate"] != DBNull.Value) { obj.CreatedDate = Convert.ToDateTime(dataReader["CreatedDate"]); }
                            if (dataReader["CreatedBy"] != DBNull.Value) { obj.CreatedBy = Convert.ToInt64(dataReader["CreatedBy"]); }
                            if (dataReader["UpdatedDate"] != DBNull.Value) { obj.UpdatedDate = Convert.ToDateTime(dataReader["UpdatedDate"]); }
                            if (dataReader["UpdatedBy"] != DBNull.Value) { obj.UpdatedBy = Convert.ToInt64(dataReader["UpdatedBy"]); }

                            collection.Add(obj);

                        }
                    }

                    var rowcount = Convert.ToInt32(db.GetParameterValue(dbCommand, "RowCount"));
                   // var pagecount = Convert.ToInt32(db.GetParameterValue(dbCommand, "PageCount"));
                    list.Rows = collection;
                    list.TotalRowCount = rowcount;
                   // list.NoOfPages = pagecount;
                    response.Response = list;
                }


            }
            catch (Exception exception)
            {
                ExceptionManager.HandleDataException(exception, ConstantManager.DATA_EXCEPTIONPOLICY);
            }
            return response;
        }

ASP.NET: Data access Layer using Enterprise Lib

        private const string Config = "ConnectionString";
        public bool Insert(Destination destination)
        {
            Database db = DatabaseFactory.CreateDatabase(Config);
            DbCommand dbCommand = db.GetStoredProcCommand("uspSaveDestination");
            db.AddInParameter(dbCommand, "DestinationID", DbType.Int64, destination.DestinationID);
            db.AddInParameter(dbCommand, "DestinationName", DbType.String, destination.DestinationName);
            db.AddInParameter(dbCommand, "Description", DbType.String, destination.Description);
            return (db.ExecuteNonQuery(dbCommand) == 1);
        }
        public bool Update(Destination destination)
        {
            Database db = DatabaseFactory.CreateDatabase(Config);
            DbCommand dbCommand = db.GetStoredProcCommand("uspSaveDestination");
            db.AddInParameter(dbCommand, "DestinationID", DbType.Int64, destination.DestinationID);
            db.AddInParameter(dbCommand, "DestinationName", DbType.String, destination.DestinationName);
            db.AddInParameter(dbCommand, "Description", DbType.String, destination.Description);
            return (db.ExecuteNonQuery(dbCommand) == 1);
        }
        public bool Delete(long DestinationID)
        {
            Database db = DatabaseFactory.CreateDatabase(Config);
            DbCommand dbCommand = db.GetStoredProcCommand("uspDeleteDestination");
            db.AddInParameter(dbCommand, "DestinationID", DbType.Int64, DestinationID);
            return (db.ExecuteNonQuery(dbCommand) == 1);
        }
        public IList<Destination> GetAll()
        {
            Database db = DatabaseFactory.CreateDatabase(Config);
            DbCommand dbCommand = db.GetStoredProcCommand("uspGetAllDestination");
            List<Destination> list = new List<Destination>();
            using (IDataReader dataReader = db.ExecuteReader(dbCommand))
            {
                while (dataReader.Read())
                {
                    Destination obj = new Destination();
                    if (dataReader["DestinationID"] != DBNull.Value) { obj.DestinationID = (Int64)dataReader["DestinationID"]; }
                    if (dataReader["DestinationName"] != DBNull.Value) { obj.DestinationName = (String)dataReader["DestinationName"]; }
                    if (dataReader["Description"] != DBNull.Value) { obj.Description = (String)dataReader["Description"]; }
                    list.Add(obj);
                }
            }
            return list;
        }
        public Destination GetByID(long DestinationID)
        {
            Database db = DatabaseFactory.CreateDatabase(Config);
            DbCommand dbCommand = db.GetStoredProcCommand("uspGetDestinationByID");
            db.AddInParameter(dbCommand, "DestinationID", DbType.Int64, DestinationID);

            Destination obj = new Destination();
            using (IDataReader dataReader = db.ExecuteReader(dbCommand))
            {
                while (dataReader.Read())
                {
                    if (dataReader["DestinationID"] != DBNull.Value) { obj.DestinationID = (Int64)dataReader["DestinationID"]; }
                    if (dataReader["DestinationName"] != DBNull.Value) { obj.DestinationName = (String)dataReader["DestinationName"]; }
                    if (dataReader["Description"] != DBNull.Value) { obj.Description = (String)dataReader["Description"]; }
                }
            }
            return obj;
        }

SQL SERVER : Dynamic Paging , Sorting

Example 1
GO
/******
-- Date                Name            Description
-- 04/27/2012        Vijay Mishra    Created



 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
alter PROCEDURE [dbo].[SP_PERMISSION_SEARCH]
@PermissionID bigint=null,
@PermissionName nvarchar(500)=null,
@PermissionDescription nvarchar(max)=null,
@PageNumber int=0,
@Pagesize int=0,
@SortColumn nvarchar(50)=null,
@SortOrder nvarchar(10)=null,
@RowCount int Output

AS
BEGIN         
      
   DECLARE @FirstRecord int, @LastRecord int
   SELECT @FirstRecord = ((@PageNumber - 1) * @Pagesize) + 1
   SELECT @LastRecord = (@PageNumber * @Pagesize )
            
   -- Set the ROWCOUNT to the @FirstRecord from where data read starts
   SET ROWCOUNT @FirstRecord
   -- Get the first row from Table (based on above statement it would retrive only one row)
   DECLARE @FirstRow int
   SELECT @FirstRow = PermissionID FROM [PEGASUS_TBL_PERMISSION] ORDER BY PermissionID asc  
  
   -- Now, set the row count to @Pagesize(maximum rows) and get
    -- all records >= @FirstRow
   SET ROWCOUNT @Pagesize
   -- execute the required condition  
   select * from [PEGASUS_TBL_PERMISSION]
   WHERE (@PermissionName IS NULL OR PermissionName LIKE '%' + @PermissionName + '%')      
      AND (@PermissionDescription IS NULL OR PermissionDescription LIKE '%' + @PermissionDescription + '%')
      AND (@PermissionID IS NULL OR PermissionID = @PermissionID)
    and PermissionID >= @FirstRow
    order by
          CASE WHEN @SortColumn='PermissionID' AND @SortOrder='DESC' THEN PermissionID END DESC,
        CASE WHEN @SortColumn='PermissionID' AND @SortOrder='ASC' THEN PermissionID END ASC,
        CASE WHEN @SortColumn='PermissionName' AND @SortOrder='DESC' THEN PermissionName END DESC,
        CASE WHEN @SortColumn='PermissionName' AND @SortOrder='ASC' THEN PermissionName END ASC,     
        CASE WHEN @SortColumn='PermissionDescription' AND @SortOrder='DESC' THEN PermissionName END DESC,
        CASE WHEN @SortColumn='PermissionDescription' AND @SortOrder='ASC' THEN PermissionName END ASC     
    -- Set total resulted ROWCOUNT
    set @RowCount=@@ROWCOUNT  
    SET ROWCOUNT 0
   
     
END

Example 2


GO
/****** Object:  StoredProcedure [dbo].[SP_PERMISSION_SEARCH_VIJAY]    Script Date: 04/27/2012 15:09:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
alter PROCEDURE [dbo].[PEGASUS_SP_PERMISSION_SEARCH_VIJAY1]
@PermissionID bigint=null,
@PermissionName nvarchar(500)=null,
@PermissionDescription nvarchar(max)=null,
@PageNumber int=0,
@Pagesize int=0,
@SortColumn nvarchar(50)=null,
@SortOrder nvarchar(10)=null,
@RowCount int Output

AS
BEGIN         
          --
           DECLARE @FirstRecord int, @LastRecord int
           SELECT @FirstRecord = ((@PageNumber - 1) * @Pagesize) + 1
           SELECT @LastRecord = (@PageNumber * @Pagesize )
           --Get Total rowcount          
           set @RowCount= (select COUNT(0) from [PEGASUS_TBL_PERMISSION])               
       -- Prepare Common Table               
      ;With PERMISSION AS(SELECT PermissionID,PermissionName,PermissionDescription, ROW_NUMBER() OVER
       (order by
          CASE WHEN @SortColumn='PermissionID' AND @SortOrder='DESC' THEN PermissionID END DESC,
        CASE WHEN @SortColumn='PermissionID' AND @SortOrder='ASC' THEN PermissionID END ASC,
        CASE WHEN @SortColumn='PermissionName' AND @SortOrder='DESC' THEN PermissionName END DESC,
        CASE WHEN @SortColumn='PermissionName' AND @SortOrder='ASC' THEN PermissionName END ASC     
       ) as RowNumber, ROW_NUMBER() OVER(ORDER BY PermissionID ASC) AS Total FROM [PEGASUS_TBL_PERMISSION]
      WHERE (@PermissionName IS NULL OR PermissionName LIKE '%' + @PermissionName + '%')      
      AND (@PermissionDescription IS NULL OR PermissionDescription LIKE '%' + @PermissionDescription + '%')
      AND (@PermissionID IS NULL OR PermissionID = @PermissionID)
      )
      , PermissionCount  as
      (
      SELECT COUNT(0) CNT FROM PERMISSION
     
      )       
   
   --   --Select required colums
      select PermissionID,PermissionName,PermissionDescription,Total+RowNumber -1 as Totalrows
      from PERMISSION
      Where RowNumber >=  case when @FirstRecord = 1 then RowNumber else @FirstRecord end and
            RowNumber <=   case when @LastRecord = 0 then  RowNumber else @LastRecord end
     
  
   
     
END