Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save JakeGinnivan/7267566 to your computer and use it in GitHub Desktop.

Select an option

Save JakeGinnivan/7267566 to your computer and use it in GitHub Desktop.
public class ViewModelPropertiesImplementNotifyPropertyChangedAndAreInUIProject : IConvention<Types>
{
public void Execute(Types data, IConventionResultContext result)
{
var notifyPropertyChanged = typeof(INotifyPropertyChanged);
var viewModelType = typeof(ViewModelBase);
var viewModels = data.TypesToVerify.Where(viewModelType.IsAssignableFrom);
var allPropertyTypes = GetPropertyTypes(viewModels, new List<Type>()).ToArray();
var failingData = allPropertyTypes.Where(t => !notifyPropertyChanged.IsAssignableFrom(t));
result.Is("Types which are publically exposed from ViewModel must inherit from INotifyPropertyChanged and live in the Toolbar.UI project",
failingData);
}
public string ConventionReason
{
get { return "This ensures that all properties off a viewmodel can be bound to and raise property changed notifications properly"; }
}
private IEnumerable<Type> GetPropertyTypes(IEnumerable<Type> typesToVerify, List<Type> knownTypes)
{
foreach (var type in typesToVerify)
{
var propertyTypes = type.GetProperties()
.Select(p =>
{
if (p.PropertyType.IsArray)
return p.PropertyType.GetElementType();
return p.PropertyType;
})
.Where(p => p.IsConcreteClass())
.Except(knownTypes)
.ToArray();
foreach (var propertyType in propertyTypes)
{
var ienumerable = propertyType.GetInterfaces().FirstOrDefault(t=>t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>));
if (ienumerable != null)
{
var ienumerableType = ienumerable.GetGenericArguments()[0];
if (ienumerableType.Namespace == null || !ienumerableType.Namespace.StartsWith("System"))
{
yield return ienumerableType;
}
}
else if (propertyType.Namespace == null || !propertyType.Namespace.StartsWith("System"))
{
yield return propertyType;
}
knownTypes.Add(propertyType);
}
foreach (var propertyType in GetPropertyTypes(propertyTypes, knownTypes))
{
knownTypes.Add(propertyType);
yield return propertyType;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment