Saturday, May 30, 2009

Base Converter

/*
This class will convert any number in any base to it's equivalent
in any other base.

Valid bases are 2 to 36 inclusive.

Usage:
-
int dec = 255;
string hex = BaseConverter.ToBase(dec.ToString(), 10, 16);

// hex is equal to "FF"
*/

public class BaseConverter {

public static string ToBase(string number, int start_base, int target_base) {

int base10 = this.ToBase10(number, start_base);
string rtn = this.FromBase10(base10, target_base);
return rtn;

}

public static int ToBase10(string number, int start_base) {

if (start_base <> 36) return 0;
if (start_base == 10) return Convert.ToInt32(number);

char[] chrs = number.ToCharArray();
int m = chrs.Length - 1;
int n = start_base;
int x;
int rtn = 0;

foreach(char c in chrs) {

if (char.IsNumber(c))
x = int.Parse(c.ToString());
else
x = Convert.ToInt32(c) - 55;

rtn += x * (Convert.ToInt32(Math.Pow(n, m)));

m--;

}

return rtn;

}

public static string FromBase10(int number, int target_base) {

if (target_base <> 36) return "";
if (target_base == 10) return number.ToString();

int n = target_base;
int q = number;
int r;
string rtn = "";

while (q >= n) {

r = q % n;
q = q / n;

if (r < 10)
rtn = r.ToString() + rtn;
else
rtn = Convert.ToChar(r + 55).ToString() + rtn;

}

if (q < 10)
rtn = q.ToString() + rtn;
else
rtn = Convert.ToChar(q + 55).ToString() + rtn;

return rtn;

}

}

Benchmark/performance timers

// Benchmark/performance timers (See Example tab for usage)

internal class UnmanagedApi
{
[DllImport("Kernel32.dll")]
internal static extern bool QueryPerformanceCounter(
out long lpPerformanceCount);

[DllImport("Kernel32.dll")]
internal static extern bool QueryPerformanceFrequency(
out long lpFrequency);
}
public class PrecisionTimer
{
private long startTick;
private long stopTick;
private long tickFrequency;
public PrecisionTimer()
{
UnmanagedApi.QueryPerformanceFrequency(out tickFrequency);
}
internal class UnmanagedApi
{
[DllImport("Kernel32.dll")]
internal static extern bool QueryPerformanceCounter(
out long lpPerformanceCount);
[DllImport("Kernel32.dll")]
internal static extern bool QueryPerformanceFrequency(
out long lpFrequency);
}

public void Start()
{
Thread.Sleep(0); //execute waiting threads first, then continue
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
UnmanagedApi.QueryPerformanceCounter(out startTick);
}

public void Stop()
{
UnmanagedApi.QueryPerformanceCounter(out stopTick);
}

public static long Tick()
{
long retVal;
UnmanagedApi.QueryPerformanceCounter(out retVal);
return retVal;
}

private long ticks
{
get
{
if (startTick > stopTick)
{
startTick = stopTick = 0;
return 0;
}
else
{
return (stopTick - startTick);
}
}
}
public void WriteLine()
{
Console.WriteLine("{0} ms", durationMs);
}
public double durationS
{
get { return (double) ticks/tickFrequency; }
}
public double durationMs
{
get { return durationS*1000; }
}
}
public class NormalTimer
{
private long startTick;
private long stopTick;
public void Start()
{
Thread.Sleep(0); //execute waiting threads first, then continue
startTick = Environment.TickCount;
}
public void Stop()
{
stopTick = Environment.TickCount;
}
private long ticks
{
get
{
if (startTick > stopTick)
{
startTick = stopTick = 0;
return 0;
}
else
{
return (stopTick - startTick);
}
}
}

public long durationMs
{
get { return ticks; }
}
public double durationS
{
get { return (double) ticks/1000; }
}
}

Sort generic list

// Sort generic list

public class Item
{
public Item(string term, int freq)
{
_term = term;
_freq = freq;
}

private string _term;
public string Term
{
get { return _term; }
set { _term = value; }
}

private int _freq;
public int Freq
{
get { return _freq; }
set { _freq = value; }
}
}

public class ItemComparer:IComparer
{
#region IComparer Members

public int Compare(Item x, Item y)
{
return y.Freq - x.Freq; //descending sort
//return x.Freq - y.Freq; //ascending sort
}

#endregion
}

static void Main()
{
List items = new List();
// ....
items.Sort(new ItemComparer());
}

"Extend" the thread class in C#

// just inherit from the EasyThread class and override the PerformWork method

public class EasyThread: IDisposable
{
Thread WorkerThread;

public EasyThread()
{
if (WorkerThread == null)
WorkerThread = new Thread(new ThreadStart(PerformWork));
}

public void Run()
{
if (WorkerThread.IsAlive == false)
WorkerThread.Start();

if (WorkerThread.ThreadState == ThreadState.Suspended)
WorkerThread.Resume();
}

///
/// EasyThread provides a facade to inheriting from a Thread class.
/// Override the perform work method to perform your tasks.
///

protected virtual void PerformWork()
{

}

public void Pause()
{
WorkerThread.Suspend();
}

public void Quit()
{
Cleanup();
}

private void Cleanup()
{
WorkerThread.Join(0);
WorkerThread = null;
}

public void Dispose()
{
Cleanup();
}
}

IsPrime?

public static bool IsPrime(Int32 ToBeChecked)
{
System.Collections.BitArray numbers = new System.Collections.BitArray(ToBeChecked+1, true);

for (Int32 i = 2; i < ToBeChecked+1; i++)
if (numbers[[b][/b]i])
{
for (Int32 j = i * 2; j < ToBeChecked+1; j += i)
numbers[j] = false;

if (numbers[i])
{
if (ToBeChecked == i)
{
return true;
}
}
}

return false;
}

Visit Every Control on a Form (includes nested controls, no recursion)

// Get the first control in the tab order.
Control ctl = this.GetNextControl(this, true);

while (ctl != null)
{
// Use ctl here.

// Get the next control in the tab order.
ctl = this.GetNextControl(ctl, true);
}

Designer clearing overloaded text property in usercontrol

// If you write custom control's like class LabelEx:Label, and override
// its Text property, then everytime you set Text property in Designer
// and compile the code, Visual Studio will clear content of Text property.

// Solution:

[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] //!!!
public override string Text {
get { return checkBox1.Text; }
set { checkBox1.Text = value; }
}