Tuesday, October 5, 2010

DIFFERENCE BETWEEN FINDALL() AND WHERE()

First of all how both these works :
Suppose we have a class Person :

public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

Now, create an object of person class :
Person person = new Person();

Take a List of person class :
List lstPerson = new List();

Now, assign values to this class and add it to list :
person.FirstName = "FirstName1";
person.LastName = "LastName1";
lstPerson.Add(person);

person.FirstName = "FirstName2";
person.LastName = "LastName2";
lstPerson.Add(person);

Now, I want to find all the records where FirstName = "FirstName1".
To do this, I have two options : FindAll() and Where()

FindAll() :
List result = lstPerson.FindAll(delegate(Person per)
{
return per.FirstName == "Firstname1";
});

Where() :
List result = lstPerson.Where((Person per) => per.FirstName == "FirstName1").ToList();


Both will return the same result. So, the question is which one should be used in which situation?
There are some difference between both, now you have to decide which one suits your requirement:

1. FindAll() is a function on the List type, it's not a LINQ extension method like Where. The LINQ extension methods work on any type that implements IEnumerable, whereas FindAll can only be used on List instances (or instances of classes that inherit from it, of course). If our collection is IEnumerable type, then we can't use FindAll() as it's a function of List.

2. The FindAll method of the List class actually constructs a new list object, and adds results to it. The Where extension method for IEnumerable will simply iterate over an existing list and yield an enumeration of the matching results without creating or adding anything (other than the enumerator itself.)

3. Where is much faster than FindAll. No matter how big the list is, Where takes exactly the same amount of time because Where() just creates a query, It doesn't actually do anything, unlike FindAll which does create a list.

Read More..

Monday, October 4, 2010

PRIME NUMBER

public bool IsPrime(int x)
{
if (x == 1)
{
return true;
}
else
{
for (int i = x - 1; i > 1; i--)
{
if (x % i == 0)
{
return false;
}
}
return true;
}
}
Read More..

RECURSIVE PROGRAM TO FIND THE FACTORIAL

public int Factorial(int x)
{
if (x == 1)
{
return x;
}
else
{
return x * Factorial(x - 1);
}
}
Read More..

Saturday, October 2, 2010

CUSTOM CONTROLS IN ASP.NET - GRIDVIEW

In Asp.net, we generally bind GridView with a data source. That data source can be anything like – Data Table, Data View, Class Object, etc. If data source contains some value then it simply binds the grid and displays the records according to grid formatting.
What happens when data source is empty? – GridView will not get displayed.
If suppose, we want to display header and footer of grid in each and every case then what should we do?
One way is to manipulate the data source and add a blank row in it and bind it with grid. It will display the header and footer along with a blank row in grid. This is dirty coding.
Another way is custom controls. Before moving to custom controls first understand the workflow of Grid View.
Steps to create a GridView custom control and use it in aspx page:
1. Take a class and declare a namespace.
2. Inherit your class with GridView (System.Web.UI.WebControls.GridView) class:
using System;
using System.Collections;
using System.Data;
using System.Web.UI.WebControls;

namespace AlwaysShowHeaderFooter {
public class GridViewAlwaysShow : GridView {
}
}
3. Add a delegate above the class:
public delegate IEnumerable MustAddARowHandler(IEnumerable data);

4. Add an event inside the class:
public event MustAddARowHandler MustAddARow;

5. Create a Method to raise this event:
protected IEnumerable OnMustAddARow(IEnumerable data) {
if (MustAddARow == null) {
throw new NullReferenceException("The datasource has no rows. You must handle the \"MustAddARow\" Event.");
}
return MustAddARow(data);
}

6. Now come to main aspx page where you want to display the grid. Register your custom control namespace here:
<%@ Register TagPrefix="Custom" Namespace="AlwaysShowHeaderFooter" %>

7. Add your custom grid on page and call OnMustAddARow function:
OnMustAddARow="grdCustom_MustAddARow"

8. Now define the grdEmail_MustAddARow() in aspx.cs file:
//Flag used to identify if the datasource is empty.
bool _isEmpty = false;

///
/// Handles the MustAddARow event of grdEmail
///

/// The data.
///
protected IEnumerable grdEmail_MustAddARow(IEnumerable data)
{
ListDictionary ldEmails = (ListDictionary)data;
ldEmails.Add("", "");
_isEmpty = true;
return ldEmails;
}
Here we have set a flag _isEmpty = true to check if data source is empty.
I have bind the grid with ListDictionary, you can take any data source.

9. Come back to your custom control class and override the OnDataBound() method to check if data source is empty. As we have added a dummy(blank) row in grdEmail_MustAddARow(), it will display a blank row in grid at runtime which should not come. So we will hide it.
protected override void OnDataBound(EventArgs e)
{

//if in DesignMode, don't do anything special. Just call base and return.
if (DesignMode)
{
base.OnDataBound(e);
return;
}

//hide the dummy row.
if (_isEmpty)
{
Rows[0].Visible = false;
}
base.OnDataBound(e);
}

10. GridView have a method protected internal override void PerformDataBinding(IEnumerable data) which gets called through Databind() method of GridView.

