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; }
}

Dirty way to solve "Cross thread operation not valid" error

// Dirty way to solve "Cross thread operation not valid" error

System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

// [put thread dirty code here - like setting property of a Form created
// in another form, which is a deadly sin by Microsoft]

System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = true;

BUG SOLVE: AcceptButton not Selected when Form is loaded

// BUG SOLVE: AcceptButton not Selected when Form is loaded

private void Form1_Load(object sender, EventArgs e)
{
if (AcceptButton != null)
((Button)AcceptButton).Select();
}

Local protect data (bind to a machine)

// Local protect data (bind to a machine)

using System.Security.Cryptography;

private static readonly byte[] salt = new byte[] { 0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c };

public static byte[] ProtectLocalData(byte[] plain)
{
return ProtectedData.Protect(plain, salt, DataProtectionScope.LocalMachine);
}

public static byte[] UnprotectLocalData(byte[] cipher)
{
return ProtectedData.Unprotect(cipher, salt, DataProtectionScope.LocalMachine);
}

Dataset compression

// Dataset compression

private static byte[] DataSetCompress(DataSet dataSet)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress);
bf.Serialize(ds, dataSet);
ds.Flush();
ds.Close();
return ms.ToArray();
}
private static DataSet DataSetDecompress(byte[] data)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream(data);
DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress);
DataSet dataSet = (DataSet)bf.Deserialize(ds);
return dataSet;
}

Safe update of windows control from other threads

// Safe update of windows control from other threads

delegate void UpdateReportCallback(string text);
private void UpdateReport(string message)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBoxReport.InvokeRequired)
{
UpdateReportCallback d = new UpdateReportCallback(UpdateReport);
this.Invoke(d, new object[] { message });
}
else
{
textBoxReport.Text = message + System.Environment.NewLine + textBoxReport.Text;
}
}

Parametrized thread start

// Parametrized thread start

Thread t = new Thread (new ParameterizedThreadStart(FetchUrl));
t.Start (www.google.com);

// ....

static void FetchUrl(object _url)
{
string url = (string)_url;
}

Access list of digital certificates through built-in UI

// Access list of digital certificates through built-in UI

X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection certs = X509Certificate2UI.SelectFromCollection(store.Certificates,"Certificates", "Please select certificate to use", X509SelectionFlag.SingleSelection);

Primitive run count application (demo) protection

// Primitive run count application (demo) protection

public static int GetRunCount()
{
int count = 0;
string guid = "";
RegistryKey regKey = Registry.CurrentUser.OpenSubKey(@"Software\Classes\Software\Settings", true);

if (regKey != null)
{
string temp = (string)regKey.GetValue("Options");
guid = (string)regKey.GetValue("Guid");
count = (int)(temp[0] ^ guid[0]);
}

return count;
}
public static int IncrementRun()
{
int count = 0;
string guid = "";
RegistryKey regKey = Registry.CurrentUser.OpenSubKey(@"Software\Classes\Software\Settings", true);

if (regKey == null)
{
regKey = Registry.CurrentUser.CreateSubKey(@"Software\Classes\Software\Settings");
guid = Guid.NewGuid().ToString();
regKey.SetValue("Guid", guid);
count = 0;
}
else
{
string temp = (string)regKey.GetValue("Options");
guid = (string)regKey.GetValue("Guid");
count = (int)(temp[0] ^ guid[0]);
}

Random rnd = new Random();
count++;
string value = string.Format("{0}{1}", (char)(guid[0] ^ count), GenerateGarbage(15));

regKey.SetValue("Options", value);

return count;
}
private static string GenerateGarbage(int length)
{
string retVal;
if (length < 0)
retVal = null;
else if (length == 0)
retVal = "";
else
{
Random rnd = new Random();
StringBuilder str = new StringBuilder();

for (int i = 0; i < length; i++)
str.Append((char)rnd.Next(33, 126));
retVal = str.ToString();
}
return retVal;
}

Simplest digital signing

// Simplest digital signing

X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection certs =
X509Certificate2UI.SelectFromCollection(store.Certificates,
"Certificates", "Please select certificate to use", X509SelectionFlag.SingleSelection);

CmsSigner cms = new CmsSigner(certs[0]);
SignedCms sig = new SignedCms(new ContentInfo(new byte[10]));

sig.ComputeSignature(cms, false);

Interprocess synchronization (safe threading)

// Interprocess synchronization (safe threading)

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ConsoleApplication12
{
class Program
{
static object thisLock = new object();
static int z = 0;
private static void ThrStart()
{
for (int i = 0; i < 10000; i++)
{
lock (thisLock)
{
z++;
Console.WriteLine(z);
}
}
}

private static void ThrStart2()
{
for (int i = 0; i < 10000; i++)
{
Monitor.Enter(thisLock);
z++;
Console.WriteLine(z);
Monitor.Exit(thisLock);
}
}

static Mutex mutex = new Mutex();
private static void ThrStart3()
{
for (int i = 0; i < 10000; i++)
{
mutex.WaitOne();
z++;
Console.WriteLine(z);
mutex.ReleaseMutex();
}
}


static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(ThrStart));
Thread t2 = new Thread(new ThreadStart(ThrStart));
t1.Start();
t2.Start();
t1.Join();
t2.Join();

t1 = new Thread(new ThreadStart(ThrStart2));
t2 = new Thread(new ThreadStart(ThrStart2));
t1.Start();
t2.Start();
t1.Join();
t2.Join();

t1 = new Thread(new ThreadStart(ThrStart3));
t2 = new Thread(new ThreadStart(ThrStart3));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
}
}
}

Solution for a common problem: "Cannot write to the registry"

// Solution for a common problem: "Cannot write to the registry"

// Original (not working):

RegistryKey reg = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop");
reg.SetValue("WallpaperStyle", "1"); //2 for stretch


// Modified (working):

RegistryKey reg = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
reg.SetValue("WallpaperStyle", "1"); //2 for stretch

Calculate MD5 hash

// Calculate MD5 hash

public string CalculateMD5Hash(string input)
{
// step 1, calculate MD5 hash from input
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);

// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}