Hard things with Expressions (property selector)

It has been hard at least for me.

This method applies the value to the specified property of the target items:

 private static void SetPropertyToAll<T, TValue>(IEnumerable<T> targetItems, Expression<Func<T, TValue>> propertyExpression, TValue value)
        {
            if (propertyExpression.Body is MemberExpression)
            {
                var memberExpression = (MemberExpression)propertyExpression.Body;

                var propInfo = (PropertyInfo)memberExpression.Member;

                foreach (var item in targetItems)
                {
                    propInfo.SetValue(item, value, null);
                }
            }
            else
            {
                throw new InvalidOperationException("See link to the Stack Overflow question below!!");
            }
        }

And this is the original question in which I found all the information I needed in order for this to work like fine cinnamon 😉

http://stackoverflow.com/a/2789606/1025407

Good luck, Expression Boy!

Leyendo imágenes desde streams

Imagina que te da por leer un array de bytes que sabes que es un PNG. Vale, estupendo. Ahora pones todo lo que sabes sobre la mesa y dices “esto está tirado, tío”. Que sí, que me lo creo, pero hay una cosa que fijo no sabes si cuando decodificas la imagen la estás leyendo desde un flujo:

Si el decoder de la imagen lo creas con la opción de BitmapCacheOption Default, la carga de la imagen será “lazy”, o sea, perezosa. No se cargará inmediatamente y si, como yo, eres un programador que suele cerrar los flujos cuando ya no los necesita (stream.Close o con un bloque “using”), en el momento en que va a cargar la imagen porque la necesita, el flujo está cerrado y la imagen no carga ni a la de 3.

En el ejemplo está bien claro, ¡majuelo!

 public static ImageSource FromArray(byte[] bytes)
        {
            using (var memoryStream = new MemoryStream(bytes))
            {
                var decoder = new PngBitmapDecoder(memoryStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                BitmapSource bitmapFrame = decoder.Frames[0];                            
                return bitmapFrame;
            }
        }

Observa el BitmapCacheOption.OnLoad Winking smile Ahí flipamos en 16,7 millones de colores. NECESARIO SI EL STREAM SE CIERRAAAAAAAAA.