dhh.GetType();

David Heinemeier Hansson (https://twitter.com/dhh):
Mixed feelings about him. Smart guy, wrong lane. Always in my opinion, of course.

He is a very representative developer that exposes the Anti-Microsoft syndrome. Let’s watch him talk in what I think it’s a flaunting of pride and empty self-satisfaction.

I’m not saying he’s a bad guy, but this gratuitous bash is completely unnecessary, unless he is just another hater. I’m feed up with presumptuous arguments like those.

Mixing Style Setters and Bindings in WinRT

To say the truth, this caught me by surprise. When I stumbled upon the fact that in WinRT you cannot just assign a Binding to a Property Setter. Surprisingly enough, this is not supported.

So no <Setter Property=”Blah” Value=”{Binding Path=Bleh}” />

But some smart dudes have coined a method to make it work. At least, the did in Silverlight 4 (the version 5 already supports Bindings in those Setters). Later, the trick came to WinRT… they say WinRT was forked from Silverlight 4. Now a lot of things make sense :S

What’s the trick? Using Attached Properties.

It uses a helper class to wire up everything. It may seem ugly at first sight, but while WinRT is so restrictive (and much more for a WPF developer like me), it’s the only way I can think of that is more of less XAML oriented.

This is the helper class (WinRT, of course):

// Copyright (C) Microsoft Corporation. All Rights Reserved.
// This code released under the terms of the Microsoft Public License
// (Ms-PL, http://opensource.org/licenses/ms-pl.html).

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Markup;

namespace Delay
{
    /// <summary>
    /// Class that implements a workaround for a Silverlight XAML parser
    /// limitation that prevents the following syntax from working:
    ///    &lt;Setter Property="IsSelected" Value="{Binding IsSelected}"/&gt;.
    /// </summary>
    [ContentProperty(Name = "Values")]
    public class SetterValueBindingHelper
    {
        /// <summary>
        /// Gets or sets an optional type parameter used to specify the type
        /// of an attached DependencyProperty as an assembly-qualified name,
        /// full name, or short name.
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods",
            Justification = "Unambiguous in XAML.")]
        public string Type { get; set; }

        /// <summary>
        /// Gets or sets a property name for the normal/attached
        /// DependencyProperty on which to set the Binding.
        /// </summary>
        public string Property { get; set; }

        /// <summary>
        /// Gets or sets a Binding to set on the specified property.
        /// </summary>
        public Binding Binding { get; set; }

        /// <summary>
        /// Gets a Collection of SetterValueBindingHelper instances to apply
        /// to the target element.
        /// </summary>
        /// <remarks>
        /// Used when multiple Bindings need to be applied to the same element.
        /// </remarks>
        public Collection<SetterValueBindingHelper> Values
        {
            get
            {
                // Defer creating collection until needed
                if (null == _values)
                {
                    _values = new Collection<SetterValueBindingHelper>();
                }
                return _values;
            }
        }

        /// <summary>
        /// Backing store for the Values property.
        /// </summary>
        private Collection<SetterValueBindingHelper> _values;

        /// <summary>
        /// Gets the value of the PropertyBinding attached DependencyProperty.
        /// </summary>
        /// <param name="element">Element for which to get the property.</param>
        /// <returns>Value of PropertyBinding attached DependencyProperty.</returns>
        [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters",
            Justification = "SetBinding is only available on FrameworkElement.")]
        public static SetterValueBindingHelper GetPropertyBinding(FrameworkElement element)
        {
            if (null == element)
            {
                throw new ArgumentNullException("element");
            }
            return (SetterValueBindingHelper)element.GetValue(PropertyBindingProperty);
        }

        /// <summary>
        /// Sets the value of the PropertyBinding attached DependencyProperty.
        /// </summary>
        /// <param name="element">Element on which to set the property.</param>
        /// <param name="value">Value forPropertyBinding attached DependencyProperty.</param>
        [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters",
            Justification = "SetBinding is only available on FrameworkElement.")]
        public static void SetPropertyBinding(FrameworkElement element, SetterValueBindingHelper value)
        {
            if (null == element)
            {
                throw new ArgumentNullException("element");
            }
            element.SetValue(PropertyBindingProperty, value);
        }

        /// <summary>
        /// PropertyBinding attached DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty PropertyBindingProperty =
            DependencyProperty.RegisterAttached(
                "PropertyBinding",
                typeof(SetterValueBindingHelper),
                typeof(SetterValueBindingHelper),
                new PropertyMetadata(null, OnPropertyBindingPropertyChanged));

        /// <summary>
        /// Change handler for the PropertyBinding attached DependencyProperty.
        /// </summary>
        /// <param name="d">Object on which the property was changed.</param>
        /// <param name="e">Property change arguments.</param>
        private static void OnPropertyBindingPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            // Get/validate parameters
            var element = (FrameworkElement)d;
            var item = (SetterValueBindingHelper)e.NewValue;

            if (null != item)
            {
                // Item value present
                if ((null == item.Values) || (0 == item.Values.Count))
                {
                    // No children; apply the relevant binding
                    ApplyBinding(element, item);
                }
                else
                {
                    // Apply the bindings of each child
                    foreach (var child in item.Values)
                    {
                        if ((null != item.Property) || (null != item.Binding))
                        {
                            throw new ArgumentException(
                                "A SetterValueBindingHelper with Values may not have its Property or Binding set.");
                        }
                        if (0 != child.Values.Count)
                        {
                            throw new ArgumentException(
                                "Values of a SetterValueBindingHelper may not have Values themselves.");
                        }
                        ApplyBinding(element, child);
                    }
                }
            }
        }

        /// <summary>
        /// Applies the Binding represented by the SetterValueBindingHelper.
        /// </summary>
        /// <param name="element">Element to apply the Binding to.</param>
        /// <param name="item">SetterValueBindingHelper representing the Binding.</param>
        private static void ApplyBinding(FrameworkElement element, SetterValueBindingHelper item)
        {
            if ((null == item.Property) || (null == item.Binding))
            {
                throw new ArgumentException(
                    "SetterValueBindingHelper's Property and Binding must both be set to non-null values.");
            }

            // Get the type on which to set the Binding
            TypeInfo type = null;
            if (null == item.Type)
            {
                // No type specified; setting for the specified element
                type = element.GetType().GetTypeInfo();
            }
            else
            {
                // Try to get the type from the type system
                type = System.Type.GetType(item.Type).GetTypeInfo();
                if (null == type)
                {
                    // Search for the type in the list of assemblies
                    foreach (var assembly in AssembliesToSearch)
                    {
                        // Match on short or full name
                        type = assembly.DefinedTypes
                            .Where(t => (t.FullName == item.Type) || (t.Name == item.Type))
                            .FirstOrDefault();
                        if (null != type)
                        {
                            // Found; done searching
                            break;
                        }
                    }
                    if (null == type)
                    {
                        // Unable to find the requested type anywhere
                        throw new ArgumentException(
                            string.Format(
                                CultureInfo.CurrentCulture,
                                "Unable to access type \"{0}\". Try using an assembly qualified type name.",
                                item.Type));
                    }
                }
            }

            // Get the DependencyProperty for which to set the Binding
            DependencyProperty property = null;

            var allProperties = type.GetAllProperties();
            var field = allProperties.FirstOrDefault(info => info.Name.Equals(item.Property + "Property"));

            if (null != field)
            {
                property = field.GetValue(null) as DependencyProperty;
            }
            if (null == property)
            {
                // Unable to find the requsted property
                throw new ArgumentException(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        "Unable to access DependencyProperty \"{0}\" on type \"{1}\".",
                        item.Property,
                        type.Name));
            }

            // Set the specified Binding on the specified property
            element.SetBinding(property, item.Binding);
        }

        /// <summary>
        /// Gets a sequence of assemblies to search for the provided type name.
        /// </summary>
        private static IEnumerable<Assembly> AssembliesToSearch
        {
            get
            {
                // Start with the System.Windows assembly (home of all core controls)
                yield return typeof(Control).GetTypeInfo().Assembly;

#if SILVERLIGHT && !WINDOWS_PHONE
                // Fall back by trying each of the assemblies in the Deployment's Parts list
                foreach (var part in Deployment.Current.Parts)
                {
                    var streamResourceInfo = Application.GetResourceStream(
                        new Uri(part.Source, UriKind.Relative));
                    using (var stream = streamResourceInfo.Stream)
                    {
                        yield return part.Load(stream);
                    }
                }
#endif
            }
        }

    }

    public static class ReflectionExtensions
    {
        public static IEnumerable<PropertyInfo> GetAllProperties(this TypeInfo type)
        {
            var list = type.DeclaredProperties.ToList();

            var subtype = type.BaseType;
            if (subtype != null)
                list.AddRange(subtype.GetTypeInfo().GetAllProperties());

            return list.ToArray();
        }
    }
}

