Click here to Skip to main content

jpmik - Professional Profile

6,226
Author
141
Authority
196
Debator
5
Editor
22
Enquirer
331
Organiser
514
Participant
No Biography provided
Member since Saturday, November 23, 2002 (9 years, 6 months)

For more information on Reputation please see the FAQ.
 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
  Refresh
GeneralWeak Timer Pin
Monday, January 2, 2012 11:27 AM
Here's a System.Threading.Timer drop-in replacement (not all overloads are present, but you get the idea). It doesn't prevent the target from being garbage collected like the original does.
 
    public class WeakTimer
    {
        private readonly Timer m_Timer;
        private readonly WeakReference m_WeakTarget;
        private readonly Action<object, object> m_Invoker;
 
        public WeakTimer(TimerCallback tc, object state, int dueTime, int period)
        {
            if (tc.Method.IsStatic)
            {
                m_Timer = new Timer(tc, state, dueTime, period);
            }
            else
            {
                m_WeakTarget = new WeakReference(tc.Target);
                m_Invoker = GenerateInvoker(tc.Method);
                m_Timer = new Timer(MyCallback, state, dueTime, period);
            }
        }
 
        private static Action<object,object> GenerateInvoker(MethodInfo method)
        {
            var instExpr = Expression.Parameter(typeof(object), "instance");
            var paramExpr = Expression.Parameter(typeof(object), "state");
            // ((Method.DeclaringType)instance).Method(param)
            var invokeExpr = Expression.Call(Expression.Convert(instExpr, method.DeclaringType), method, paramExpr);
            return Expression.Lambda<Action<object, object>>(invokeExpr, instExpr, paramExpr).Compile();
        }
 
        private void MyCallback(object state)
        {
            object handler = m_WeakTarget.Target;
 
            if (handler != null)
            {
                m_Invoker(handler, state);
            }
            else
            {
                m_Timer.Change(Timeout.Infinite, Timeout.Infinite);
            }
        }
 
        public void Change(int dueTime, int period)
        {
            m_Timer.Change(dueTime, period);
        }
    }
 

 
GeneralReference Wrapper Pin
Friday, December 17, 2010 12:19 PM
Here's a class that wraps any reference so it's safe to use as a key for a Dictionary of references, regardless whether the original object implemented its Equals() and GetHashCode() correctly.
 
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.CompilerServices;
 
    public class ReferenceWrap<T> : IEquatable<ReferenceWrap<T>>
    {
        private T inner;
 
        public T Inner
        {
            get { return inner; }
        }
 
        public ReferenceWrap(T inner)
        {
            if (inner == null) throw new ArgumentException("inner reference can't be null", "inner");
            this.inner = inner;
        }
 
        public override bool Equals(object obj)
        {
            return Equals(obj as ReferenceWrap<T>);
        }
 
        public override int GetHashCode()
        {
            return RuntimeHelpers.GetHashCode(inner);
        }
 
        public override string ToString()
        {
            return inner.ToString();
        }
 
        public bool Equals(ReferenceWrap<T> other)
        {
            return (other != null && object.ReferenceEquals(other.inner, inner));
        }
    }

 
GeneralTFTP server Pin
Wednesday, April 7, 2010 10:19 AM
I have created a open source managed TFTP server in C#. You can download it at http://tftpserver.codeplex.com/
 
Generalvalue clipping extension method Pin
Wednesday, May 20, 2009 9:59 AM
        public static T Clip<T>(this T value, T minValue, T maxValue) where T : IComparable<T>
        {
            T result;
            if (value.CompareTo(minValue) < 0)
                result = minValue;
            else if (value.CompareTo(maxValue) > 0)
                result = maxValue;
            else 
                result = value;
            return result;
        }

 
GeneralRandomize/Shuffle your lists Pin
Saturday, April 25, 2009 11:50 PM
The following code is a generic extension method that randomly shuffles the contents of a list. It uses a forward form of the Fisher-Yates shuffle algorithm.
 
        public static IEnumerable<tsource> Shuffle<tsource>(this IEnumerable<tsource> source, Random rnd)
        {
            var shuffled = source.ToList();
            for (int t = 0; t < shuffled.Count; t++)
            {
                int newpos = t + rnd.Next(shuffled.Count - t);
                var tmp = shuffled[t];
                shuffled[t] = shuffled[newpos];
                shuffled[newpos] = tmp;
            }
            return shuffled;
        }
