Showing posts with label C sharp. Show all posts
Showing posts with label C sharp. Show all posts

Friday, May 1, 2009

Code to Serialize Object in C# .Net

Please use the below method if you want to serialize any object. This method returns you a string which is XML consists of all public properties and public data members of the object passed. It perfectly works for any type of reference type object.


String SerializeObject(Object obj)
{
try
{
String XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();

XmlSerializer xs = new XmlSerializer(obj.GetType());
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

xs.Serialize(xmlTextWriter, obj);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}

catch (Exception e)
{
System.Console.WriteLine(e);
return null;
}
}

Tuesday, April 28, 2009

How to sort list of objects in C#

The following code helps in sorting list of objects based on some property’s value.

public class Person
{
public int age;
public string name;

public Person(int age, string name)
{
this.age = age;
this.name = name;
}
}

List people = new List();

people.Add(new Person(50, “Kiran”));
people.Add(new Person(30, “Raghava”));
people.Add(new Person(26, “Andrew”));
people.Add(new Person(24, “Praveen”));
people.Add(new Person(5, “Sudhir”));
people.Add(new Person(6, “Prudhvi”));

Console.WriteLine(”Unsorted list”);
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format(”{0} {1}”, p.age, p.name)); });

Console.WriteLine(”Sorted list, by name”);
people.Sort(delegate(Person p1, Person p2) { return p1.name.CompareTo(p2.name); });
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format(”{0} {1}”, p.age, p.name)); });

people.Sort(delegate(Person p1, Person p2) { return p1.age.CompareTo(p2.age); });
Console.WriteLine(”Sorted list, by age”);
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format(”{0} {1}”, p.age, p.name)); });

How to invoke a process/application from parent application using C#

You can start a new process/application using the following C# code line.

System.Diagnostics.Process.Start(filePATH);

filePATH is the relative path of the application executable.

If you give a website url in filePATH then it will be opened in a default web browser.

Ex: System.Diagnostics.Process.Start(”http://rampgroup.com”); will cause to open the website home page in a default web browser.