May 24, 2006

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;

March 27, 2006

C# Xml Creation Sample

Parsing Hexadecimal

How to parse a number in Hexadecimal form
 newByte = .Parse(hex, System.Globalization.NumberStyles.HexNumber);