Friday, February 25, 2011

Compressing and Decompressing Dataset in C#



Some times we need to Compress the Dataset, if it holds large data, before sending over network. If you are using web services or WCF Services ,It is better to compress the dataset to byte array before sending over the network. You can decompress the byte array to dataset. Here is some code snippet to do that using System.IO.Compression.


   1:  using System;
   2:  using System.IO;
   3:  using System.Data;
   4:  using System.IO.Compression;
   5:   
   6:  namespace TestApp
   7:  {
   8:      public class DataSetCompressor
   9:      {
  10:   
  11:          public Byte[] Compress(DataSet dataset) 
  12:          { 
  13:              Byte[] data; 
  14:              MemoryStream mem = new MemoryStream(); 
  15:              GZipStream zip = new GZipStream(mem, CompressionMode.Compress); 
  16:              dataset.WriteXml(zip, XmlWriteMode.WriteSchema);
  17:              zip.Close();
  18:              data = mem.ToArray();
  19:              mem.Close(); 
  20:              return data; 
  21:          }          
  22:          public DataSet Decompress(Byte[] data) 
  23:          { 
  24:              MemoryStream mem = new MemoryStream(data);
  25:              GZipStream zip = new GZipStream(mem, CompressionMode.Decompress); 
  26:              DataSet dataset = new DataSet(); 
  27:              dataset.ReadXml(zip, XmlReadMode.ReadSchema); 
  28:              zip.Close();
  29:              mem.Close();
  30:              return dataset;
  31:          }
  32:      }
  33:  }

Converting MS SQL Database to MySQL

If you want to Convert your sql server database tables, stroed procs, functions etc to Mysql ,you can use this tool . Here is the URL

http://www.ispirer.com/products/sql-server-to-mysql-migration

You can either use free evaluation or can purchase. You need to register before downloading the tool.

Friday, February 18, 2011

Implementing Paging in DataList using ASP.Net / C#



In ASP.Net , the controls commonly used for displaying large data are GridView,DataList,Repeater etc.
GridView has built in paging functionalitiy. DataList is another flexible control in which we can display data with Repeat direction either horizontal or vertical , we can specify the repeatcolums as well. But unfortunately DataList control does't have built-in Paging functionality. You need to implement it. A variety of ways are there. Here I am explaining how to do it with C# code.

My Scenario is to Load all categories starting with a letter when clicking on that letter, but it should show say first 10 categories and the next , prev etc...If clicking another letter load categories starting with that letter and then do paging.

Here is my aspx code


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PagingTest.aspx.cs" Inherits="PagingTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Paging in DataList</title>

</head><body>
<form runat="server">
    <h3>Implementing Datalist Paging </h3>
<a name="BookMark"></a>
<asp:DataList ID="DataList1" runat="server" RepeatColumns="4" 
                                        RepeatDirection="Horizontal">
                                        <ItemTemplate>
                                            <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                                <tr>
                                                    <td align="left" valign="top" width="18">
                                                        &nbsp;</td>
                                                    <td align="left" valign="top" width="225">
                                                        <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                                            <tr>
                                                                <td align="left" valign="middle" width="15">
                                                                    <img height="6" src="images/arrow.jpg" width="3" /></td>
                                                                <td align="left" class="style1" valign="middle">
                                                                    <asp:HyperLink ID="LinkButton2" runat="server" CssClass="listlink" 
                                                                        NavigateUrl='<%# "Search.aspx?mode=1&Search=" + Convert.ToString(Eval("classname"))%>' 
                                                                        Text='<%# Convert.ToString(Eval("classname")) %>'></asp:HyperLink>
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                </tr>
                                            </table>
                                        </ItemTemplate>
                                    </asp:DataList>
<table width="100%">
  <tr>
    <td width=42%" align="left">
      <asp:label ID="lblCounts" Runat="server"  />
    </td>
    <td width=4% valign="bottom">
      <a href="#" id="First" OnServerClick="ShowFirstPage" runat="server">
      <img src="images/firstpage.gif" border="0"></a>
    </td>
    <td width=4% valign="bottom">
      <a href="#" id="Previous" OnServerClick="ShowPreviousPage" runat="server">
      <img src="images/prevpage.gif" border="0"></a>
    </td>
    <td width=4% valign="bottom">
      <a hhref="#" id="Next" OnServerClick="ShowNextPage" runat="server">
      <img src="images/nextpage.gif" border="0"></a>
    </td>
    <td width=4% valign="bottom">
      <a href="#" id="Last" OnServerClick="ShowLastPage" runat="server">
      <img src="images/lastpage.gif" border="0"></a>
    </td>
    <td width="42%" align="center">
        <asp:Button ID="btnLetterA" runat="server"  Text="A" 
            Width="100px" onclick="btnLetterA_Click"  />
        <asp:Button ID="btnLetterB" runat="server"  Text="B" 
            Width="100px" onclick="btnLetterB_Click" />
        <asp:Button ID="btnLetterC" runat="server"  Text="C" 
            Width="100px" onclick="btnLetterC_Click" />
      </td>
  </tr>
