view SilverlightValidation/SilverlightValidation.Tests/TestSupport/PropertySupport.cs @ 97:1adc1ae981ea

Tests added to SilverlightValidation.Tests
author stevenhollidge <stevenhollidge@hotmail.com>
date Sat, 05 May 2012 16:39:00 +0100
parents
children
line wrap: on
line source

using System;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;

namespace SilverlightValidation.Tests.TestSupport
{
    /// <summary>
    /// Utility class with property specific helper methods.
    /// </summary>
    public static class PropertySupport
    {
        [Conditional("DEBUG")]
        [DebuggerStepThrough]
        public static void VerifyPropertyName<T>(T model, string propertyName)
        {
            // A null or empty string indicates all properties on the object have changed
            if (!string.IsNullOrEmpty(propertyName))
            {
                var modelType = model.GetType();
                if (modelType.GetProperty(propertyName) == null)
                {
                    throw new ArgumentException(@"Property not found on target type", propertyName);
                }
            }
        }

        /// <summary>
        /// Extracts the name of a property from a suitable LambdaExpression.
        /// </summary>
        /// <param name="propertyExpression">The property expression.</param>
        /// <returns></returns>
        public static string ExtractPropertyName(LambdaExpression propertyExpression)
        {
            if (propertyExpression == null)
            {
                throw new ArgumentNullException("propertyExpression");
            }

            var memberExpression = propertyExpression.Body as MemberExpression;
            if (memberExpression == null)
            {
                throw new ArgumentException(@"Not a member expression", "propertyExpression");
            }

            var property = memberExpression.Member as PropertyInfo;
            if (property == null)
            {
                throw new ArgumentException(@"Not a property", "propertyExpression");
            }

            var getMethod = property.GetGetMethod(true);
            if (getMethod.IsStatic)
            {
                throw new ArgumentException(@"Can't be static", "propertyExpression");
            }

            return memberExpression.Member.Name;
        }
    }
}