Monday, February 22, 2010

Anonymous Methods Vs Named Methods

create a console application in c#.net and copy this

namespace ConsoleApplication1
{
class Program
{
//Declaring a delegate
delegate void Display(String text);

static void Main(string[] args)
{
//Anonymous method
Display d = delegate(String s)
{
Console.WriteLine(s + "Anonymous method");
};

//Calling anonymous method
d("I am calling ");

d = new Display(Program.Foo);

//Calling named method
d("I am calling ");

Console.ReadLine();
}

/// Named method
public static void Foo(String text)
{
Console.WriteLine(text + "Named Method.");
}
}
}

You cannot use a "ref" or "out" variable inside an anonymous method.
If you are using a variable that is declared outside the anonymous method is called "outer" or "captured" variables of the anonymous method.

eg:-
string outside = "I am captured";
//Anonymous method
Display d = delegate(String s)
{
Console.WriteLine(s + "Anonymous method " + outside);
};

Sunday, February 21, 2010

Conditional Loop In XSLT

XML
--------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="test.xslt" ?>
<Root>
<Title>Looping function example</Title>
<Limit>10</Limit>
</Root>


XSLT
----------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="/">

<html>
<head>
<title> <xsl:value-of select="Root/Title" /> </title>
</head>
<body>
<!--CALLING FUNCTION -->

<h3><xsl:value-of select="Root/Title" /></h3>
<xsl:call-template name="LoopingFunc">
<xsl:with-param name="limit" select="Root/Limit" />
</xsl:call-template>
</body>
</html>
</xsl:template>
<!--LOOPING FUNCTION -->

<xsl:template name="LoopingFunc">
<xsl:param name="limit"/>
<xsl:if test="$limit > 0">
<h5>
<xsl:value-of select="$limit"/>
</h5>
<xsl:call-template name="LoopingFunc">
<xsl:with-param name="limit" select="$limit - 1" />
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>


Out put
----------------
Looping function example
10
9
8
7
6
5
4
3
2
1

Thursday, February 18, 2010

Enable and Disable a Control by Binding to another Control


You can Set the Enable Property of a control by binding that control to another control.

How to Achieve this?

See this code snippet.This is a Windows Application Project with C# language.
To test this code you should have a TextBox named "txtName" and a CheckBox named "chk".

In the form load event write this

txtName.DataBindings.Add("Enabled", chk, "Checked");
Execute code and check and uncheck CheckBox. So that you can find the TextBox's property changing.

Serialize Objects using BinaryFormatter

Serialization is the process of converting an object to a format that can be transfer through a network or can be save to a location(file or DB).
The serialized data contains the object's informations like Version,Culture,PublicKeyToken,Type etc.
Deserialization is the reverse process of serialization, that is reconstructing the object from the serialized state to its original state.

Here is an eg:

A class "Employee" and its collection class "Employees". I marked these classes as Serializable with the [Serializable] attribute.
and also i am using BinaryFormatter to Serialize and Deserialize this object.



private void button1_Click
(object sender, EventArgs e)
{
Employees emps = new Employees();
emps.Add(new Employee("1", "Sabu"));
emps.Add(new Employee("2", "Litson"));

String pth = @"E:\Test.dat";
Serialize(emps, pth);
Deserialize(pth);
}

public void Serialize(Employees emps, String filename)
{
System.IO.Stream ms = File.OpenWrite(filename);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(ms, emps);
ms.Flush();
ms.Close();
ms.Dispose();
formatter = null;
}

public void Deserialize(String filename)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
object obj = formatter.Deserialize(File.Open(filename, FileMode.Open));
Employees emps = (Employees)obj;
MessageBox.Show(emps[1].Name);
}


//Classes
[Serializable]
public class Employee
{

public Employee(String id, String name)
{
_ID = id;
_Name = name;
}

private String _ID = String.Empty;
private String _Name = String.Empty;

public String ID
{
get
{
return _ID;
}
set
{
_ID = value;
}
}

public String Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}
}

[Serializable]
public class Employees:CollectionBase
{
//Constructor
public Employees()
{

}

//Add function
public void Add(T objT)
{
this.List.Add(objT);
}

//Indexer
public T this[int i]
{
get
{
return (T) this.List[i];
}
set
{
this.List.Add(value);
}
}
}

Serialize Objects using XmlSerializer class

Xml Serialization
--------------------------------------
Serialization is the process of converting an object to a format that can be transfer through a network or can be save to a location(file or DB).
The serialized data contains the object's informations like Version,Culture,PublicKeyToken,Type etc.
Deserialization is the reverse process of serialization, that is reconstructing the object from the serialized state to its original state.

Here is an eg:

A class "Employee" and its collection class "Employees". I marked these classes as Serializable with the [Serializable] attribute.
and also i am using XmlSerializer class to Serialize and Deserialize this object.

private void button1_Click
(object sender, EventArgs e)
{
Employees emps = new Employees();
emps.Add(new Employee("1", "Sabu"));
emps.Add(new Employee("2", "Litson"));

String pth = @"E:\Test.xml";
XmlSerialize(emps, pth);
XmlDeserialize(pth);
}

public void XmlSerialize(Employees emps, String filename)
{
System.IO.Stream ms = File.OpenWrite(filename);
System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(emps.GetType());
xmlSer.Serialize(ms, emps);
ms.Flush();
ms.Close();
ms.Dispose();
xmlSer = null;
}

public void XmlDeserialize(String filename)
{
System.Xml.Serialization.XmlSerializer xmlSer =
new System.Xml.Serialization.XmlSerializer(typeof(Employees));
FileStream fs = new FileStream(filename, FileMode.Open);
object obj = xmlSer.Deserialize(fs);
Employees emps = (Employees)obj;
MessageBox.Show(emps[1].Name);
}


//Classes

[Serializable]
public class Employee
{

public Employee(String id, String name)
{
_ID = id;
_Name = name;
}

private String _ID = String.Empty;
private String _Name = String.Empty;

public String ID
{
get
{
return _ID;
}
set
{
_ID = value;
}
}

public String Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}
}

[Serializable]
public class Employees:CollectionBase
{
//Constructor
public Employees()
{

}

//Add function
public void Add(T objT)
{
this.List.Add(objT);
}

//Indexer
public T this[int i]
{
get
{
return (T) this.List[i];
}
set
{
this.List.Add(value);
}
}
}

DataGridView - Dynamically Seting up column styles

#region Person Class
public class Person
{
private String _code = String.Empty;
private String _name = String.Empty;
private String _address = String.Empty;
private String _faxNo = String.Empty;
private String _contactPerson = String.Empty;

public int ID
{
get { return _id; }
set { _id = value; }
}

public String Code
{
get
{
return _code;
}
set
{
_code = value;
}
}

public String Name
{
get
{
return _name;
}
set
{
_name = value;
}
}

public String Address
{
get { return _address; }
set { _address = value; }
}

public String FaxNo
{
get { return _faxNo; }
set { _faxNo = value; }
}

public String ContactPerson
{
get { return _contactPerson; }
set { _contactPerson = value; }
}

public void Fill(DataRow drPerson)
{
if (drPerson != null)
{
this.Code =
drPerson["code"].ToString();
this.Name =
drPerson["name"].ToString();
this.Address =
drPerson["address"].ToString();
this.FaxNo =
drPerson["faxno"].ToString();
this.ContactPerson =
drPerson["contactperson"].ToString();
}
}

public List GetAllPersons()
{
List persons = new List();
DataTable dtPerson = new DataTable();

using (SqlConnection conn = DataHelper.GetConnection())
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
String getQuery = "SELECT id,code,name,address," +
"faxno,contactperson FROM person ORDER BY name";
comm.CommandText = getQuery;
comm.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter();
daConst.SelectCommand = comm;

try
{
connConst.Open();
daConst.Fill(dtPerson);

if (dtPerson.Rows.Count < 1)
{
foreach (DataRow drPerson in dtPerson.Rows)
{
Person objPerson = new Person();
objPerson.Fill(drPerson);
persons.Add(objClient);
}
}
}
catch (Exception ex)
{ throw ex; }
finally
{ comm.Dispose(); }
}
}
return persons;
}
}
#endregion


#region "Form Events"
private void FormView_Load(object sender, EventArgs e)
{
SetupGrid();
dgvPersons.DataSource = Person.GetAllPersons();
}