</table>
<asp:label ID="LabelRecordCount" Visible="False" Runat="server" />
<asp:label ID="LabelCurrentIndex" Visible="False" Text="0" Runat="server" />
<asp:label ID="LabelPageSize" Visible="False" Text="30" Runat="server" />
</form>
</body>
</html>

Here is my Code behind


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class PagingTest : System.Web.UI.Page
{
    DataTable dtbl;
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            PrevFilter = string.Empty;
            Filter = "A";
            BindTheData();
     
        }
    }
    private void BindTheData()
    {
        if (PrevFilter!=Filter)
        {
            PrevFilter = Filter;
            LabelCurrentIndex.Text = "0";
            dtbl = Search.loadCategories(Filter);
            LabelRecordCount.Text = dtbl.Rows.Count.ToString();
        }
        DataSet dataSet=new DataSet();
        dataSet = Search.loadCategories_ByPage(Filter, int.Parse(LabelCurrentIndex.Text), int.Parse(LabelPageSize.Text));
        DataList1.DataSource = dataSet.Tables["categories"].DefaultView;
        DataList1.DataBind();
        ShowCounts();
    }
    public void ShowFirstPage(object sender, EventArgs e)
    {
        LabelCurrentIndex.Text = "0";
        BindTheData();
    }
    public void ShowPreviousPage(object sender, EventArgs e)
    {
        LabelCurrentIndex.Text = (int.Parse(LabelCurrentIndex.Text) - int.Parse(LabelPageSize.Text)).ToString();
        if (int.Parse(LabelCurrentIndex.Text) < 0)
        {
            LabelCurrentIndex.Text = "0";
        }
        BindTheData();
    }
    public void ShowNextPage(object sender, EventArgs e)
    {
        if (int.Parse(LabelCurrentIndex.Text) + int.Parse(LabelPageSize.Text) < int.Parse(LabelRecordCount.Text))
        {
            LabelCurrentIndex.Text = (int.Parse(LabelCurrentIndex.Text) + int.Parse(LabelPageSize.Text)).ToString();
        }
        BindTheData();
    }
    public void ShowLastPage(object sender, EventArgs e)
    {
        int intMod;
        intMod = int.Parse(LabelRecordCount.Text) % int.Parse(LabelPageSize.Text);
        if (intMod > 0)
        {
            LabelCurrentIndex.Text = (int.Parse(LabelRecordCount.Text) - intMod).ToString();
        }
        else
        {
            LabelCurrentIndex.Text = (int.Parse(LabelRecordCount.Text) - int.Parse(LabelPageSize.Text)).ToString();
        }

        BindTheData();
    }
    private void ShowCounts()
    {
        string curPage = "";
        if (int.Parse(LabelRecordCount.Text) % int.Parse(LabelPageSize.Text) > 0)
        {
            curPage = (Math.Truncate(Convert.ToDecimal(LabelRecordCount.Text) / int.Parse(LabelPageSize.Text) + 1)).ToString();
        }
        else
        {
            curPage = (Math.Truncate(Convert.ToDecimal(LabelRecordCount.Text) / int.Parse(LabelPageSize.Text))).ToString();
        }
        lblCounts.Text = "Showing Page:<b>" + (int.Parse(LabelCurrentIndex.Text) / int.Parse(LabelPageSize.Text) + 1).ToString() + "</b> of <b>" + curPage;
   
    }
    string Filter
    {
        get
        {
            object o = ViewState["Filter"];
            return (o != null) ? (string)o : string.Empty;
        }
        set
        {
            ViewState["Filter"] = value;
        }
    }
    string PrevFilter
    {
        get
        {
            object o = ViewState["PrevFilter"];
            return (o != null) ? (string)o : string.Empty;
        }
        set
        {
            ViewState["PrevFilter"] = value;
        }
    }
  
    protected void btnLetterB_Click(object sender, EventArgs e)
    {
        Filter = "B";
        BindTheData();
    }
    protected void btnLetterC_Click(object sender, EventArgs e)
    {
        Filter = "C";
        BindTheData();
    }
    protected void btnLetterA_Click(object sender, EventArgs e)
    {
        Filter = "A";
        BindTheData();
    }
}
I have a class Search which contains a static function , which calling from the code behind to populate data. Here is the function


public static DataSet LoadCategories_ByPage(string letter, int curIndex, int PageSize)
    {
        DataSet dtCategories = new DataSet();
        using (SqlConnection dbConn = new SqlConnection(source))
        {
            string selectCmd = "select distinct category from category_table where category like '" + letter + "%' order by category asc";
            dbConn.Open();
            if (dbConn.State == ConnectionState.Open)
            {
                using (SqlDataAdapter sqlAdptr = new SqlDataAdapter(selectCmd, dbConn))
                {
                    sqlAdptr.Fill(dtCategories, curIndex, PageSize, "categories");
                }

            }
        }

        return dtCategories;
    }

