Thursday, July 24, 2008

C# convert between int and byte array

BitConverter is a native way of converting int and byte[]. In fact, converting byte array into float(single in C#), double, Int16,Int32 etc....

For example:
int tmp = 10;
byte[] b = BitConverter.GetBytes(tmp);

// convert to float
byte[] b = new byte[4];
BitConverter.ToSingle(b, 0);

Depending on how you want the byte[] to be converted, BitConverter has whole lot functions to do that.Only to remember, if you are about to convert 8 bit byte array, you can simply cast it to int.

One interesting thing is that when you wanted to receive bytes from network, you might need to worry about big endian and little endian issue. I saw some hard solutions, but found a simple way of doing it.

byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
Array.Reverse(receiveBytes);

Enjoy

Tuesday, July 22, 2008

.Net C# serial port

http://msmvps.com/blogs/coad/archive/2005/03/23/SerialPort-_2800_RS_2D00_232-Serial-COM-Port_2900_-in-C_2300_-.NET.aspx

The above sample code is one of the best tutorial I have ever find discussing serial port programming using .Net. I recently been asked to download data from device through serial port.
To start with, I used the demo example to send simple command to the device and see whether the response is what I expected. Then I start working on my own application. Enjoy.

Windows Fomr ----- Datagridview with collapse function

After a lot of digging, I realise the easiest way to create collapse function in datagridview is by using a + or - icon and implement the algorithm myself.
The custom control is either too complected or not I want. Just use an image and it solves all problems.

Windows From ----- Only one instance of the program can be started

Don't want user to start your application twice ? Use the code below:

static void Main()
{
bool instanceCountOne = false;

using (Mutex mtex = new Mutex(true, "MYApplication", out instanceCountOne))
{
if (instanceCountOne)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

using(login l = new login())
{
if (l.ShowDialog() == DialogResult.OK)
{
l.Dispose();

if (Properties.Settings.Default.from_database == true && Properties.Settings.Default.Start_CommitChanges == true)
{
Connecter c = new Connecter();
commit_changes(c);
}

Application.Run(new GUI());
}
else
{
l.Dispose();
//MessageBox.Show("Login Cancelled.");
}
}

mtex.ReleaseMutex();
}
else
{
MessageBox.Show("An application instance is already running");
}
}
}