Simplifying properties???

Simplifying properties???

Old forum URL: forums.lhotka.net/forums/t/7088.aspx


boo posted on Thursday, June 11, 2009

[Serializable] public class TestObj : BusinessBase<TestObj> { [CslaProperty(DefaultValue=-1)] public int Id { get { return GetPropertyHelper<int>("Id"); } set { SetPropertyHelper("Id", value); } } protected override void AddBusinessRules() { RegisterProperties(); // TODO: add validation rules //ValidationRules.AddRule(RuleMethod, ""); ValidationRules.AddRule<TestObj>(IsIdValid, registeredProperties["Id"]); } private static bool IsIdValid<T>(T target, RuleArgs e) where T : TestObj { e.Description = "Id is not valid"; return false; } private static Dictionary<string, PropertyInfo<object>> registeredProperties = new Dictionary<string,PropertyInfo<object>>(); private T GetPropertyHelper<T>(string name) { return (T)GetProperty(registeredProperties[name]); } private void SetPropertyHelper(string name, object value) { SetProperty(registeredProperties[name], value); } private TestObj() { /* Require use of factory methods */ RegisterProperties(); } private static bool registered = false; private void RegisterProperties() { if (!registered) { Type t = this.GetType(); var bindableProperties = from p in t.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) where p.GetCustomAttributes(typeof(CslaPropertyAttribute), false).Length == 1 select p; bindableProperties.ToList().ForEach(p => { PropertyInfo<object> info; if (((CslaPropertyAttribute)p.GetCustomAttributes(typeof(CslaPropertyAttribute), false)[0]).DefaultValue != null) { info = RegisterProperty(new PropertyInfo<object>(p.Name, p.Name, ((CslaPropertyAttribute)p.GetCustomAttributes(typeof(CslaPropertyAttribute), false)[0]).DefaultValue)); } else { info = RegisterProperty(new PropertyInfo<object>(p.Name)); } registeredProperties.Add(p.Name, info); }); registered = true; } } }

Copyright (c) Marimer LLC