XmlValidatingReader is obsolete!

The way you read XML files with validation has been changed in .Net 2.0. Before we could do this:

StringReader sr = new StringReader(xmlfragment);
XmlTextReader tr = new XmlTextReader(sr);

XmlValidatingReader vr = new XmlValidatingReader(tr);
vr.Schemas.Add("", Path.Combine( _sInstallDir, @"Schemas\schema.xsd"));
vr.ValidationType = ValidationType.Schema;
vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);

while (vr.Read())

That still works (in Beta 2 of VS2k5) but will give “obsolete” warnings. Apparently this is the way to go now:

StringReader sr = new StringReader(xmlfragment);

XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, Path.Combine(_sInstallDir, @"Schemas\schema.xsd"));
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);

XmlReader reader = XmlReader.Create(sr, settings);

while (reader.Read())

It’s very similar so I’m not quite sure as to why the modification has been made. Maybe to limit the number of classes in the System.Xml namespace?

Note that you can also use this method with XmlWriter. I haven’t tried that yet, though.

Help, my code examples are messed with!

One supremely annoying problem I had the first days of using WordPress was that it kept on “beautifying” my code samples. For example replacing normal quotes with curly ones. For normal text that’s okay I guess, but for code it isn’t!

For example:

string s = “this is a string”;

Luckily however, this can be fixed by using using a plugin called Preserve Code Formatting by Scott Reilly. Very useful!

Just install it and after that WordPress will keep it’s dirty hands off content within <code>-tags.

The code sample above now reads:

string s = "this is a string";

String.Format tips

Format a number in different ways:

// Result is rounded to 1.9, 2.0, 2.1, etc.
string snitt = String.Format("{0:.0}",total / antal);

// Fill unused space with zeroes
// 000, 001, ..., 023, ... 122, ..., 1232
string s = String.Format("{0:000}", i);

// Result is rounded to 0, 1, 2, etc.

// Right-justified text
string s = String.Format("{0,3}", i);

// Separation into 3 digit groups ("323 232"):
string s = amount.ToString("### ### ###").Trim();

Formatting date strings

Standard DateTime Format Strings

String.Format("{0:u}", DateTime.Now);
// Result: "2005-07-26 15:48:16Z"

For more codes, look up “Standard DateTime Format Strings“.

Can also be used like this:


More examples:

timevar.ToString("yyyy-MM-dd HH:mm");

Custom DateTime Format Strings

String.Format("{0:%d}/{0:%M}", DateTime.Now) ;
String.Format("{0:%d'/'%M}", DateTime.Now);
// Same result for both: "26/7"

“%” is needed for these codes to guarantee that Custom codes are used. The codes ‘d’ and ‘M’ also namely also exists as Standard codes, but with other meanings.

For more codes, look up “Custom DateTime Format Strings“.

Can also be used like this: