Measuring Elapsed Time in C# Methods

When determining why some damned thing in my .NET programs is taking so damned long, it is useful to be able to look at the elapsed time for various sections of code. The straightforward way to do this is to create an instance of System.Diagnostics.Stopwatch, start it, do the thing, then stop the Stopwatch and print out the elapsed time.

But it gets tedious to keep adding those var stopwatch = new Stopwatch(); stopwatch.Start(); and stopwatch.Stop(); Print(stopwatch.ElapsedMilliseconds); lines all over the place, and it also makes the code less readable, so I made a little class to simplify things.

Deserializing Objects from XML in C#

Here's another C# code snippet that takes me way too much time to recreate by just reading the documentation.

This is a simple example of a class that can be serialized to/from XML. In this case the "ServerConfig" XML string can contain a list of servers, looking like this:

<ServerConfig loggingEnabled="1">
    <Server host="test1.example.com" port="9999" />
    <Server host="test2.example.com" port="8888" />

The client code can just do "var serverConfig = ServerConfig.FromXmlString(s);" to deserialize it into a ServerConfig object.

(The method that would serialize a ServerConfig to an XML string is left as an exercise for the reader. I rarely need to do that.)

Pretty-formatting XML in C#

I had a need to convert an XML string to a nice, indented format. It was a little more complicated than I expected, so I'm posting this snippet here where I can find it again when I need it.

using System;
using System.Text;
using System.Xml;
using System.Xml.Linq;

static string PrettyXml(string xml)
    var stringBuilder = new StringBuilder();

    var element = XElement.Parse(xml);

    var settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = true;
    settings.Indent = true;
    settings.NewLineOnAttributes = true;

    using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))

    return stringBuilder.ToString();

Note that this method can throw exceptions for a variety of reasons.

Syndicate content