Tuesday, December 30, 2008

Thursday, December 25, 2008

C# array in descending or reverse order

How do you sort a C# array in descending or reverse order? A simple way is to sort the array in ascending order, then reverse it:
int[] intArray = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>( intArray );
Array.Reverse( intArray );
Of course, this is not efficient for large arrays.

A better approach is to create a custom Comparer. Following is a nice generics class that will sort an array in descending order. Note that the object type must be comparable (inherit from IComparable) as any useful class should.

Here’s a simple web application to test it:

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="SortSample.aspx.cs" Inherits="SampleApplication.SortSample" %>

<!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 runat="server">
<title>Sort Ascending /Descending Order by Generic</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList3" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;

namespace SampleApplication.
{
public partial class SortSample: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int[] intArray = new int[] { 3, 1, 4, 5, 2 };
char[] charArray = new char[] { 'r', '1', 'f', 'c', 'x' };
string[] stringArray = new string[] { "array item 1", "array item 2", "array item 3", "array item 4", "array item 5" };

ArraySorter<int>.SortDescending(intArray);
ArraySorter<char>.SortDescending(charArray);
ArraySorter<string>.SortDescending(stringArray);

BindDropDownList(DropDownList1, intArray);
BindDropDownList(DropDownList2, charArray);
BindDropDownList(DropDownList3, stringArray);
}

private static void BindDropDownList(BaseDataBoundControl ddl, Array arr)
{
if(ddl !=null && arr !=null && arr.Length>0)
{
ddl.DataSource = arr;
ddl.DataBind();
}
}
static public class ArraySorter<T> where T : IComparable
{
static public void SortDescending(T[] array)
{
Array.Sort<T>(array, s_Comparer);
}

static private readonly ReverseComparer s_Comparer = new ReverseComparer();

private class ReverseComparer : IComparer<T>
{
public int Compare(T object1, T object2)
{
return -((IComparable)object1).CompareTo(object2);
}
}
}

}
}

I hope it will help you in someway.

Happy Coding!!!

Saturday, December 20, 2008

Design Pattern - Abstract Factory Pattern

Today I'm going to write about one of the most popular patterns in the design patterns world - the abstract factory.

You can read my previous posts about design patterns here:
An abstract factory provides an interface for creating families of related objects without specifying their concrete classes.

The abstract factory dictates which products the concrete factories will produce. Each concrete factory can build different products of different types.

The only way to get the products by the client is through the factory which isolate the products definition and creation. Object creation has been abstracted and there is no need for hard-coded class names in the client code.

For an example, take a real-world demonstrates the Factory method offering flexibility in creating different documents. The derived Document classes Report and Resume instantiate extended versions of the Document class. Here, the Factory Method is called in the constructor of the Document base class.

using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatternConsole
{
/// <summary>
/// The 'Product' abstract class
/// </summary>
abstract class Page
{
}


/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class SkillsPage : Page
{
}

/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class EducationPage : Page
{
}


/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class ExperiencePage : Page
{
}


/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class IntroductionPage : Page
{
}


/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class ResultsPage : Page
{
}


/// <summary>
/// The 'Creator' abstract class
/// </summary>
abstract class Document
{
private List<Page> _pages = new List<Page>();

// Constructor calls abstract Factory method
public Document()
{
this.CreatePages();
}

public List<Page> Pages
{
get { return _pages; }
}

// Factory Method
public abstract void CreatePages();
}

/// <summary>
/// A 'ConcreteCreator' class
/// </summary>
class Resume : Document
{
// Factory Method implementation
public override void CreatePages()
{
Pages.Add(new SkillsPage());
Pages.Add(new EducationPage());
Pages.Add(new ExperiencePage());
}
}

/// <summary>
/// A 'ConcreteCreator' class
/// </summary>
class Report : Document
{
// Factory Method implementation
public override void CreatePages()
{
Pages.Add(new IntroductionPage());
Pages.Add(new ResultsPage());
}
}

class AbstractFactory
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Note: constructors call Factory Method
Document[] documents = new Document[2];
documents[0] = new Resume();
documents[1] = new Report();

// Display document pages
foreach (Document document in documents)
{
Console.WriteLine("\n" + document.GetType().Name + "--");
foreach (Page page in document.Pages)
{
Console.WriteLine(" " + page.GetType().Name);
}
}

// Wait for user
Console.ReadKey();
}
}
}

Output :

The benefits of using the pattern are the isolation of concrete classes, it makes it easy to exchange product families and it makes the products consistent.

The drawback of the pattern is that the support of new products is difficult.

Happy Coding!!!

Design Pattern - Singleton

Before we move to Singleton pattern, first we should know what is instantiation and how it will play main role in Singleton.

Please refer my previous post for basic information about Design Pattern if you needs.

