Advertisement
Guest User

InputMapper

a guest
Sep 21st, 2010
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.90 KB | None | 0 0
  1.  
  2. public class InputMapper<TSource>
  3. {
  4.     private List<InputMapping> mappings = new List<InputMapping>();
  5.  
  6.     public void Map<TProperty>(object input, Expression<Func<TSource, TProperty>> projection, string errorMessage)
  7.     {
  8.         mappings.Add(new InputMapping<TSource, TProperty>
  9.         {
  10.             Input = input,
  11.             Projection = projection,
  12.             ErrorMessage = errorMessage
  13.         });
  14.     }
  15.  
  16.     public TSource Create()
  17.     {
  18.         var instance = Activator.CreateInstance<TSource>();
  19.  
  20.         foreach (var mapping in mappings)
  21.         {
  22.             if (!mapping.Apply(instance))
  23.             {
  24.                 throw new Exception(mapping.ErrorMessage);
  25.             }
  26.         }
  27.        
  28.         return instance;
  29.     }
  30. }
  31.  
  32. abstract class InputMapping
  33. {
  34.     public object Input { get; set; }      
  35.     public string ErrorMessage { get; set; }
  36.    
  37.     public abstract bool Apply(object target);
  38. }
  39.  
  40. class InputMapping<TSource, TProperty> : InputMapping
  41. {
  42.     public Expression<Func<TSource, TProperty>> Projection { get; set; }
  43.    
  44.     public override bool Apply(object target)
  45.     {
  46.         if (!target.GetType().Equals(typeof(TSource)))
  47.         {
  48.             return false;
  49.         }
  50.        
  51.         var lambda = Projection as LambdaExpression;
  52.         if (lambda == null)
  53.         {
  54.             return false;
  55.         }
  56.        
  57.         MemberExpression exp = lambda.Body as MemberExpression;
  58.         if (exp == null)
  59.         {
  60.             return false;
  61.         }
  62.        
  63.         PropertyInfo prop = exp.Member as PropertyInfo;
  64.         if (prop == null)
  65.         {
  66.             return false;
  67.         }
  68.        
  69.         if (!prop.CanWrite || prop.GetIndexParameters().Length > 0)
  70.         {
  71.             return false;
  72.         }
  73.        
  74.         prop.SetValue(target, Convert.ChangeType(Input, typeof(TProperty)), null);
  75.        
  76.         return true;
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement