February 2, 2008

Converting A Class Heirarchy To Xml And Then Html

public class XXXToHtmlHelper
{
    private string xml;
    private Encoding encodingStandard;

    public XXXToHtmlHelper()
    {
        string tmpFileName = Path.GetTempFileName();
        if (Path.HasExtension(tmpFileName))
        {
            tmpFileName = Path.GetFileNameWithoutExtension(Path.GetTempFileName());
        }
        xml = Path.Combine(Path.GetTempPath(), tmpFileName + ".xml");
    }

    public void GenerateHtml(
        Encoding encoding, 
        string xsl, 
        XXX xxx,
        string html)
    {
        XXXToXmlFile(xml, encoding, xxx);
        XXX_XmlToHtml(xml, xsl, html);
        if (File.Exists(xml))
        {
            File.Delete(xml);
        }
    }

    private static void XXXToXmlFile(
        string xmlFile,
        Encoding encoding,
        XXX xxxObj)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            XmlTextWriter writer = new XmlTextWriter(ms, encoding);
            try
            {
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                xxxObj.ToXml(writer);
                writer.WriteEndDocument();
                writer.Flush();
            }
            finally
            {
                writer.Close();
            }
            File.WriteAllBytes(xml, ms.ToArray());
        }
    }


    private void XXX_XmlToHtml(string xmlInput, string htmlOutput)
    {
        XsltArgumentList args = new XsltArgumentList();
        args.AddParam("DATE", "", DateTime.Now.ToString("F"));
        args.AddParam("COMMENT", "", "Some comment");
        args.AddParam("USER", "", Environment.UserName);
        XslCompiledTransform xslt = new XslCompiledTransform();
        xslt.Load(xslFile);
        MemoryStream ms = new MemoryStream();
        xslt.Transform(xmlInput, args, ms);
        File.WriteAllBytes(htmlOutput, ms.ToArray());
    }

}

Using Wait Cursor

Cursor = Cursors.WaitCursor;
try
{

}
finally
{
    Cursor = Cursors.Default;
}

Keyboard Handling in Win Forms

C# Key Processing Techniques Use Form.KeyPreview = true Tells form to receive all KeyPress, KeyDown, and KeyUp events. After the form's event handlers have completed processing the keystroke, the keystroke is then assigned to the control with focus. For example, if the KeyPreview property is set to true and the currently selected control is a TextBox, after the keystroke is handled by the event-handling methods of the form the TextBox control will receive the key that was pressed. To handle keyboard events only at the form level and not allow controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form's KeyPress event-handling method to true. eg.: Hide the form when the Escape key is Pressed
myForm.KeyPreview = true;
...
protected override bool ProcessDialogKey(Keys keyData)
{
    if (keyData == Keys.Escape)
    {
        this.Hide();
        return true;
    }
    return base.ProcessDialogKey(keyData);
}

IEnumerable, ICollection, IList Compared

  • IEnumerable<> => Allows use of 'foreach' on a collection. The collection can be inspected in a forward only manner. You must never remove or add elements of an enumerable whilst iterating it.
  • ICollection<> => As IEnumerable<> + Add(), Remove(), Count, Clear(), Contains(), IsReadOnly, CopyTo()
  • IList<> => As ICollection<> + this[int], Insert(), IndexOf(), RemoveAt(). ie. It adds indexing type list operators.Use this when you need a collection that is considered ordered in some manner
  • IReadOnlyXXX<> => Finally we have the ReadOnlys: IReadOnlyList<> and IReadOnlyCollection<>. Most of the time when you return a Collection or List you don't want your users to be able to modify it. This is where the ReadOnly modifier comes into play. Apart from the IEnumerable<> which is at the heart of Linq and all it's wonderful magic, most of the time you will be probably be returning an IReadOnlyXXX<>

SQL Links

SQL Syntax - Also Shows the syntax for creating SQL tables. Not too VERBOSe but quite complete Another SQL Lookup Another SQL Lookup Another SQL Lookup Teach Yourself SQL Server SQL Server Data Types and Their .NET Framework Equivalents

Anonymous Delegates And Iterators

c# 2.0 Iterators
Using anonymous delegates

This code: (Note how an anonymous method can access local variables!)
...
XXX mainXXX = ...
...
xxxList.RemoveAll(
    delegate(XXX xxx)
    {
        return xxx.Id == mainXXX.Id; 
    }
);
Does the same as this:
List entriesToRemove = new List();
foreach (XXX xxx in xxxList)
{
    if (xxx.Id == mainXXX.Id)
    {
        entriesToRemove.Add(xxx);
    }
}
foreach (XXX xxx in entriesToRemove)
{
    xxxList.Remove(userToRemove);
}

Calculate Drive Free Space

Calculate the Ammount of Freespace on a Given Drive
private static long FreeSpaceOnDrive(string path)
{
    long res = 0;
    string root = string.Empty;
    if (Path.IsPathRooted(path))
    {
        root = Path.GetPathRoot(path);
        DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
        foreach (DriveInfo drive in drives)
        {
            if (root.Equals(Path.GetPathRoot(drive.Name), 
                StringComparison.InvariantCultureIgnoreCase))
            {
                if (drive.IsReady)
                {
                    res = drive.AvailableFreeSpace;
                    break;
                }
            }
        }
    }
    return res;
}