And the other important thing is to know how to use it inside XAML:

 <Button
            Grid.Column="1"
            Grid.ColumnSpan="2"
            DataContext="Coco">
            <Button.Style>
                <Style TargetType="Button">
                    <!-- Equivalent WPF syntax:
                    <Setter Property="Content" Value="{Binding}"/> -->
                    <Setter Property="delay:SetterValueBindingHelper.PropertyBinding">
                        <Setter.Value>
                            <delay:SetterValueBindingHelper
                                Property="Content"
                                Binding="{Binding}"/>
                        </Setter.Value>
                    </Setter>
                </Style>
            </Button.Style>
        </Button>

Another example from my Project VisualDesigner:

   <designSurface:DesignSurface Background="PowderBlue"
                                     ItemTemplateSelector="{StaticResource TypedTemplateSelector}"
                                     ItemsSource="{Binding  Items}" Grid.Row="1">
            <!--<designSurface:DesignSurface.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas />
                </ItemsPanelTemplate>
            </designSurface:DesignSurface.ItemsPanel>-->
            <designSurface:DesignSurface.ItemContainerStyle>
                <Style TargetType="winRt:CanvasItemControl">
                    <Setter Property="delay:SetterValueBindingHelper.PropertyBinding">
                        <Setter.Value>
                            <delay:SetterValueBindingHelper>
                                <delay:SetterValueBindingHelper
                                    Type="Canvas"
                                    Property="Left"
                                    Binding="{Binding Left, Mode=TwoWay}" />
                                <delay:SetterValueBindingHelper
                                    Type="Canvas"
                                    Property="Top"
                                    Binding="{Binding Top, Mode=TwoWay}" />
                                <delay:SetterValueBindingHelper
                                    Property="Width"
                                    Binding="{Binding Width, Mode=TwoWay}" />
                                <delay:SetterValueBindingHelper
                                    Property="Height"
                                    Binding="{Binding Height, Mode=TwoWay}" />
                            </delay:SetterValueBindingHelper>
                        </Setter.Value>
                    </Setter>
                </Style>
            </designSurface:DesignSurface.ItemContainerStyle>
        </designSurface:DesignSurface>

