Monday, April 25, 2011

How to Serialize and DeSerialize a Generic List

private void button1_Click(object sender, EventArgs e)
{
List<Employee> emps = new List<Employee>();
emps.Add(new Employee("1", "Sabu"));
emps.Add(new Employee("2", "John"));
emps.Add(new Employee("3", "Tom"));
emps.Add(new Employee("4", "George"));
string serializedXmlString = XmlSerialize(emps);
List<Employee> deserializedEmps = XmlDeserialize(serializedXmlString);
}

//XmlSerialize method
public string XmlSerialize(List<Employee> emps)
{
System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(emps.GetType());
StringWriter textWriter = new StringWriter();
xmlSer.Serialize(textWriter, emps);
xmlSer = null;
return textWriter.ToString();
}


//XmlDeserialize method
public List<Employee> XmlDeserialize(String data)
{
System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(List<Employee>));
TextReader reader = new StringReader(data);
object obj = xmlSer.Deserialize(reader);
return (List<Employee>)obj;
}


//Employee Class with Serializable attribute

[Serializable]
public class Employee
{
public Employee()
{
ID = "";
Name = "";
}

public Employee(String id, String name)
{
ID = id;
Name = name;
}


public string ID { get; set; }
public string Name { get; set; }
}

SQL Table Reseeding

For Reseeding an Identity column use this statement.

DBCC CHECKIDENT (Employee, RESEED, 0)
Employee is the TABLE NAME. After the execution of this statement identity value will start from 1...

if you want to start from 11, execute statement like
DBCC CHECKIDENT (Employee, RESEED, 10)


DBCC means Database Console Commands.
this command statements are grouped in to several categories

  • Maintenance statements - Maintenance tasks on a database, index, or filegroup.
  • Miscellaneous statements - Miscellaneous tasks such as enabling row-level locking or removing a dynamic-link library (DLL) from memory.
  • Status statements - Status checks.
  • Validation statements - Validation operations on a database, table, index, catalog, filegroup, system tables, or allocation of database pages.

For more info
1. http://msdn.microsoft.com/en-us/library/aa258281(v=sql.80).aspx
2. http://msdn.microsoft.com/en-us/library/aa258817(v=sql.80).aspx