Calling a .NET C# class from XSLT

If you've ever worked with XSLT, you'd know that it's pretty limited when it comes to its programming capabilities. Try writing a for loop in XSLT and you'd know what I mean. XSLT is not designed to be a programming language so you should never put too much programming logic in your XSLT. That code can be a pain to write and maintain and so it should be avoided at all costs. Keep your xslt simple and put any complex logic that your xslt transformation requires in a class.

Here is how you can create a helper class and call that from your xslt. For example, this is my helper class:

 public class XsltHelper
    {
        public string GetStringHash(string originalString)
        {
            return originalString.GetHashCode().ToString();
        }
    }

 

And this is my xslt file(notice the namespace declaration that references the helper class):

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:ext="http://MyNamespace">
    <xsl:output method="text" indent="yes" omit-xml-declaration="yes"/>
    <xsl:template  match="/">The hash code of "<xsl:value-of select="stringList/string1" />" is "<xsl:value-of select="ext:GetStringHash(stringList/string1)" />".
    </xsl:template>
</xsl:stylesheet>

 

Here is how you can include the helper class as part of the transformation:

string xml = "<stringList><string1>test</string1></stringList>";
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xml);
 
            XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
            xslCompiledTransform.Load("XSLTFile1.xslt");
 
            XsltArgumentList xsltArgs = new XsltArgumentList();            
            xsltArgs.AddExtensionObject("http://MyNamespace", Activator.CreateInstance(typeof(XsltHelper)));
 
            using (FileStream fileStream = new FileStream("TransformResults.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                // transform the xml and output to the output file ...
                xslCompiledTransform.Transform(xmlDocument, xsltArgs, fileStream);                
            }

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Writing to a file asynchronously

Here is a code snippet for writing to a file asynchronously:

private
void writeFileAsync(string text)
{
      System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
      byte[] buffer = encoding.GetBytes(text);
      using (FileStream fs = new FileStream("temp.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite, buffer.Length, FileOptions.Asynchronous))
      {
           IAsyncResult asyncResult = fs.BeginWrite(buffer, 0, buffer.Length, new AsyncCallback(EndWriteCallback), new State());
      }
}

private void EndWriteCallback(IAsyncResult result)
{
 
}
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

DataGridView upper case textbox column

It's a shame that the DataGridViewTextBoxColumn class doesn't allow you to set the casing so that you can restrict user input to all upper or lower case letters.

Fortunately, it's actually pretty easy to create a custom column class to do just that.
public class DataGridViewUpperCaseTextBoxColumn : DataGridViewTextBoxColumn
{
    public DataGridViewUpperCaseTextBoxColumn()
        : base()
    {
        CellTemplate = new DataGridViewUpperCaseTextBoxCell();
    }
}
 
public class DataGridViewUpperCaseTextBoxCell : DataGridViewTextBoxCell
{
    public DataGridViewUpperCaseTextBoxCell()
        : base()
    {
    }
 
    public override Type EditType
    {
        get
        {
            return typeof(DataGridViewUpperCaseTextBoxEditingControl);
        }
    }
}
 
public class DataGridViewUpperCaseTextBoxEditingControl : DataGridViewTextBoxEditingControl
{
    public DataGridViewUpperCaseTextBoxEditingControl()
        : base()
    {
        this.CharacterCasing = CharacterCasing.Upper;
    }
}

Sweet fancy moses:)
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Scrollable PictureBox control

The PictureBox control in .NET does not have scroll bars, however, it is actually really easy to create a PictureBox control with scroll bars enabled. All you have to do is to drop a panel control onto a form, and set the AutoScroll property to true.

this.panel1.AutoScroll = true;

And drop a PictureBox control inside the panel and set the SizeMode to AutoSize.

this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;

That's it.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Starting a background thread using the Threadpool

Here is a quick and easy way of starting a background process using the Threadpool by way of an inline delegate.

ThreadPool.QueueUserWorkItem(new WaitCallback(
delegate(object stateInfo)
{
    saveToDB();
}));         
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Time enjoyed wasting is not wasted time

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Expect: 100-continue Header Problem

Here is a way for you to disable the Expect: 100-continue Header:

string url = "http://www.myurl.com";
 
ServicePoint sp = ServicePointManager.FindServicePoint(new Uri(url));
sp.Expect100Continue = false;

I was getting a 500 http error when I tried to send a post to a Java web service through .Net using HttpWebRequest. Turning off this header did the trick. This will work even if you are using the WebClient class, which goes through HttpWebRequest under the covers. Hope this helps someone, this is a doozy of a problem to debug.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Sending key presses to applications

I was working on an UI automation project recently and I had to submit key press messages to a windows forms application. I was looking at ways of writing code to make that possible, but then I found that you can actually just call SendKeys.Send() to send any key press message to the active form. Who knew it could be so easy.

http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Microsoft test vouchers

I just found out that I can't use the 15% off voucher and the second shot offer voucher on the same MCTS certification test. That's really lame Microsoft.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Searching for an item in a list

It's cool to see how the .Net framework has evolved from 1.1 to 2.0 and to 3.5. Searching for items in a list is a pretty common programming task. This is a comparison of how list searching has changed throughout the different .Net framework versions.

 
//.Net 1.1 search using a foreach statement
foreach (Customer cust in customerList)
{
    if (cust.FirstName == "Bill")
    {
        customer = cust;
        break;
    }
}
 
//.Net 2.0 search using a inline delegate            
Customer cust = customers.Find(
    delegate(Customer c)
    {
        return c.FirstName == "Bill";
    });
 
//.Net 3.5 search using a lambda expression
Customer cust = customers.Find(C => C.FirstName == "Bill");
 
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
«February»
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910