Finally, I would like to give thanks to Mark Smith (@marksm in Twitter), for pointing me out some interesting posts to the solution. He has supported me from the beginning. These were the links that he gave me 🙂

Thanks to them, too!

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!

Nice MultiValueConverter

If you have a MultiBinding and you want to get true when every binding evaluates to the same value, then this is four you, little pollo:

 public class AllEqualConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (!values.Any())
            {
                return true;
            }

            var first = values.First();

            var allAreTheSame = values.All(other => Equals(first, other));
            return allAreTheSame;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException("This is only mean to support conversions in One Way");
        }
    }

ASP.NET adventure! SignalR

As I’m an adventurer and I don’t want to get an arrow in the knee, I’ve put my wellington boots and dug a bit into the topic about distributed services, surrounding the web, brrrrhh!! Confused smile 

My friend Xavi (@XaviPaper) told me about SignalR when I mentioned an application that I want to make as a way to practice. In the meanwhile, to get sure that I’m not wasting time learning how to start my first SignalR application/s using old methods, I downloaded Visual Studio .NET 2013 RC (Release Candidate) to get the latest bits. I’m always with the new and tasty Smile But that usually means I problems.

After touching here and there I haven’t had any luck. So I asked Xavi who told me to go to “Variable not found” a blog run by José María Aguilar (@jmaguilar) who seems to be a master on this topic. I contacted him directly, and he kindly tried to guide me. I told them I would try to walk through all the process and come with the results. So I decided to do it and RECORD the process.

Yes, I armed myself and face the problem! knowing that some of the best colleagues are there to help me out. Jumping with a net is really better Smile

