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

Thursday, June 3, 2010

Measure code execution time in C#

To time a part of the code in a loop, use ResetTimingValue() before you enter the loop. Than use StartTiming() and AddTimingValue() to get the combined execution time of the code in the loop.

This test uses all the functions of the ExecutionTimer:

Sunday, May 16, 2010

C# Object Serialization to XML file


public class XmlSerializationManager
{
public static void SaveObjectToXmlFile(String path, Object _object, Type _type)
{
FileStream stream = File.Open(path, FileMode.Create, FileAccess.Write);

XmlSerializer serializer = new XmlSerializer(_type);
serializer.Serialize(stream, _object);

stream.Close();
}

public static void SaveObjectToXmlFile(String path, Object _object, Type _type, Type[] extraTypes)
{
FileStream stream = File.Open(path, FileMode.Create, FileAccess.Write);

XmlSerializer serializer = new XmlSerializer(_type, extraTypes);
serializer.Serialize(stream, _object);

stream.Close();
}

public static Object LoadObjectFromXmlFile(String path, Type _type)
{
if (!File.Exists(path))
{
return null;
}

FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read);

if (stream.Length == 0)
{
return null;
}

XmlSerializer serializer = new XmlSerializer(_type);
Object _object = serializer.Deserialize(stream);

stream.Close();

return _object;
}

public static Object LoadObjectFromXmlFile(String path, Type _type, Type[] extraTypes)
{
if (!File.Exists(path))
{
return null;
}

FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read);

if (stream.Length == 0)
{
return null;
}

XmlSerializer serializer = new XmlSerializer(_type, extraTypes);
Object _object = serializer.Deserialize(stream);

stream.Close();

return _object;
}
}

C# Logger - Write strings to log file


public class Logger
{
public static bool _doLog = true;

public static void Log(String filename, String Message)
{
if (!_doLog)
return;

if (File.Exists(filename))
{
using (StreamWriter sw = File.AppendText(filename))
{
sw.WriteLine(String.Format("{0} : {1}", DateTime.Now, Message));
sw.Close();
}
}
else
{
using (StreamWriter sw = File.CreateText(filename))
{
sw.WriteLine(String.Format("{0} : {1}", DateTime.Now, Message));
sw.Close();
}
}
}
}

Tuesday, May 11, 2010

C++ version of C# Random.Next(int minValue, int maxValue);


int Random(int min, int max)
{
return (int)((double)rand() / ((double)RAND_MAX + 1.0) * (double)(max - min) + (double)min);
}