Update 2010-03-23 – Sorry, but the images and downloads were hosted on a server that is no longer available. I will try to find the sample code bits and images on a backup sometime!
The code previously posted for the .NET Reference Messenger Bot was built for .NET 1.1, and when running under 2.0 an InvalidOperationException occurs (thanks to Jeff Gonzalez for pointing this out.)
I’ve since modified the code to work in 2.0, and posted a separate download at the following link.
http://www.scottvanvliet.com/downloads/NRB_fx_2_0.zip
For those of you that are interested in the cause of this error:
The DotMSN API implementation responds to interactions with MSN Messenger on different threads. The test application simply handled those thread callbacks and set the some properties on controls in the form directly. The problem with this approach is that it is not thread-safe. In 1.1, this bad practice does not generate an error, nor is it validated for thread safety. However, 2.0 does a better job (albeit at runtime) of trapping such conflicts and throws the InvalidOperationException.
Thus, to fix the problem, the interactions between the callbacks and the form have to be thread safe. To do this, I added the following code to the form:
private delegate void SetTextHandler(object control, string text, bool append);
private void SetText(object control, string text, bool append)
{
if (this.txtLog.InvokeRequired)
{
SetTextHandler d = new SetTextHandler(SetText);
this.Invoke(d, new object[] { control, text, append });
}
else
{
System.Reflection.PropertyInfo textProperty = control.GetType().GetProperty("Text");
text = (append) ? String.Concat(textProperty.GetValue(control, null), text) : text;
textProperty.SetValue(control, text, null);
}
}
This method will allow the form to delegate control manipulation to the main thread under which the form is executing. Note that using reflection for setting text is not part of this solution – it just made the refactoring effort a little easier as multiple controls in this test application had their Text properties changed by API callbacks.
Please let me know if you encounter other errors with this test application, or have any questions :)