Tuesday, February 15, 2011

Data Validation with Regular Expressions in C#

Here is some C# functions that validate Numbers, Email and Alpha numeric values

Note : using System.Text.RegularExpressions;


public static bool IsNumber(String strNumber)
        {
            Regex objNotNumberPattern = new Regex("[^0-9.-]");
            Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
            Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
            String strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
            String strValidIntegerPattern = "^([-]|[0-9])[0-9]*$";
            Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")");
            return !objNotNumberPattern.IsMatch(strNumber) &&
            !objTwoDotPattern.IsMatch(strNumber) &&
            !objTwoMinusPattern.IsMatch(strNumber) &&
            objNumberPattern.IsMatch(strNumber);
        }
        // Function to Test for Positive Number both Integer & Real 
        public static bool IsPositiveNumber(String strNumber)
        {
            Regex objNotPositivePattern = new Regex("[^0-9.]");
            Regex objPositivePattern = new Regex("^[.][0-9]+$|[0-9]*[.]*[0-9]+$");
            Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
            return !objNotPositivePattern.IsMatch(strNumber) &&
            objPositivePattern.IsMatch(strNumber) &&
            !objTwoDotPattern.IsMatch(strNumber);
        }
        
        // Function to test for Positive Integers. 
        public static bool IsNaturalNumber(String strNumber)
        {
            Regex objNotNaturalPattern = new Regex("[^0-9]");
            Regex objNaturalPattern = new Regex("0*[1-9][0-9]*");
            return !objNotNaturalPattern.IsMatch(strNumber) &&
            objNaturalPattern.IsMatch(strNumber);
        }
        // Function to test for Positive Integers with zero inclusive 
        public static bool IsWholeNumber(String strNumber)
        {
            Regex objNotWholePattern = new Regex("[^0-9]");
            return !objNotWholePattern.IsMatch(strNumber);
        }
        // Function to Test for Integers both Positive & Negative 
        public static bool IsInteger(String strNumber)
        {
            Regex objNotIntPattern = new Regex("[^0-9-]");
            Regex objIntPattern = new Regex("^-[0-9]+$|^[0-9]+$");
            return !objNotIntPattern.IsMatch(strNumber) && objIntPattern.IsMatch(strNumber);
        }
        // Function To test for Alphabets. 
        public static bool IsAlpha(String strToCheck)
        {
            Regex objAlphaPattern = new Regex("[^a-zA-Z]");
            return !objAlphaPattern.IsMatch(strToCheck);
        }
        // Function to Check for AlphaNumeric.
        public static bool IsAlphaNumeric(String strToCheck)
        {
            Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]");
            return !objAlphaNumericPattern.IsMatch(strToCheck);
        }

 public static bool IsEmail(string strEmail)
        {
            string patternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                       + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                       + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                       + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                       + @"[a-zA-Z]{2,}))$";
            Regex emailregex = new Regex(patternStrict);
                      
            Match m = emailregex.Match(strEmail);
            if (m.Success)
                return true;
            else
                return false;

        }

Monday, February 14, 2011

Generating Random Passwords and checking Password strength in C#





Here is some code for generating random passwords and checking Password strength  based on some criterias  in C#



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

