Friday, May 29, 2009

C# - UI Cross Thread

If you use a UI thread to perform lengthy process, you will experience UI "hang" and you will not be able to do anything else (even closing the UI)

To fix that, you will have to start another thread to perform these lengthy process.



//doLengthyProcess is a method that perform your process
Thread newThread = new Thread(new ThreadStart(doLengthyProcess));

// Start the thread
newThread.Start();


But now, if you update UI component at this newThread, you will encounter Croess Thread Exception. The way to fix cross thread issue is delegate. Some steps are

1. You have to create a UI method that update your UI components.
2. Create a Delegate callback to perform UI thread callback
3. Check for InvokeRequire of your UI component
4. If invoke required, use delegate callback to wake up UI thread to perform UI action


//delegate to clear textfield
public delegate void ClearText();

//method to clear text. It check for Cross Thread too
private void clearText() {
if (myText.InvokeRequired){
this.Invoke(new ClearText(clearText));
}else{
myText.Text = "";
}
}

C# - read from file

I am amazed by the simplicity to read all file bytes in C#... WoooHoo


byte[] dataBytes = File.ReadAllBytes("My_FILE_NAME");

Tuesday, May 26, 2009

C# - XML Serialization

C# XML Serialization can be done by

1. Create a serializable class
2. Use a XmlSerializer to serialize and deserialize
3. Use TextWriter and FileStream to write and read from file respectively.

Below are very sample code

A Serializable class - It is a C# class with [Serializable] tag



Write serializable object to xml file




Read xml file and deserialize into object



The resulting xml is



Monday, May 25, 2009

Autorun Program From Removable Media

Autorun, as the name imply, allow program to autorun from removable storage (USB drive, CD-ROM...). This will give you simple guide on how to create a autorun removable storage

To create a autorun removable media, do the following step

1. Create a file call autorun.inf in the root folder of the removable media.

2. Open autorun.inf with any text editor program

3. At the top of the file, put [autorun]. [autorun] denote that this is a autorun file

4. In general, the autorun file setting is in name=value pair. (ie, icon=myicon.ico). The following give you some example of the name value pair

icon=xxx.ico -> allow you to set the icon of your autorun removable media

label=xxxx -> allow you to set the name of this removable media

open=xxxx.xxx -> allow you to define the program with you want to be open when media is inserted

action=xxxx -> allow you to set the action name in the action prompt when you insert your media

shell\xxxx\command -> allow you to set XXXX to the context menu when you right click on the removable media in My Computer folder

shell=xxxx -> allow you to overwrite the default action. Note: If you has set up shell\xxxx\command, you can reuse xxxx as the shell= action

For better clarity, below is a workable autorun.inf example



[autorun]
icon=myicon.ico
label=My USB Drive
open=mydesktop.exe
action=My Desktop Program
shell\MyDesktop\command=mydesktop.exe
shell=MyDesktop




Depend on your Window Version, you may be prompted for Autorun action dialog. This is security feature to prevent malicious attack from removable drive.

Saturday, May 9, 2009

HTTP Persistent Connection

HTTP/1.1 offers HTTP persistent connection. This persistent connection provides a huge improvement in HTTP performance. HTTP persistent connection allows the same TCP connection to send/receive data over the same TCP socket without opening a new socket.

If you have notice, in HTTP/1.0, it does not provide HTTP persistent connection. As a result, each HTTP call opens a new connection.

So, what the issue?

The issue is TCP termination. Whenever a TCP connection terminate, the TCP socket will goes into a Time-Wait state. TCP Time-Wait state make the device to wait for a period of time equal to double the maximum segment life (MSL) time. This gives enough time to ensure the ACK it sent to the client was received. And, the damaging effect is Port Availability, that is, you cannot use that port for 2*MSL time.

In Window and Linux environment, the default TCP Time-Wait is 2 minutes. This means: After a TCP connection is closed, the port is not available for the next 4 minutes.

You may ask, what is the big deal? Imagine... If you are doing HTTP image streaming and each HTTP image fetch open a new connection. Lets do some calculation. If you are streaming at 30FPS for a camera, you will need 1800 ports per minutes. As TCP Time-Wait for Window is 4 minutes, it will use almost 7200 ports in 4 minutes. Very soon, you will use up all the available ports in the system.

In the HTTP/1.0 world, the only solution may be reducing TCP Time-Wait and increase the maximum number of ports can be use in the system.

In Window, you can set

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\TcpTimedWaitDelay

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\MaxUserPorts

to tune the system. See TCP TIME-WAIT Delay for further details.

HTTP/1.1 TCP connection reuse helps to solve this issue. It adds a HTTP header Connection: Keep-Alive to denote TCP connection resuse. In Java Socket, HTTP persistent connection is implemented. It has a default TCP keep-alive and a maximum persistent connection of 5. See Java HTTP Persistent Connection

But, please be aware of 1 thing. That is Connection: close. HTTP/1.1 defines as follows

HTTP/1.1 defines the "close" connection option for the sender to signal that the connection will be closed after completion of the response. For example, Connection: close
in either the request or the response header fields indicates that the connection SHOULD NOT be considered `persistent' (section 8.1) after the current request/response is complete.

That mean, if a HTTP/1.1 reply contains a Connection: close header, the socket will be closed and cannot be reuse. This is true for Java. Please beware.

One way to check if you are using HTTP persistent connection correctly is the command netstat -a in Window. You SHOULD NOT see a lot of TCP connection in TIME-WAIT state under the same Foreign Address. You SHOULD NOT see TCP connection increasing like a bull too.

If you see such events happening, you should start looking at network packet level to diagnose the issue. You may have a Connection: close somewhere. Wireshark is one of the good tools for this.

Monday, May 4, 2009

Use named Mutex to restrict multiple program startup

Something new I had learn from C# today, and that is, the use of Mutex.

I guess most people know what is mutex. For clarity, below is the Mutex definition from Microsoft

When two or more threads need to access a shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex.

But, there is 2 types of Mutex, local and system-wide. Local Mutex is a unnamed mutex that only avaiable for the created process. System-wide Mutex is a named mutex that available for the whole operation system.

Definition from Microsoft

Mutexes are of two types: local mutexes, which are unnamed, and named system mutexes. A local mutex exists only within your process. It can be used by any thread in your process that has a reference to the Mutex object that represents the mutex. Each unnamed Mutex object represents a separate local mutex.
Named system mutexes are visible throughout the operating system, and can be used to synchronize the activities of processes. You can create a Mutex object that represents a named system mutex by using a constructor that accepts a name. The operating-system object can be created at the same time, or it can exist before the creation of the Mutex object. You can create multiple Mutex objects that represent the same named system mutex, and you can use the
OpenExisting method to open an existing named system mutex.

By creating a system-wide mutex, you can restrict a multiple startup of your program.


bool ok;
mutex = new Mutex(true, "Your-Mutex-Name", out ok);



Using Mutex(Boolean, String, Boolean) constructor, it will try to create a system-wide mutex with Your-Mutex-Name and request initial ownship for the calling thread. On method return, ok boolean will indicates whether the calling thread was granted initial ownership of the mutex. So, to prevent multiple program startup, all you need is to check if(ok == false), when that occurs, exit the program.


GC.KeepAlive(mutex);


The above is important to tell VM not to clear the mutex as long as the program is running. Put that after Application.run() will do.

See http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx

Facebook - Control privacy setting of liked page

By default, Facebook displayed your liked page to public. It is the user responsibility to adjust the privacy setting. And in my opinion, F...