Thursday, March 1, 2018

A couple of really useful extension methods

This one can make a List<> out of a SortedList

        public static List ToList(this SortedList collection)
        {
            var list = new List();
            foreach (DictionaryEntry item in collection)
                list.Add((T)item.Value);
            return list;
        }

And this one solves the problem of trying to stuff an instance of a base class into an instance of a class derived from it.
 
      public static T As(this object donor)
        {
            var type = typeof(T);
            var instance = Activator.CreateInstance(type);

            if (type.BaseType != null)
            {
                var properties = type.BaseType.GetProperties();
                foreach (var property in properties)
                    if (property.CanWrite)
                        property.SetValue(instance,  
                        property.GetValue(donor, null),
                        null);
            }

            return (T)instance;
        }

Monday, June 10, 2013

Cross Threaded Invoke of typed method

private string MyMethod(string inString)
{
   if (this.InvokeRequired)
      return (string)this.Invoke(new MethodInvoker(() => MyMethod(inString)));
   else
   {
      string result = "";
      // working code of MyMethod
      return result;
   }
}

Friday, February 15, 2013

Serializing a class

The Class:

    [Serializable]
    public class _Config
    {
        public string AppTitle { get; set; }
        public int AppNumber { get; set; }        
    }



To Serialize:

         using System.Xml.Serialization;         

    XmlSerializer ser = new XmlSerializer(typeof(_Config));

    var config = new _Config()
                {
                   AppTitle = "MyApp",
                   AppNumber = 42
                };



    using (var writer = new     
           StreamWriter("c:\\some\\path\\MyApp.xml"))
    {
        ser.Serialize(writer, config);
    }

To Deserialize:


   using (var reader = new 
          StreamReader("c:\some\\path\\MyApp.xml"))
   {
       config = (_Config)ser.Deserialize(reader);
   }

Wednesday, December 19, 2012

Cross thread control update

Here is a very nice way to update a UI control from a worker thread...


string newText = "abc"; // running on worker thread
this.Invoke((MethodInvoker)delegate {
    someLabel.Text = newText; // runs on UI thread
});
Here is how it is done in WPF
if (someLabel.Dispatcher.CheckAccess())
    someLabel.Text = newText;
else
    someLabel.Dispatcher.Invoke(new Action(() => someLabel.Text = newText), null);
    DoEvents();
And a WPF 'DoEvents' equivalent
public void DoEvents()
{
   try
   {
      Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(delegate { }));
   }
   catch { }
}

Tuesday, December 4, 2012

A great way to define a class with disposing

If you are creating a class that hold unmanaged resources or 'fat' managed resources you want released immediately (instead of waiting for the GC), you can implement them like this pattern or like this:

In the project, define these two classes:


public interface IDisposer : IDisposable
{    
    void Initialize(Action disposeCallback);

    public class Disposer : IDisposer 
    {
        private readonly Action _disposeCallback;

        public void Initialize(Action disposeCallback) 
        {
            _disposeCallback = disposeCallback;
        }

        public void Dispose() 
        {
            _disposeCallback(true);
        }
    }
}

public interface IDisposerFactory : IDisposable
{
    IDisposer Create(Action disposeAction);
}


Then use this pattern when defining new class that have the unmanaged/fat resources:


pubic class YourBuggyClass : IDisposable
{
    private readonly IDisposer _disposer;

    public YourBuggyClass(IDisposerFactory disposerFactory)
    {
        _disposer = disposerFactory.create((disposing) => 
                    DoRealDispose(disposing));
    }

    private void DoRealDispose(bool disposing) {
        // dispose your unmanaged/fat stuff here
    }

    public void Dispose() 
    {
        _disposer.Dispose();
    }
}

Monday, November 19, 2012

Easy way to have a class publish an event

This is an easy way to have a class fire an event. First declare the event as an Action<> in the class.

public class MyClass
{
    public event Action<int, string> MyEvent;
    public event EventHandler<bool> MyOtherEvent; 
 
    public MyClass()
    {
    }
    private void MyMethod(int i, string s, bool b)
    {
        // an exception will be thrown if you attempt to fire an event 
        // when there are no subscribers to the event, so we need to 
        // check first
        if (MyEvent != null)
            MyEvent(i,s);  // fires the event
                                                    
           MyOtherEvent?.Invoke<this, b>;   
    }
}

To consume the event, just declare a handler for it after instantiating the class.

    MyClass mc = new MyClass();
    mc.MyEvent += new Action(mc_MyEvent);
    mc.MyOtherEvent += Mc_MyOtherEvent;

   void mc_MyEvent(int i, string s)
   {

   }

   private static void Mc_MyOtherEvent(object sender, bool e)
   {
       
   }

Saturday, November 10, 2012

How to lock a resource

List myList = new List();
public static ReaderWriterLockSlim myLock = new ReaderWriterLockSlim();


public void myMethod(string Foo);
{
   myLock.EnterWriteLock(); //waits here if anything else has entered the lock
   myList.Add(Foo);
   myLock.ExitWriteLock();
}

public void myOtherMethod(string Bar);
{
   //Because this call doesn't use the lock, 
   //it ignores the lock and still can write to the list
   myList.Add(Bar);

   //this call would 'play nice' with other calls using the lock
   //once you use a lock on something, you should probably always
   //use a lock on that thing
   myLock.EnterWriteLock(); //waits here until the lock in myMethod is exited
   myList.Add(Bar);  
   myLock.ExitWriteLock();
}