#region SetupGrid
///
/// SetupGrid
///
private void SetupGrid()
{
DataGridViewTextBoxColumn colCode = new DataGridViewTextBoxColumn();
colCode.HeaderText = "Code";
colCode.DataPropertyName = "Code";
colCode.Width = 50;

DataGridViewTextBoxColumn colName = new DataGridViewTextBoxColumn();
colName.HeaderText = "Name";

colName.DataPropertyName = "Name";
colName.Width = 250;

DataGridViewTextBoxColumn colAddressDet = new DataGridViewTextBoxColumn();
colAddressDet.HeaderText = "Address";
colAddressDet.DataPropertyName = "Address";
colAddressDet.Width = 300;

DataGridViewTextBoxColumn colFaxNo = new DataGridViewTextBoxColumn();
colFaxNo.HeaderText = "FaxNo";
colFaxNo.DataPropertyName = "FaxNo";
colFaxNo.Width = 50;

DataGridViewTextBoxColumn colContactPerson = new DataGridViewTextBoxColumn();
colContactPerson.HeaderText = "ContactPerson";
colContactPerson.DataPropertyName = "ContactPerson";
colContactPerson.Width = 100;

DataGridViewButtonColumn colEdit = new DataGridViewButtonColumn();
colEdit.HeaderText = "Edit";
colEdit.FlatStyle = FlatStyle.Flat;
colEdit.UseColumnTextForButtonValue = true;
colEdit.Text = "Edit";
colEdit.Width = 50;

DataGridViewButtonColumn colDelete = new DataGridViewButtonColumn();
colDelete.HeaderText = "Delete";
colDelete.FlatStyle = FlatStyle.Flat;
colDelete.UseColumnTextForButtonValue = true;
colDelete.Text = "Delete";
colDelete.Width = 60;

dgvClients.Columns.AddRange(new DataGridViewColumn[]
{ colCode, colName, colAddressDet, colFaxNo,
colContactPerson, colEdit, colDelete });
}
#endregion
#endregion

Difference between Arraylist and Generic List

//Arraylist - Arraylist accept values as object
//So i can give any type of data in to that.
//Here in this eg: an arraylist object accepting
//values like String,int,decimal, char and a custom object

Employee emp = new Employee("2", "Litson");
ArrayList arr = new ArrayList();
arr.Add("Sabu");
arr.Add(234);
arr.Add(45.236);
arr.Add(emp);
arr.Add('s');
//This process is known as boxing

//To get inserted vales from arraylist we have to specify the index.
//So it will return that values as object.
//we have to cast that value from object to its original type.

String name = (String)arr[0];
int num = (int)arr[1];
decimal dec = (decimal)arr[2];
Employee em = (Employee)arr[3];
char c = (char)arr[4];
//This process that is converting from object to its original type is known as unboxing
//------------------------------------------------------------------------------------
//Generic List
//List<>

//Main advantage of Generic List is we can specify the type of data we are going to insert in to
//List. So that we can avoid boxing and unboxing
//Eg:
List<string> strLst = new List<string>();
strLst.Add("Sabu");//Here List accepting values as String only
strLst.Add("Litson");
strLst.Add("Sabu");
strLst.Add("Sabu");

List<int> intLst = new List<int>();
intLst.Add(12);//Here List accepting values as int only
intLst.Add(14);
intLst.Add(89);
intLst.Add(34);

List<decimal> decLst = new List<decimal>();
decLst.Add(2.5M);//Here List accepting values as deciaml only
decLst.Add(14.4587m);
decLst.Add(89.258m);
decLst.Add(34.159m);

List<Employee> empLst = new List<Employee>();
empLst.Add(new Employee("1", "Sabu"));//Here List accepting Employee Objects only
empLst.Add(new Employee("2", "Mahesh"));
empLst.Add(new Employee("3", "Sajith"));
empLst.Add(new Employee("4", "Binu"));


//To get values from Generic List
String nme = strLst[0]; //No need of casting
int nm = intLst[0];
Decimal decVal = decLst[0];
Employee empVal = empLst[0];

Linq to SQL Update Method

//Creating Employee DataContext object
EmployeeDBDataContext db = new EmployeeDBDataContext();

//Selecting an employee to update his name and address
emp = db.Employees.Single(e => e.EmpID == 1);
emp.Name = "Sabu";
emp.Address = "Cochin";

//Submitting changes
db.SubmitChanges();