May 25, 2006

Using DOM to parse an Xml Document

XmlDocument xDoc = new XmlDocument();
try
{
  // load the configuration file
  xDoc.Load(sFileName);

  // find the node of interest from the key
  XmlNode theNode = 
  xDoc.SelectSingleNode(@"/thingy/appSettings/add[@key = '" + key + "\']");

  // retrieve the nodes value if it exists
  if (theNode != null)
    return theNode.Attributes["value"].Value;
}

NUnit as the Debugging Application in Visual Studio

See also Using NUnit

Setting Visual Studio To test a particular Assembly using the NUnit GUI In VS, for the particular project of interest go to Project->Properties->Configuration Properties->Debugging and set the following fields:

Start Application:
C:\...\NUnitPath\bin\nunit-gui.exe
Command Line Arguments:
/fixture:namespace.of.assembly.to.test.goes.here /run

System.Threading.Interlocked.CompareExchange

Use
System.Threading.Interlocked.CompareExchange(ref x, y, null);
instead of
if (x == null)
{
    lock (lockObject)
    {
        if (x == null)
        {
            x = y;
        }
    }
}

May 24, 2006

The Close and/or Dispose Connundrum

In my opinion "Close() should not call Dispose()". I am not sure what Microsoft's stance is on this. However their views should not always be taken as best. I remember once I wrote some code to store some settings in a Ini file (this was before Xml and config files) and a colleague came and berated me, telling me that the Microsoft standard is that all settings should go in the registry. I thought 'Ini' files were and still are great. The API is simple as is the 'Ini' file format unlike the registry!
Why should Close() not call or implement Dispose(). What if you call Open on the object again? If its been disposed of by the Close() and SuppressFinaliser() was called then you have problems. How will you get the Finaliser back in the Finaliser queue? If you call Dispose() however then you are explicitly saying that all the objects resources should be relinquished this is not the case with Close() where you might want to Open() the object again.
Also, in OO Semantics Close() does not imply that all unmanaged resources will be released. Calling Close() on an object may release 1 or more unmanaged resources but you cannot assume that it releases all of them. In a lazy implementation it may not release any. You should always call Dispose after Close.
Its possible that Open may be called again on an object some time after Close was called but if the object has been disposed of within the previous call to Close then BANG!. I think Paul Wilson's article makes a good case for this. Check this out as well for some other opinions.
In 'Applied Microsoft .NET Framework Programming', Jeffrey Richter 'strongly discourages' the use of Dispose. He says the garbage collector is well written and you should let it do its job.

Quick Time Comparison in .NET

Use System.Environment.TickCount for quick stop watch type functionality
  private int startTime = System.Environment.TickCount;
  private const int TenSeconds = 10000;
  Math.Abs(System.Environment.TickCount-startTime) > TenSeconds

Reading XSLT From A Manifest Resource annd Applying It

public static string ApplyXslFromManifest(string sourceXml)
{
  Assembly myAssembly = Assembly.GetAssembly(
typeof(assemblyName)); Stream fileStream = myAssembly.GetManifestResourceStream(
"Common.StripComments.xslt"); StreamReader streamReader = new StreamReader(fileStream); string text = streamReader.ReadToEnd(); return ApplyXslTransform(sourceXml, text); } public static string ApplyXslTransform(
string sourceXml, string xslStyleSheet) { //the outputs string result=""; // read XML XmlTextReader xmlReader = new XmlTextReader(new
StringReader(sourceXml)); // read XSLT XmlTextReader xsltReader = new XmlTextReader(new
StringReader(xslStyleSheet)); XslTransform xslt = new XslTransform (); xslt.Load(xsltReader, null, null); //create the output stream StringBuilder sb = new StringBuilder(); TextWriter outputWriter = new StringWriter(sb); // Transform to a new XPath document XPathDocument xPathDocument = new XPathDocument(
xmlReader); xslt.Transform(xPathDocument, null, outputWriter,
null); //get result result=sb.ToString(); return result; }

May 12, 2006

XSL To Strip Comments Out Of Some Xml

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template 
     match="*|@*|processing-instruction()|text()">
    <xsl:copy>
      <xsl:apply-templates
        select="*|@*|processing-instruction()|text()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

May 11, 2006

Using A System.Threading.Timer To Implement A TimeOut Feature

// The Timer delegate to be invoked on a callback (from 
// another thread)
protected void TimeOut(object obj)
{
  lock(accesslock) // Careful. TimeOut callback occurs on 
another thread { log.Error("Something TIMED OUT, will take action"); TakeTimeOutAction(); } } ... // Example usage using (Timer timer = new Timer(new TimerCallback(TimeOut), null,
10000L, Timeout.Infinite)) { while (!complete) { log.Debug("Something waiting for something else to complete"); Thread.Sleep(1000); } }

Non-expiring Singleton Object Lease

To make the lease on a singleton object never expire override the MarshalByRefObject method 'InitializeLifetiemService'. Simply make the method return null

public override object InitializeLifetiemService()
{
  return null;
}

Loading an Assemby and Creating an Object by Reflection

// Load the containing assembly
Assembly assembly = Assembly.LoadFrom(assemblyPath);
// Get the full name for the object including namespace
string objName = ProjConfig.Instance.NamespaceName
+ "." + className; // Create the object obj = assembly.CreateInstance(objName); // Convert to required class or interface Thingy myThingy = obj as Thingy;