C Sharp Tricks

From Hobowiki
Jump to navigation Jump to search

Here is a list of things that I've learned from C# that seem to be useful to me in some manner or another at some point or another. Also, I would have called it Stupid C# Tricks, but I can't due to technical restrictions.

Anonymous Timer Method

When doing testing, sometimes it's useful to try and step on the toes of your methods while in progress in order to emulate reality. In order to do this, sometimes what is required is a timer elapsing in the middle of execution of another method. Without going into all the hairy business of building a separate method or class to house all the timer pieces, you can simply build a short little anonymous timer that gives you the options you need. Here's a quick little example using Delegates.

System.Timers.Timer t = new System.Timers.Timer(2000);
System.IO.FileStream file;
t.Elapsed += new System.Timers.ElapsedEventHandler(delegate(object s, System.Timers.ElapsedEventArgs e)
{
    file = new System.IO.FileStream("myfile.txt", System.IO.FileMode.Open);
    ((System.Timers.Timer)s).Stop();
});
System.Timers.Timer t2 = new System.Timers.Timer(4000);
t.Elapsed += new System.Timers.ElapsedEventHandler(delegate(object s, System.Timers.ElapsedEventArgs e)
{
    if (file != null) file.Close();
    ((System.Timers.Timer)s).Stop();
});
t.Start();
t2.Start();

This will wait 2 seconds, open a file for reading, then 2 seconds later it will close that file.

Automatic Get & Set Properties For Testing

When doing testing, you need to check that class properties work as advertised so when you set them the value is stored. This utility automates the process of calling get and set on all properties of a class.

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using CCH.EFile.Common;
using CCH.EFile.Services;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ReturnValidationService.Test
{
    public static class UnitTestExtensions
    {
        public static void SetGetAllProperties(this object o)
        {
            foreach (System.Reflection.PropertyInfo pi in o.GetType().GetProperties())
            {
                if (!pi.CanWrite && pi.CanRead) 
                {
                    object presetValue = pi.GetGetMethod().Invoke(o, null);
                    Assert.IsNotNull(presetValue);
                    continue;
                }
                object value = null;
                if (pi.PropertyType == typeof(char))
                {
                    value = 'Z';
                }

                if (pi.PropertyType == typeof(string))
                {
                    value = "TestValue";
                }

                if (pi.PropertyType == typeof(int))
                {
                    value = 1;
                }

                if (pi.PropertyType == typeof(bool))
                {
                    value = true;
                }

                if (pi.PropertyType == typeof(DataTable))
                {
                    value = new DataTable();
                }

                if (pi.PropertyType == typeof(DateTime))
                {
                    value = DateTime.Now;
                }

                if (pi.PropertyType == typeof(XmlDocument))
                {
                    value = new XmlDocument();
                }

                if (pi.PropertyType == typeof(List<string>))
                {
                    value = new List<string>();
                }

                if (pi.PropertyType == typeof(NameValueCollection))
                {
                    value = new NameValueCollection();
                }

                if (value == null) continue;

                pi.GetSetMethod().Invoke(o, new object[] {value});
                object newValue = pi.GetGetMethod().Invoke(o, null);
                if (!value.Equals(newValue))
                {
                    Assert.Fail($"{pi.Name}: Getter/setter failed, {value} did not equal {newValue}");
                }
            }
        }
    }
}