Wednesday, August 20, 2008

Design Patterns : An introduction

Design Patterns

Design Patterns are an essential tool for any object orientated programmer who wants to take his/her skills to the next level. Understanding the specifics of Design Pattern practices and methodologies will help developers uncover reoccurring patterns in software development and give them the tools to apply the correct solution.

Types of Design Patterns

  • Informal Design Patterns - such as the use of standard code constructs, best practice, well structured code, common sense, the accepted approach, and evolution over time.
  • Formal Design Patterns - documented with sections such as "Context", "Problem", "Solution", and a UML diagram.

Formal patterns usually have specific aims and solve specific issues, whereas informal patterns tend to provide guidance that is more general. Formal patterns usually have specific aims and solve specific issues, whereas informal patterns tend to provide guidance that is more general.

For example, some patterns provide presentation logic for displaying specific views that make up the user interface. Others control the way that the application behaves as the user interacts with it. There are also groups of patterns that specify techniques for persisting data, define best practices for data access, and indicate optimum approaches for creating instances of objects that the application uses.

The following list shows some of the most common design patterns within these groups:

  • Presentation Logic
    1. Model-View-Controller (MVC)
    2. Model-View-Presenter (MVP)
    3. Use Case Controller
  • Host or Behavioral
    1. Command
    2. Publish-Subscribe / Observer
    3. Plug-in / Module / Intercepting Filter
  • Structural
    1. Service Agent / Proxy / Broker
    2. Provider / Adapter
  • Creational
    1. Factory / Builder / Injection
  • Persistence
    1. Repository

We will see how to use these pattern in the next post.

Happy programming!!!

Thursday, July 31, 2008

Short cut RUN prompt or Commends prompt keys

I know there are a lot of people who love using the RUN prompt or the COMMAND prompt rather than using the MMC control. Here are some of the short cut command for your regular use.

  • Add/Remove Programs : appwiz.cpl
  • Automatic Updates : wuaucpl.cpl
  • Date and Time Properties : timedate.cpl
  • Display Properties : control desktop
  • Display Properties : desk.cpl
  • Findfast : findfast.cpl
  • Shuts Down Windows : shutdown
  • Task Manager : taskmgr
  • Wordpad : write

Use the shortcuts!!!

Thursday, July 24, 2008

Convert string data into DataTime in Sql Server

In SQL Server, no direct funtion to convert interger string into time format. We need to do it by our own logic. See the below sample which convert integer string to datetime.



DECLARE

@DateTimeValue varchar(30),

@DateValue char(8),

@TimeValue char(6)



SELECT

@DateValue = '20080723',

@TimeValue = '211957'



SELECT @DateTimeValue =

convert(varchar, convert(datetime, @DateValue), 111)

+ ' ' + substring(@TimeValue, 1, 2)

+ ':' + substring(@TimeValue, 3, 2)

+ ':' + substring(@TimeValue, 5, 2)



SELECT

DateInput = @DateValue,

TimeInput = @TimeValue,

DateTimeOutput = @DateTimeValue

Use this tips!!!

Monday, July 21, 2008

Visual Studio 2005 / 2008 short cut keys

Visual Studio 2005/2008 short cut keys
Using keyboard shortcuts is the best way to get things done faster in Visual Studio. Below are my favorite Visual Studio keyboard shortcuts.
  • F12 : Go to definition of a variable, object, or function.
  • SHIFT+F12 : Find all references of a function or variable.
  • CTRL+ALT+L : View Solution Explorer. I use Auto Hide for all of my tool windows to maximize screen real estate. Whenever I need to open the Solution Explorer, it’s just a shortcut away.
  • CTRL+M, O: Collapse to Definitions. This is usually the first thing I do when opening up a new class.
  • CTRL+-: Go back to the previous location in the navigation history.
  • ALT+B, B: Build Solution.
  • ALT+B, U : Build selected Project
  • ALT+B, R : Rebuild Solution
  • CTRL+ALT+Down Arrow : Show dropdown of currently open files. Type the first few letters of the file you want to select.
  • CTRL+K, CTRL+D : Format code.
  • CTRL+L : Delete entire line.

Use the technology!!!

Saturday, July 19, 2008

Delegates in .NET

What is a Delegate?
We can say delegates are a .NET object which points to a method that matches its specific signature or delegates are function pointers that point to function of matching signatures.

Function pointers which are extensively used in c/c++ to points to a function holds only the memory address of the function, it doesn’t carry further information about the function parameters, return type etc.

In other words delegates are function pointers that point to function of matching signatures. Function pointers which are extensively used in c/c++ to points to a function holds only the memory address of the function, it doesn’t carry further information about the function parameters, return type etc.

In .NET framework has introduced a type-safe mechanism called delegates, with automatic verification of the signature by the compiler. So the delegates are type-safe, object oriented, secure .NET objects which can be used to invoke methods of matching signature.