public static class RandomPasswordGenerator
    {
        // Define default min and max password lengths.
        private static int DEFAULT_MIN_PASSWORD_LENGTH = 8;
        private static int DEFAULT_MAX_PASSWORD_LENGTH = 10;
        // Define supported password characters divided into groups.
        // You can add (or remove) characters to (from) these groups.
        private static string PASSWORD_CHARS_LCASE = "abcdefghijkmnopqrstuvwxyz";
        private static string PASSWORD_CHARS_UCASE = "ABCDEFGHJKLMNPQRSTUVWXYZ";
        private static string PASSWORD_CHARS_NUMERIC = "23456789";
        private static string PASSWORD_CHARS_SPECIAL = "*$-+?_&=!%{}/";
        public static string Generate()
        {
            return Generate(DEFAULT_MIN_PASSWORD_LENGTH,
                            DEFAULT_MAX_PASSWORD_LENGTH);
        }
        public static string Generate(int length)
        {
            return Generate(length, length);
        }
        public static string Generate(int minLength,
                                 int maxLength)
        {
            // Make sure that input parameters are valid.
            if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
                return null;
            // Create a local array containing supported password characters
            // grouped by types. You can remove character groups from this
            // array, but doing so will weaken the password strength.
            char[][] charGroups = new char[][] 
        {
            PASSWORD_CHARS_LCASE.ToCharArray(),
            PASSWORD_CHARS_UCASE.ToCharArray(),
            PASSWORD_CHARS_NUMERIC.ToCharArray(),
            PASSWORD_CHARS_SPECIAL.ToCharArray()
        };
            // Use this array to track the number of unused characters in each
            // character group.
            int[] charsLeftInGroup = new int[charGroups.Length];
            // Initially, all characters in each group are not used.
            for (int i = 0; i < charsLeftInGroup.Length; i++)
                charsLeftInGroup[i] = charGroups[i].Length;
            // Use this array to track (iterate through) unused character groups.
            int[] leftGroupsOrder = new int[charGroups.Length];
            // Initially, all character groups are not used.
            for (int i = 0; i < leftGroupsOrder.Length; i++)
                leftGroupsOrder[i] = i;
            // Because we cannot use the default randomizer, which is based on the
            // current time (it will produce the same "random" number within a
            // second), we will use a random number generator to seed the
            // randomizer.
            // Use a 4-byte array to fill it with random bytes and convert it then
            // to an integer value.
            byte[] randomBytes = new byte[4];
            // Generate 4 random bytes.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(randomBytes);
            // Convert 4 bytes into a 32-bit integer value.
            int seed = (randomBytes[0] & 0x7f) << 24 |
                        randomBytes[1] << 16 |
                        randomBytes[2] << 8 |
                        randomBytes[3];
            // Now, this is real randomization.
            Random random = new Random(seed);
            // This array will hold password characters.
            char[] password = null;
            // Allocate appropriate memory for the password.
            if (minLength < maxLength)
                password = new char[random.Next(minLength, maxLength + 1)];
            else
                password = new char[minLength];
            // Index of the next character to be added to password.
            int nextCharIdx;
            // Index of the next character group to be processed.
            int nextGroupIdx;
            // Index which will be used to track not processed character groups.
            int nextLeftGroupsOrderIdx;
            // Index of the last non-processed character in a group.
            int lastCharIdx;
            // Index of the last non-processed group.
            int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
            // Generate password characters one at a time.
            for (int i = 0; i < password.Length; i++)
            {
                // If only one character group remained unprocessed, process it;
                // otherwise, pick a random character group from the unprocessed
                // group list. To allow a special character to appear in the
                // first position, increment the second parameter of the Next
                // function call by one, i.e. lastLeftGroupsOrderIdx + 1.
                if (lastLeftGroupsOrderIdx == 0)
                    nextLeftGroupsOrderIdx = 0;
                else
                    nextLeftGroupsOrderIdx = random.Next(0,
                                                         lastLeftGroupsOrderIdx);
                // Get the actual index of the character group, from which we will
                // pick the next character.
                nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];
                // Get the index of the last unprocessed characters in this group.
                lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;
                // If only one unprocessed character is left, pick it; otherwise,
                // get a random character from the unused character list.
                if (lastCharIdx == 0)
                    nextCharIdx = 0;
                else
                    nextCharIdx = random.Next(0, lastCharIdx + 1);
                // Add this character to the password.
                password[i] = charGroups[nextGroupIdx][nextCharIdx];
                // If we processed the last character in this group, start over.
                if (lastCharIdx == 0)
                    charsLeftInGroup[nextGroupIdx] =
                                              charGroups[nextGroupIdx].Length;
                // There are more unprocessed characters left.
                else
                {
                    // Swap processed character with the last unprocessed character
                    // so that we don't pick it until we process all characters in
                    // this group.
                    if (lastCharIdx != nextCharIdx)
                    {
                        char temp = charGroups[nextGroupIdx][lastCharIdx];
                        charGroups[nextGroupIdx][lastCharIdx] =
                                    charGroups[nextGroupIdx][nextCharIdx];
                        charGroups[nextGroupIdx][nextCharIdx] = temp;
                    }
                    // Decrement the number of unprocessed characters in
                    // this group.
                    charsLeftInGroup[nextGroupIdx]--;
                }
                // If we processed the last group, start all over.
                if (lastLeftGroupsOrderIdx == 0)
                    lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
                // There are more unprocessed groups left.
                else
                {
                    // Swap processed group with the last unprocessed group
                    // so that we don't pick it until we process all groups.
                    if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
                    {
                        int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
                        leftGroupsOrder[lastLeftGroupsOrderIdx] =
                                    leftGroupsOrder[nextLeftGroupsOrderIdx];
                        leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
                    }
                    // Decrement the number of unprocessed groups.
                    lastLeftGroupsOrderIdx--;
                }
            }
            // Convert password characters into a string and return the result.
            return new string(password);
        }
        // this function actually checking whether the password is strong based on some criterias
        public static bool IsPasswordStrong(string passwd)
        {
           
            bool isContainsLCase = false;
            bool isContainsUCase = false;
            bool isContainsNumeric = false;
            char[] PASSWORD_CHAR_LCASE = { 'a', 'b', 'c', 'd', 'e', 'f', 'g','h', 'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's', 't','u','v', 'w', 'x', 'y', 'z' };
            char[] PASSWORD_CHAR_UCASE = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','I', 'J', 'K', 'L', 'M', 'N','O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
            char[] PASSWORD_CHAR_NUMERIC = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9' };
            char[] PASSWORD_CHAR_SPECIAL = "*$-+?_&=!%{}/".ToCharArray();
            //checking length
            if (passwd.Length < 6)
            {
                return false;
            }
            // checking uppercase exists or not you can add or remove the letters you want
            foreach (char ch in PASSWORD_CHAR_LCASE)
            {
                if (passwd.IndexOf(ch) > -1)
                {
                    if (ch == 'l')
                    {
                        isContainsLCase = false;
                        break;
                    }
                    else
                    {
                        isContainsLCase = true;
                      
                    }
                }
            }
            if (isContainsLCase == false) // No Lowercase found or invalid letter found so return false
            {
                return false;
            }
            // checking uppercase exists or not
            foreach (char ch in PASSWORD_CHAR_UCASE)
            {
                if (passwd.IndexOf(ch) > -1)
                {
                    if (ch == 'I' || ch=='O')
                    {
                        isContainsUCase = false;
                        break;
                    }
                    else
                    {
                        isContainsUCase = true;
                    }
                   
                }
            }
            if (isContainsUCase == false) // No Uppercase found or invalid uppercase found so return false
            {
                return false;
            }
            // checking numeric value exists or not
            foreach (char ch in PASSWORD_CHAR_NUMERIC)
            {
                if (passwd.IndexOf(ch) > -1)
                {
                    if (ch == '0' || ch == '1')
                    {
                        isContainsNumeric = false;
                        break;
                    }
                    else
                    {
                        isContainsNumeric = true;
                    }
                }
            }
            if (isContainsNumeric == false) // No Numeric found or invalid numeric found so return false
            {
                return false;
            }
            return true;
        }
    }

