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
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
    • Can use 'return yield ???' in conjunction with IEnumerable<> to only return 1 object at a time. This is where the real power of IEnumerable comes from (not from simply returning a list or an array).
    • When returning a list decide what can be exposed to the user and return the appropriate type. 
    • Maybe its best to return an ICollection<> or IList<> and if the code client only needs to enumerate the list they can cast it to an IEnumerable<>. ie. Given ICollection<Widgets> SomeMethod() … The user could invoke it as IEnumerable<Widgets> widgets = SomeMethod()

    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;
    }