While using delegates it is very necessary to make sure that the functions which the delegates points has the same number of argument type and same return type.

For example
if we have a method that takes a single string as a parameter and another method that takes two string parameters, then we need to have two separate delegate type for each method.

Types of Delegate
Delegates are of two types. They are
  • Single cast delegate
  • Multicast Delegates

Single cast delegate

A delegate is called single cast delegate if it invokes a single method. Its derive from the System.Delegate class. See the below sample :

using System;

namespace Delegates
{
public delegate int DelegateToMethod(int x, int y);

public class Math
{
public static int Add(int first, int second)
{
return first + second;
}

public static int Multiply(int first, int second)
{
return first * second;
}
}

public class DelegateApp
{
public static void Main()
{
DelegateToMethod aDelegate = new DelegateToMethod(Math.Add);
DelegateToMethod mDelegate = new DelegateToMethod(Math.Multiply);
Console.WriteLine("Calling the method Math.Add() through the aDelegate object");
Console.WriteLine(aDelegate(5,5));
Console.WriteLine("Calling the method Math.Multiply() through the mDelegate object");
Console.WriteLine(mDelegate(5,5));
Console.ReadLine();
}

}
}

The output for above sample is

Calling the method Math.Add() through the aDelegate object
10
Calling the method Math.Multiply() through the mDelegate object
25

Multicast delegate

A multicast delegate is an object that maintains a linked list of delegates. Invoking the delegate invokes each delegate in the same order that it has been added to the linked list.

For an example

we have created an object (a delegate) called multiDelegate of type Math.DelegateToMethod and assigned a null value to this object. The next, assigns a new delegate object that encapsulates the method math.Add(). Using the operator += we assign more delegate objects (thus creating a multicast delegate) to the delegate multiDelegate.

It invoking the delegate invokes all the delegates maintained in its linked list, which in turn calls the encapsulated methods.

See the below sample :


using System;

namespace Delegates
{
public class Math
{
// note that the delegate now is a nested type of the Math class
public delegate void DelegateToMethod(int x, int y);

public void Add(int first, int second)
{
Console.WriteLine("The method Add() returns {0}", first + second);
}

public void Multiply(int first, int second)
{
Console.WriteLine("The method Multiply() returns {0}", first * second);
}

public void Divide(int first, int second)
{
Console.WriteLine("The method Divide() returns {0}", first / second);
}
}

public class DelegateApp
{
public static void Main()
{
Math math = new Math();
Math.DelegateToMethod multiDelegate = null;
multiDelegate = new Math.DelegateToMethod(math.Add);
multiDelegate += new Math.DelegateToMethod(math.Multiply);
multiDelegate += new Math.DelegateToMethod(math.Divide);
multiDelegate(5,5);
Console.ReadLine();
}
}
}


The output of the above sample is

The method Add() returns 10
The method Multiply() returns 25
The method Divide() returns 1

The statement multiDelegate(5,5); is similar to our previous example in which we have created three delegate objects and then calling each of them separately.

You can remove a delegate object from the linked list using the operator -=.

Where are Delegates used?
The most common example of using delegates is in events. You define a method that contains code for performing various tasks when an event (such as a mouse click) takes place.
This method needs to be invoked by the runtime when the event occurs. Hence this method, that you defined, is passed as a parameter to a delegate.

Happy coding!!!

Monday, July 14, 2008

Convert DataTable to DataView in C# in VS 2008

The following sample will demonstrate the convertion from DataTable to DataView in C# in VS 2008.

In VS 2008, DataView having one method which accept datatable as input parameter and it return the converted result as dataview by using DataView().

// Create dynamic data table.
var dataTable = new DataTable();


// Create columns
dataTable.Columns.Add("FirstName");
dataTable.Columns.Add("LastName");
dataTable.Columns.Add("Salary");


var dataRow = dataTable.NewRow();
dataRow[0] = "Kannan";
dataRow[1] = "Arjun";
dataRow[2] = 1000;



// Add new Datarow to data table.
dataTable.Rows.Add(dataRow);



dataRow = dataTable.NewRow();
dataRow[0] = "Seema";
dataRow[1] = "Sekar";
dataRow[2] = 4000;



// Add new Datarow to data table.
dataTable.Rows.Add(dataRow);



// Convert data table to dataview.
var dataView = new DataView(dataTable);
// Now ready to use this dataview.



Happy coding!!!

ValidateRequest in Page directive in asp.net