Saturday, February 12, 2011

Implementing Events and Delegates in C#





Events and Delegates

If you are a C# progarmmer, you might have read a lot of about Events and delegates. Before reading this article you must read the previous article "The Observer Design Pattern and Events and delegates in C#" .
Here I am presenting some C# code which clearly shows how events and delegates works !!

In this sample we have a clock class which acts as the publisher and two other classes  DisplayClock and TimeLogEntry which acts as subscribers. Both these classes registered with the publishers SecondChanged event. On each second changed , the subscribers will be notified.

Here is the code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Delegate_Event_Ex
{
    // Clock class is the publisher , who triggers the event
    public class Clock
    {
        public delegate void SecondChangeHandler(object clock, TimeInfoEventArgs timeinformation);
        public event SecondChangeHandler SecondChanged;
        int hour;
        int minute;
        int second;
        public void Start()
        {
            while (true)
            {
                Thread.Sleep(100);
                DateTime dt = DateTime.Now;
                if (dt.Second != second)
                {
                    TimeInfoEventArgs timeArgs = new TimeInfoEventArgs(dt.Hour, dt.Minute, dt.Second);
                    if (SecondChanged != null)
                    {
                        SecondChanged(this, timeArgs);
                    }
                }
                this.hour = dt.Hour;
                this.minute = dt.Minute;
                this.second = dt.Second;
            }
        }

    }
    public class TimeInfoEventArgs : EventArgs
    {
       public int hour;
       public int minute;
       public int second;
        public TimeInfoEventArgs(int h, int m, int s)
        {
            this.hour = h;
            this.minute = m;
            this.second = s;
        }
    }
    //DisplayClock class is one of the Subscribers,who is responding to the event
    public class DisplayClock
    {
        public void Subscribe(Clock theClock)
        {
           // theClock.SecondChanged += new Clock.SecondChangeHandler(TimeHasChanged);
            theClock.SecondChanged += delegate(object theClock1, TimeInfoEventArgs ti)
            {
                Console.WriteLine("Calling Anonymous-Current Time: {0}:{1}:{2}",
                  ti.hour.ToString(), ti.minute.ToString(), ti.second.ToString());
            };
        }
        public void TimeHasChanged(object theClock, TimeInfoEventArgs ti)
        {
            Console.WriteLine("Current Time: {0}:{1}:{2}",
             ti.hour.ToString(), ti.minute.ToString(), ti.second.ToString());
        }
    }
    //TimeLogEntry Class is one of the Subscribers,who is responding to the event
    public class TimeLogEntry
    {
        public void Subscribe(Clock theClock)
        {
            theClock.SecondChanged += new Clock.SecondChangeHandler(LogEntry);
            theClock.SecondChanged +=
                                (aClock, ti) =>
                                {
                                    Console.WriteLine("Calling Lambda Expression-Current Time: {0}:{1}:{2}",
                                                       ti.hour.ToString(),
                                                       ti.minute.ToString(),
                                                       ti.second.ToString());
                                };
        }
        public void LogEntry(object theClock, TimeInfoEventArgs ti)
        {
            Console.WriteLine("Writing Log - Current Time: {0}:{1}:{2}",
            ti.hour.ToString(), ti.minute.ToString(), ti.second.ToString());
        }
    }
    public class MyTester
    {
        public void Run()
        {
            Clock clock = new Clock();
            DisplayClock dc = new DisplayClock();
            dc.Subscribe(clock);
            TimeLogEntry tle = new TimeLogEntry();
            tle.Subscribe(clock);
            //Console.WriteLine("Calling the method directly!");
            //System.DateTime dt = System.DateTime.Now.AddHours(2);
            //TimeInfoEventArgs timeInformation =
            //    new TimeInfoEventArgs(dt.Hour, dt.Minute, dt.Second);
            //clock.SecondChanged(clock, timeInformation);
            clock.Start();
        }
        
        
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyTester tester = new MyTester();
            tester.Run();
        }
    }
}