11. Now override the PerformDataBinding method to call OnMustAddARow method if data source is blank. This method gets called from databind() method of GridView.
protected override void PerformDataBinding(IEnumerable data)
{

//If in DesignMode, don't do anything special. Just call base and return.
if (DesignMode)
{
base.PerformDataBinding(data);
return;
}

//Count the data items.(I wish I knew a better way to do this.)
int objectItemCount = 0;
foreach (object o in data)
{
objectItemCount++;
}

//If there is a count, don't do anything special. Just call base and return.
if (objectItemCount > 0)
{
base.PerformDataBinding(data);
return;
}

//Set these values so the GridView knows what's up.
SelectArguments.TotalRowCount++;
_isEmpty = true;

//If it's a DataView, it will work without having to handle the MustAddARow event.
if (data.GetType() == typeof(DataView))
{
//Add a row and use that new view.
DataView dv = (DataView)data;
dv.Table.Rows.InsertAt(dv.Table.NewRow(), 0);
base.PerformDataBinding(dv.Table.DefaultView);
return;
}
else
{
//If you are using some custom object, you need to handle this event.
base.PerformDataBinding(OnMustAddARow(data));
return;
}
}

That’s it!! Your custom control is ready to run...:)
Read More..

WORKFLOW OF GRIDVIEW

Have you ever thought how grid view handles all the events like RowDataBound, RowCommand, RowDeleting, RowUpdating, etc...? If you look in System.Web.UI.WebControls.GridView class, you will find lots of properties, events and methods.

Let’s take RowDataBound as an example to understand the GridView workflow.
1. We have an event RowDataBound which gets fired OnRowDataBound method :
// Summary: Occurs when a data row is bound to data in a
System.Web.UI.WebControls.GridView control.
public event GridViewRowEventHandler RowDataBound;

2. We have a delegate to handle RowDataBound event :
using System;
namespace System.Web.UI.WebControls
{
// Summary: Represents the method that handles the
// System.Web.UI.WebControls.GridView.RowCreated and S
// System.Web.UI.WebControls.GridView.RowDataBound events of a
// System.Web.UI.WebControls.GridView control.
// Parameters:
// sender: The source of the event.
//e: A System.Web.UI.WebControls.GridViewRowEventArgs object that contains the event data.
public delegate void GridViewRowEventHandler(object sender, GridViewRowEventArgs e);
}

3. We have a method OnRowDataBound() which raises the RowDataBound event :
// Summary: Raises the System.Web.UI.WebControls.GridView.RowDataBound event.
// Parameters:
// e: A System.Web.UI.WebControls.GridViewRowEventArgs that contains event data.
protected virtual void OnRowDataBound(GridViewRowEventArgs e);

4. Create grdTest_RowDataBound function in aspx.cs and write the code which you want to execute for each row when data binding takes and call it in OnRowDataBound()
Here I am generating the Serial No., which will be displayed in grid.

private int intSerialNo = 1;

/// Handles the RowDataBound event of the grdEmail control.
/// The source of the event.
/// The instance containing the event data.
protected void grdEmail_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow) || (e.Row.RowType == DataControlRowType.Footer))
{
Label serialNumber = (Label)e.Row.FindControl("lblSno");
serialNumber.Text = intSerialNo.ToString() + ".";
intSerialNo = intSerialNo + 1;
}
}

This is how GridView works!!
Read More..

Wednesday, September 29, 2010

Basics Of WCF

Main components of WCF are :
1. EndPonits
2. Binding
3. Contract

A service is a construct that exposes one or more endpoints, each of which exposes one or more service operations.
The endpoint of a service specifies an address where the service can be found, a binding that contains the information that a client must communicate with the service, and a contract that defines the functionality provided by the service to its clients.

Windows Communication Foundation (WCF) enables applications to communicate whether they are on the same computer, across the Internet, or on different application platforms.

The Basic Tasks

The basic tasks to perform are, in order:

1. Define the service contract. A service contract specifies the signature of a service, the data it exchanges, and other contractually required data.

2. Implement the contract. To implement a service contract, create the class that implements the contract and specify custom behaviors that the runtime should have.

3. Configure the service by specifying endpoint information and other behavior information.

4. Host the service in an application.

5. Build a client application.
Read More..

Friday, June 4, 2010

FIND() AND FINDALL() FUNCTIONS IN LINQ

We have a table Customer which contains details of a customer like name, address, phone, etc.

we have a list of customers -
List lstCust = new List();

we want to find a particular record from this list based on some criteria.
say where name = 'abc';

In C# :

List lstCustResult = lstCust .FindAll(
delegate(Customers cust)
{
return cust.name == "abc";
});

This will return all the records having name ="abc".

suppose we want to fetch a particular value based on some criteria, in that case we will use Find instead of FindAll.

string name = lstCust .Find(
delegate(Customers cust)
{
return cust.id== 1;
}).name;

Also, if suppose we have a list of strings and want to find a particular record in that list.
For That we need to do something like this :

List lstNumbers = new List();
lstNumbers.Add("One");
lstNumbers.Add("Two");
lstNumbers.Add("Three");
lstNumbers.Add("Four");
lstNumbers.Add("One");
List result= lst.FindAll(delegate(string name)
{
name = "One";
return lstNumbers.Equals(name);
});
Read More..