ASP.NET 2.0 validates form input values for potentially dangerous entries such as the '<' and '>' characters. When I enter the value '<' and '>' in textbox in .Net web form, it returns an error like 'Sys.WebForms.PageRequestManagerServerErrorException: An unkown erroroccured while processing the request on the server. The status code returned from the server was: 500'. So I search on google indicates the below solution for this :
  • Add ValidateRequest = "false" in the Page directive.
    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="sample.aspx.cs"
    Inherits="KannanDemo.sample" validateRequest="false"%>
    After added it and run the application. This time I got the error like The 'ValidateRequest' attribute is not supported by the 'Page directive.'

  • Then I found another way to solve this issue by adding <pages ValidateRequest="false"/> in System.Web of the Web.Config file. I got the result.

Note:

The main disadvantage of setting the ValidateRequest to false on a page is the openning of an opportunity to hack your page, because the ValidateRequest's job is to ensure that the most common injection attacks are not possible for your page, and so if you disable it then you should start making all the necessary changes to avoid SQL Injection, Script Injection, and so on.

Happy coding!!!

Saturday, July 12, 2008

Convert IEnumerable to DataTable in C#

Convert IEnumerable to DataTable in C#

In LINQ, there is no option to casting IEnumerable to DataTable. We need to convert manually. For this, I have created one healper class which convert any type of IEnumerable to DataTable. Use the code below for this kind of requirements.

using System;

using System.Data;

using System.Configuration;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Reflection;



namespace KannanDotNetReference.HelperClasses

{

static public class ConvertDataTable

{

public static DataTable ConvertToDataTable<T>(this System.Collections.Generic.IEnumerable<T> varList, CreateRowDelegate<T> fn)

{

DataTable dataTable = new DataTable();



// Variable for column names.

PropertyInfo[] tableColumns = null;



// To check whether more than one elements there in varList.

foreach (T rec in varList)

{

// Use reflection to get column names, to create table.

if (tableColumns == null)

{

tableColumns = ((Type)rec.GetType()).GetProperties();

foreach (PropertyInfo pi in tableColumns)

{

Type columnType = pi.PropertyType;

if ((columnType.IsGenericType) && (columnType.GetGenericTypeDefinition() == typeof(Nullable<>)))

{

columnType = columnType.GetGenericArguments()[0];

}

dataTable.Columns.Add(new DataColumn(pi.Name, columnType));

}

}



// Copying the IEnumerable value to DataRow and then added into DataTable.

DataRow dataRow = dataTable.NewRow();

foreach (PropertyInfo pi in tableColumns)

{

dataRow[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);

}

dataTable.Rows.Add(dataRow);

}

return (dataTable);

}



public delegate object[] CreateRowDelegate<T>(T t);

}

}





See the below sample which fetch all the country with their customers count from Northwind database by using LINQ.
I have created Sample.aspx with one gridview control for displaying the result. See the code below: Sample.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Sample.aspx.cs" Inherits="KannanDotNetReference.Sample" %>

<!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>Kannan Samples : IEnumerabl to DataTable convertor</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>

See the sample.aspx.cs code below which fetch the data from Northwind by using LINQ technique. In the code GetCountry() method is using ConvertToDataTable() helper method for converting IEnumerable result to datable. See the complete codeing of Sample.aspx.cs :


using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using KannanDotNetReference.HelperClasses;



namespace KannanDotNetReference

{

public partial class Sample : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

GridView1.DataSource = GetCountry();

GridView1.DataBind();

}



private DataTable GetCountry()

{

var db = new NorthwindDataContext();

var table = db.KannanGetCountry();



DataTable dt = table.ConvertToDataTable(record => new object[] { table });



return dt;

}

}

}




Once we finished our coding part, next run this application. See the result below.


Note:

I have created one stored procedure for fetching the country with number of customers belongs to by using the below code:


CREATE PROCEDURE [dbo].[KannanGetCountry]
AS
SELECT
Country as 'CountryName',
COUNT(CustomerId) as 'CountryCount'
FROM Customers
GROUP BY Country

Happy Coding!!!

Adding Northwind Pub Database to SQL Server 2005

SQL Server 2005 doesn't include the Pubs and Northwind databases.

  • You can click here to download (.msi) the latest version of Pub and Northwind sample databases .
  • Install .msi file. It will create binary files (.mdf , .ldf) and SQL scripts (.sql) files.

Installing sample databases from the Management Studio GUI:

  • This method will use binary files.
  • Copy .mdf and .ldf files back to SQL DATA folder like c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\. This path varies somewhat depending how many instances of SQL Server you have on your machine.
  • Open SQL Server 2005.
  • Right-click the root database
  • Click "Attach"
  • Click the "Add" button and choose the *.mdf file from the \Data folder
  • Click OK

Installing sample databases from the command line:

  • This method will use SQL scripts files.
  • Click the "New Query" toolbar button
  • Cut and paste the contents of the instnwnd.sql or instpubs.sql scripts in the query window
  • Hit F5 button to run.

Use the technology!!!