The output will be like this ( click on the Image to view large)


The Observer Design Pattern and Events and delegates in C#

The Observer Pattern

The Observer Pattern belongs to the behavioural pattern. Also termed as "Publisher-Subscriber" Model.
This pattern
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Let me tell you a real world example. Consider an Aution process. What is actually happening there. There is an Auctioneer and a lot of bidders . When the acutioneer call the aution the bidders respond accordingly.

So the basic idea is there is an object which acts as publisher and a number of object which acts as subscribers, who are registered with the publisher. So the publisher changes something all the registered subscribers will be notified.

The events and delegates in C# is implemented based on this pattern


C# Code Sample
using System;
using System.Collections;
class ObserverDemo
{
static void Main()
{
// Configure Observer pattern
ConcretePublisher s = new ConcretePublisher();
s.Attach(new ConcreteObserver(s,"X"));
s.Attach(new ConcreteObserver(s,"Y"));
s.Attach(new ConcreteObserver(s,"Z"));
// Change Publisher and notify observers
s.PublisherState = "ABC";
s.Notify();
// Wait for user
Console.Read();
}
}
// "Publisher"
abstract class Publisher
{
private ArrayList observers = new ArrayList();
public void Attach(Observer observer)
{
observers.Add(observer);
}
public void Detach(Observer observer)
{
observers.Remove(observer);
}
public void Notify()
{
foreach (Observer o in observers)
{
o.Update();
}
}
}
// "ConcretePublisher"
class ConcretePublisher : Publisher
{
private string PublisherState;
// Property
public string PublisherState
{
get{ return PublisherState; }
set{ PublisherState = value; }
}
}
// "Observer"
abstract class Observer
{
public abstract void Update();
}
// "ConcreteObserver"
class ConcreteObserver : Observer
{
private string name;
private string observerState;
private ConcretePublisher publisher;
// Constructor
public ConcreteObserver(
ConcretePublisher publisher, string name)
{
this.Publisher = publisher;
this.name = name;
}
public override void Update()
{
observerState = Publisher.PublisherState;
Console.WriteLine("Observer {0}'s new state is {1}",
name, observerState);
}
// Property
public ConcretePublisher Publisher
{
get { return publisher; }
set { publisher = value; }
}
}

Converting Class to XML and XML to Class in C# 4.0

Converting your Class to XML in C# 4.0

XML is a simple and powerful technology . So converting your entire class data to XML and then XML to class back is very helpful when you are doing some project . Here I am explaining how to convert your class data to XML in C# 4.0 using System.Xml.Linq.

C# Sample code

 public class MyPackage
    {
        # region Private Variables Declaration
        private string _packageCode;
        private string _packageDescription;
        private decimal _packageValue;
        private int _mode;         

        # endregion
          public MyPackage()
        {
           
         }
        public MyPackage(int mode)
        {
           
            _mode = mode;
        }
        # region Properties Implementation
        public string PackageCode
        {
            get { return _packageCode; }
            set { _packageCode = value; }
        }
        public string PackageDescription
        {
            get { return _packageDescription; }
            set { _packageDescription = value; }
        }
        public decimal PackageValue
        {
            get { return _packageValue; }
            set { _packageValue = value; }
        }
        public int Mode
        {
            get { return _mode; }
            set { _mode = value; }
        }
   
        #endregion
        public string TransformClassToXML()
        {
            #region  Transform Current Class To XML
         
            XDocument Xmldocument = null;
            try
            {
                Xmldocument = new XDocument(
                          new XElement("Package",
                                             new XElement("PackageCode", PackageCode),
                                               new XElement("PackageDescription", PackageDescription),
                                               new XElement("PackageValue", PackageValue),
                                               new XElement("Mode", Mode)
                                              
                                           )
                           );
            }
            catch (Exception ex)
            {
                string exp = ex.Message;
              
            }
            return Xmldocument.ToString();
            #endregion
        }
                     
    }


// converting back

public void TransformXMLToClass(string pXml)
        {
            // This function converts the xml back to class
            # region Converting the XML to Class
            XElement doc = XElement.Parse(pXml);
 foreach(XElement el in doc.Elements("Package") )
 {
   MyPackage package = new MyPackage();
          
            package.PackageCode = el.Element("PackageCode").Value;
            package.PackageDescription = el.Element("PackageDescription").Value;
            package.PackageValue = Convert.ToDecimal(el.Element("PackageValue").Value);
            package.Mode = Convert.ToInt32(el.Element("Mode").Value);

 }         

            # endregion

        }