Instantiation means creating an object using a class as a template. There are two approaches to instantiation:
  • Lazy instantiation
  • Eager instantiation

Lazy instantiation : a class is not instantiated until a request is made via the Singleton.Instance() method.
if (singleton == null)
{
singleton = new Singleton(); // lazy instantiation
Console.WriteLine ("Singleton instantiated");
}

This code is quite simple. If singleton is null, then the Singleton object has not yet been instantiated. And, if not, it is instantiated with the new operator. This is only done once; because, the next time the code is called, singleton will not be null.

Eager instantiation is still lazy, it will run the initializers whenever the class is instantiated or another static member is accessed.

public sealed class Singleton
{

//private static Singleton singleton;
private static readonly Singleton singleton = new Singleton(); // eager instantiation

static Singleton()
{
Console.WriteLine ("Singleton instantiated");
}

private Singleton() {} // private constructor

public static Singleton GetInstance()
{
//if (singleton == null)
//{
// singleton = new Singleton();
// Console.WriteLine ("Singleton instantiated");
//}
return singleton;
}
}

The only differences between this eager code and the previous lazy example is that Singleton is instantiated in the static initializer instead of in the Singleton.Instance() method; and, there is a static constructor. However, this implementation is thread safe.


Now we will move to singleton.

Singleton is a design pattern used to restrict the instantiation of a class to one object. It is one of the most used and well know design patterns in programming.

For an example, you may need a class that will contain the user information across the system, there is no need to create several instances of this class. The explanation of this will be given in this little sample below:

Step 1. DesignPatternTest.aspx

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="DesignPatternTest.aspx.cs"
Inherits="DesignPatternTest.SingletonSample" %>


<!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 runat="server">
<title>Singleton</title>
</head>
<body>
<form id="form1" runat="server">
<div>
See the above Singleton output
</div>
</form>
</body>
</html>

Step 2. DesignPatternTest.aspx.cs
using System;

namespace DesignPatternTest
{
public partial class SingletonSample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Constructor is protected
// Prevented from using 'new' keyword
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();

if (s1 == s2)
Response.Write("s1 & s2 are the same instance");

s1.x = 100;
Response.Write("<br>s1.x=" + s1.x);

s2.x = 200;
Response.Write("<br>s2.x=" + s2.x);

// Updates to x are updating same instance
Response.Write("<br>s1.x=" + s1.x);
Response.Write("<br>s2.x=" + s2.x);

}
}

public class Singleton
{
// Variable
public int x = 0;

// Fields
private static Singleton instance;

// Empty Constructor
protected Singleton() { }

// Methods
public static Singleton Instance()
{
// Uses "Lazy initialization"
if (instance == null)
instance = new Singleton();

return instance;
}
}
}

See the output

Singleton can be used in many situations, for samples.
  • Caches
  • Loggers
  • Thread pools
  • Dialog boxes
  • Device drivers
Last but not least, singleton is a class which permits itself to be instantiated only once.

  • Has a private or protected constructor with no parameters.
  • Has a single, global means of access via a static method.
  • Cannot be subclassed nor instantiated with the new operator.
  • Uses lazy instantiation

Happy Coding!!!

Saturday, December 6, 2008

Highlight Datagrid or GridView row on mouse over in asp.net

To highlight the row and when mouse moves out, the style sheet is switched back to normal.

Use the following two steps to solve this case. This will applicable for both Gridview and Datagrid controls.

Step 1 : Create styles for normal and highlight view of the row.

<style type="text/css">
.normalrow
{
background-color:white;
}
.hightlighrow
{
background-color:#cccccc;
}
</style>
Step 2 : Now add handler for RowCreated event for the grid and add the attributes for onmouseover and onmouseout javascript events.

Following code snippet shows how this has been done.

protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.className='hightlighrow'");
e.Row.Attributes.Add("onmouseout", "this.className='normalrow'");
}
}
Use the technology!!!

Friday, December 5, 2008

Allow only numbers / digits in TextBox.

Allow only numbers/digits in TextBox. How to use Javascript to allow only numbers to be entered in a textbox. This is useful for phone numbers, ZipCode, and etc., Use the following two step to solve this situation. This solution works in both IE and Netscape/Mozilla.

Step 1: Add the following javascript into you page.

function AllowNumbersOnly(evt)
{
// Allow numbers only in the Textbox.
var e = event evt; // for trans-browser compatibility
var charCode = e.which e.keyCode;
if (charCode > 31 && (charCode < 48 charCode > 57))
return false;
return true;
}

Step 2: Add the keypress event into your textbox.

<INPUT id="txtChar" onkeypress="return AllowNumbersOnly(event)" type="text" name="txtChar">

In asp.net add your textbox control and use this code behind.

TextBox.Attributes.Add("onkeypress", "javascript:return AllowNumbersOnly(event);");

Use technology!!!