The first problem I encountered is that I cannot even have a working base application to start. The most basic skeleton for some simple app. Maybe it’s because I’m just too new to ASP.NET/MVC or whatever technologies are used for this (believe me, there are a lot of them implied into the most basic template!)

To illustrate my short journey into this new world I captured every step I did. Everyone is labeled with a number for anyone to refer to a particular step in order to correct me (because I think I’m doing it wrong in some place).

Step 1.

Visual Studio 2013 RC itself!

image

Step 2.

File > New Project…

image

Step 3.

I choose Visual C# / Web / ASP.NET Web Application and give it a name.

image

Step 4.

After clicking “OK”, a new dialog pops up. I choose MVC blindly. I don’t really know the reason to do it, but I’ve seen this in some tutorials Smile with tongue out I would like to make a web service that sits silently and serves a range of clients (Windows Phone 8 / Windows 8, for instance).

image

After that, I press “Create Project”

Step 5.

An entire structure is created. Wow. That is huge!

image

Step 6.

To add SignalR to the project I deduced I had to install the NuGet package. I choose to manage packages in the project.

image

Step 7.

I explicitly choose “Include prerrelease” in the combo and choose Microsoft ASP.NET SignalR. I press the “Install” button.

image

After that, a lot of packages (some even include JavaScript/jQuery, my dirty nemesis!)

Step 8.

A readme.txt file appears, giving some info about how to setup SignalR.

image

The document states:

“To enable SignalR in your application, create a class called Startup with the following”

Step 9.

It shows a sample class called “Startup” and it says that you have to create it, but oh boy! I discovered, horrified, that it already exists!!

image

Step 10.

It’s there! Startup.cs. Let’s check it.

image

Step 11.

Not only it already exist, but it’s different from the one that the readme.txt shows.

image

And now, what?

EDIT:

Step 12.

Following Jose María’s directions, I replace the code in the Startup class with the one the readme.txt file.

So the class remains:

using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(ChorriApplication.Startup))] namespace ChorriApplication { public partial class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } } } 

 

Step 13.

After the change, I decide it’s time to run the application and I press F5 and this is what it’s shown!

image

Pretty good, uh? Open-mouthed smile It shows something, at least.

I close the browser window (Internet Explorer powah! Winking smile)

Step 14.

I’m trying to add a Hub class, since I have heard that hubs are like services that concurrently listen/send messages from clients.

I’m doing it via context menu, clicking over the project in the Solution Explorer.

image

A small dialog appears and I type my hub’s name.

image

Step 15.

Click on OK and a new class is created.

image

So, my Hub says hello? Well, and what can I do with that?

I think I’m done for today! I have no “clients” and NO IDEA of how to continue. I hope some colleague points out some new steps for me to follow.

But something is sure: whichever it is my way, I will show you Smile

ViewModels: make them right!

It’s not so simple to just make a class implement the INotifyPropertyChanged and create some properties.

Normally you have to REPRESENT a model. But how? Replicating the properties in the model that you want? Exposing the model itself using a property?

That is a good question that every MVVM lover should have asked himself when writhing a ViewModel.

You can take a look at this article. It really hits the nail on the head.

http://msdn.microsoft.com/en-us/magazine/ff798279.aspx

I normally expose the model directly and make UI classes that implement INotifyPropertyChanged. But I see the property mapping far more elegant and pure MVVMish 😉

What do you prefer?

DDD principles in a visual designer? Part 1

Yeah, boys, I’m crazy to think about applying DDD to an application like this, but I feel that being so purist has some great consequences to my designs, taking some benefits from this way of thinking  about development.

Domain-driven design, taking as it sounds, is to put the focus on the domain. Think about the domain and about how the model HAS TO BE. Let the rest flow as you need it. Everything should be subsidiary (although it will be important, too).   Take the true essence of the domain of it and make a model.

That model can be simple or incredibly complex, but you have a model and you can talk about it using concepts and relations that flow naturally from it. The model is self-contained and has to describe any substantial change of the domain it represents. You can talk about it as a whole!

That’s really cool.

But there are situations where the model is a bit strange. What if the model is not a common entity like a Person, a Bank Account or a Product? What if you have to deal with entities that are commonly attached to the UI, the layout or part of a document, like a Paragraph, a Rectangle, a Field…?