The proxy Pattern

Proxy Design pattern

Proxy pattern is one of the commonly used structural design pattern. A proxy, in its most general form, is a class functioning as an interface to something else. Proxy instantiates the real object the first time the client makes a request of the proxy, who  remembers the identity of this real object, and forwards the instigating request to this real object. Then all subsequent requests are simply forwarded directly to the encapsulated real object

There are four common situations in which the Proxy pattern is applicable.
  1. A virtual proxy is a placeholder for “expensive to create” objects. The real object is only created when a client first requests/accesses the object.
  2. A remote proxy provides a local representative for an object that resides in a different address space. This is what the “stub” code in RPC and CORBA provides.
  3. A protective proxy controls access to a sensitive master object. The “surrogate” object checks that the caller has the access permissions required prior to forwarding the request.
  4. A smart proxy interposes additional actions when an object is accessed. Typical uses include:
    • Counting the number of references to the real object so that it can be freed automatically when there are no more references (aka smart pointer),
    • Loading a persistent object into memory when it’s first referenced,
    • Checking that the real object is locked before it is accessed to ensure that no other object can change it.

C# Code Sample

class ProxyDemo
  {
    static void Main()
    {
      // Create proxy and request a service
      Proxy proxy = new Proxy();
      proxy.Request();
      // Wait for user
      Console.Read();
    }
  }
  // "Subject"
  abstract class proxySubject
  {
    public abstract void Request();   
  }
  // "RealSubject"
  class RealSubject : proxySubject
  {
    public override void Request()
    {
      Console.WriteLine("Called RealSubject.Request()");
    }
  }
  // "Proxy"
  class Proxy : proxySubject
  {
    RealSubject realSubject;
    public override void Request()
    {
      // Use 'lazy initialization'
      if (realSubject == null)
      {
        realSubject = new RealSubject();
      }
      realSubject.Request();
    } 
  }

Friday, February 11, 2011

Object Pool

Object Pool Design Pattern

Object pooling can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low.

For example : We have a collection of pairs of shoes.. we took one from the shoe rack , after usage we will put it in the shoe rack. Again needed one, we may take another shoe from the same rack .. so that we can reuse the shoes from the currently availables free shoes..

Did you heard about Database Connection pooling ?  That technique is implemented using object pool pattern.

So the basic idea is  Instead of creating new new instances we will create a finite no of instances. Then pick one instance from the pool when needed. If there is no free instance in the pool then the client need to wait for getting one.

For creating Object Pool the following criterias should be there

  1. Create ObjectPool class with private array of Objects inside
  2. Create acquare and release methods in ObjectPool class
  3. Make sure that your ObjectPool is Singleton

C# Code sample


 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Threading;
namespace ObjectPoolmpl
{
    public sealed class MyPoolManager
    {
        private Queue poolQ = new Queue();
        private Hashtable tblPool = new Hashtable();
        private static readonly object objLock = new object();
        private const int PoolSize = 20;
        private int count = 0;
        private static MyPoolManager poolManager = null;
        /// <summary>
        /// Private constructor to prevent instantiation
        /// </summary>
        private MyPoolManager()
        {
        }
        static MyPoolManager()
        {
            poolManager = new MyPoolManager();
        }
        public static MyPoolManager Instance
        {
            get
            {
                if (poolManager != null)
                {
                    return poolManager;
                }
                return null;
            }
        }
        public void CreatePoolObjects(object obj)
        {
            object _obj = obj;
            count = 0;
            poolQ.Clear();
            tblPool.Clear();
            for (int objCounter = 0; objCounter < PoolSize; objCounter++)
            {
                _obj = new object();
                lock (objLock)
                {
                    tblPool.Add(_obj.GetHashCode(), _obj);
                    poolQ.Enqueue(_obj);
                    count++;
                }
            }
        }
        public bool AddObjectToPool(object obj)
        {
            if (count == PoolSize)
                return false;
            lock (objLock)
            {
                tblPool.Add(obj.GetHashCode(), obj);
                poolQ.Enqueue(obj);
                count++;
            }
            return true;
        }
        public object ReleaseObjectFromPool()
        {
            if (count == 0)
                return null;
            lock (objLock)
            {
                if (poolQ.Count > 0)
                {
                    object obj = poolQ.Dequeue();
                    tblPool.Remove(obj.GetHashCode());
                    count--;
                    return obj;
                }
                return null;
            }
           // return null;
        }
        public object ReleaseObjectFromPool(object obj)
        {
            if (count == 0)
                return null;
            lock (objLock)
            {
                tblPool.Remove(obj.GetHashCode());
                count--;
                PutInPoolAgain();
                return obj;
            }
        }
        private void PutInPoolAgain()
        {
            if (poolQ.Count > 0)
                poolQ.Clear();
            foreach (int key in tblPool.Keys)
            {
                poolQ.Enqueue(tblPool[key]);
            }
        }
        public int CurrentObjectsInPool
        {
            get
            {
                return count;
            }
        }
        public int MaxObjectsInPool
        {
            get
            {
                return PoolSize;
            }
        }
       
    }
    class Program
    {
        static void Main(string[] args)
        {
            //object obj1 = new object();
            //object obj2 = new object();
            MyPoolManager poolManager = MyPoolManager.Instance;
            //poolManager.AddObjectToPool(obj1);
            //poolManager.AddObjectToPool(obj2);
            //Console.WriteLine(poolManager.CurrentObjectsInPool.ToString());
            //poolManager.ReleaseObjectFromPool(obj1);
            //Console.WriteLine(poolManager.CurrentObjectsInPool.ToString());
            Console.WriteLine("Creating object Pool of size {0}" ,poolManager.MaxObjectsInPool);
            poolManager.CreatePoolObjects(new object());
            //for (int i = 0; i < poolManager.MaxObjectsInPool; i++)
            //{
            //    object obj2 = new object();
            //    poolManager.AddObjectToPool(obj2);
            //}
            object obj = null;
            for (; ; )
            {
                obj = poolManager.ReleaseObjectFromPool();
                if (obj != null)
                {
                    Thread.Sleep(1000);
                    Console.WriteLine("An Object Released :"+obj.GetHashCode().ToString());
                    Console.WriteLine("Current Objects in Pool :" + poolManager.CurrentObjectsInPool);
                    poolManager.AddObjectToPool(obj);
                    Console.WriteLine("An Object Addedd :" + obj.GetHashCode().ToString());
                }
                else
                {
                    Console.WriteLine("No more objects in the pool");
                    break;
                }
            }
            Console.ReadLine();
        }
    }
}