</tsource></tsource></tsource>

 
GeneralSerializable Color type Pin
Sunday, April 19, 2009 8:18 AM
If you want to have user-configurable colors and store them in the application settings, you'll notice that System.Drawing.Color doesn't serialize correctly. This is because it doesn't have setters for its public properties. The following class is a convenient wrapper around Color that does provide these and thus serializes correctly.
 
    [Serializable()]
    public struct SerializableColor
    {
        private Color m_Color;
 
        public byte R
        {
            get
            {
                return m_Color.R;
            }
            set
            {
                m_Color = Color.FromArgb(m_Color.A, value, m_Color.G, m_Color.B);
            }
        }
 
        public byte G
        {
            get
            {
                return m_Color.G;
            }
            set
            {
                m_Color = Color.FromArgb(m_Color.A, m_Color.R, value, m_Color.B);
            }
        }
 
        public byte B
        {
            get
            {
                return m_Color.B;
            }
            set
            {
                m_Color = Color.FromArgb(m_Color.A, m_Color.R, m_Color.G, value);
            }
        }
 
        public byte A
        {
            get
            {
                return m_Color.A;
            }
            set
            {
                m_Color = Color.FromArgb(value, m_Color.R, m_Color.G, m_Color.B);
            }
        }
 
        public SerializableColor(int a, int r, int g, int b)
        {
            m_Color = Color.FromArgb(a, r, g, b);
        }
 
        public SerializableColor(Color c)
        {
            m_Color = c;
        }
 
        static public implicit operator SerializableColor(Color c)
        {
            return new SerializableColor(c);
        }
 
        static public implicit operator Color(SerializableColor c)
        {
            return c.m_Color;
        }
    }

 
GeneralStandard variance / Standard deviation extension methods using IEnumerable.Aggregate Pin
Saturday, January 24, 2009 6:48 AM
        
        public static double StandardVariance<T>(this IEnumerable<T> sequence, Func<T, double> selector)
        {
            return sequence.Select(selector).Aggregate(
 
                new{ Count = 0, Q = 0.0, Average = 0.0 },
                
                (a, x) =>
                    new
                    {
                        Count = a.Count + 1,
                        Q = a.Q + Math.Pow(x-a.Average,2.0) * a.Count / (a.Count+1),
                        Average = a.Average + (x-a.Average) / (a.Count+1)
                    }
                ,
 
                a => a.Q / a.Count);
        }
 
        public static double StandardDeviation<T>(this IEnumerable<T> sequence, Func<T, double> selector)
        {
            return Math.Sqrt(sequence.StandardVariance(selector));
        }
 
How to use:
 
            double[] example = new double[]{ 3,4,7,23,5,2,5,212,5 };
            Console.WriteLine("{0}", example.StandardDeviation(x => x));

 
GeneralConvert WIC BitmapFrame to GDI+ Image extension method Pin
Monday, May 26, 2008 7:03 AM
The following code snippet demonstrates an extension method that allows you to convert a BitmapFrame to a GDI+ compatible image.
 
  
    ...  
    using System.Drawing;
    using System.Windows.Media.Imaging;
    ...
 
    public static class WICExtension
    {
        public static Image ToImage(this BitmapFrame bitmapFrame)
        {
            using (Stream s = new MemoryStream())
            {
                // encode the BitmapFrame as a BMP file into a memory stream
                BitmapEncoder bitmapEncoder = new BmpBitmapEncoder();
                bitmapEncoder.Frames.Add(bitmapFrame);
                bitmapEncoder.Save(s);
                s.Flush();
                // reset the memory stream
                s.Seek(0, SeekOrigin.Begin);
                // read the GDI+ Image from the memory stream
                return Bitmap.FromStream(s);
            }
        }
    }

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   


Advertise | Privacy | Mobile
Web04 | 2.5.120528.1 | Last Updated 28 May 2012
Copyright © CodeProject, 1999-2012
All Rights Reserved. Terms of Use
Layout: fixed | fluid