Friday, October 17, 2008

WPF gotcha: MessageBox.Show() inside Dispatcher.Invoke

in WPF, if you’re calling MessageBox.Show() inside a Dispatcher.Invoke call (when you’re moving back to the GUI thread from a worker thread), make sure you pass a Window object for the optional first parameter when calling MessageBox.Show (e.g. MessageBox.Show(this, "Message Here", "Title Here");). if you don’t, the message box can show up non-modal alongside your app, which is almost never your intent



Thursday, October 16, 2008

use a specialized Xml writer when creating xml strings

avoid creating Xml streams by string manipulation (e.g. string s = "<Name First='" + firstName + "' Last='" + lastName + "'/>), since you get no reserved character escaping and will throw an error when certain input characters are processed.

in .NET 3.5, there are two good choices: XDocument (in System.Xml.LINQ) and XmlWriter (in System.Xml). XDocument is particularly powerful, since both it and XElement have param of objects constructors, which means you can specify all elements and each element’s attributes in one statement. it ends up looking very declarative:

XDocument xDoc = new XDocument(
new XElement("Name",
new XAttribute("First", firstName),
new XAttribute("Last", lastName)

string encodedXml = xDoc.ToString();

you can use XmlWriter to write directly to a Stream or to a StringBuilder:

StringBuilder sb = new StringBuilder();

using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true } ))
writer.WriteAttributeString("First", firstName);
writer.WriteAttributeString("Id", lastName);

string encodedXml = sb.ToString();