Singleton

Singleton pattern

This pattern is a commonly used design pattern on most of the object oriented programming.
The basic idea is only one instance of a class ever exists if it is designed as singleton..
To make a class singleton the following criteria must be there.

  1. Define a private static attribute in the “single instance” class.
  2. Define a public static accessor function in the class.
  3. Do “lazy initialization” (creation on first use) in the accessor function.
  4. Define all constructors to be protected or private.
  5. Clients may only use the accessor function to manipulate the Singleton.
C# Code

class Singleton
  {

    private static Singleton instance;

    // Note: Constructor is 'protected' or private
    protected Singleton()
    {
    }

    public static Singleton GetInstance()
    {
      // Use 'Lazy initialization'
      if (instance == null)
      {
        instance = new Singleton();
      }

      return instance;
    }
  }

static void Main()
    {
      // Constructor is protected -- cannot use new
      Singleton s1 = Singleton.GetInstance();
      Singleton s2 = Singleton.GetInstance();

      if (s1 == s2)
      {
        Console.WriteLine("Objects are the same instance");
      }

    }

Design Patterns

Why Design Patterns ?

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn't a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

In most of the object oriented languages some common problems are solved with design patterns viz.. singleton, proxy, object pool etc....

It can roughly classified into the following

1. Creational
2. Structural
3. Behavioural

1. Creational

              This design patterns is all about class instantiation. This pattern can be further divided into class-creation patterns and object-creational patterns.

Major types of creational patterns are
  • Abstract Factory - Creates an instance of several families of classes
  • Builder - Separates object construction from its representation
  • Factory Method - Creates an instance of several derived classes
  • Object Pool - Avoid expensive acquisition and release of resources by recycling objects that are no longer in use
  • Prototype - A fully initialized instance to be copied or cloned
  • Singleton - A class of which only a single instance can exist 
2. Structural

This design patterns is all about Class and Object composition. Structural class-creation patterns use inheritance to compose interfaces

Major types are
  • Adapter - Match interfaces of different classes
  • Bridge - Separates an object’s interface from its implementation
  • Composite - A tree structure of simple and composite objects
  • Decorator - Add responsibilities to objects dynamically
  • Facade - A single class that represents an entire subsystem
  • Flyweight - A fine-grained instance used for efficient sharing
  • Private Class Data - Restricts accessor/mutator access
  • Proxy - An object representing another object
 3. Behavioural

This design patterns is all about Class's objects communication. Behavioral patterns are those patterns that are most specifically concerned with communication between objects.
  • Chain of responsibility - A way of passing a request between a chain of objects
  • Command - Encapsulate a command request as an object
  • Interpreter - A way to include language elements in a program
  • Iterator - Sequentially access the elements of a collection
  • Mediator - Defines simplified communication between classes
  • Memento - Capture and restore an object's internal state
  • Null Object - Designed to act as a default value of an object
  • Observer - A way of notifying change to a number of classes
  • State - Alter an object's behavior when its state changes
  • Strategy - Encapsulates an algorithm inside a class
  • Template method - Defer the exact steps of an algorithm to a subclass
  • Visitor - Defines a new operation to a class without change
I will discuss how to use some of the design patterns in object oriented programs with the help of C# codes in the next posts !!