I’m working on a feature which allows you make configuration changes to List instances on feature activation. The exact configuration is provided to the feature via feature properties and I wanted to be able to set property values on the SPList instance dynamically using reflection.
Here’s the code which does that;
private static bool SetListProperty(SPList list, string propertyName, string propertyValue) { if (list == null) throw new ArgumentNullException("list"); if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName"); var t = list.GetType(); if (t == null) throw new Exception("Invalid reflection object"); var pi = t.GetProperty(propertyName); if (pi == null) throw new Exception("Invalid property: " + propertyName); if (!pi.CanWrite) throw new NotSupportedException("Property " + propertyName + " is Read Only!"); try { var ovalue = Convert.ChangeType(propertyValue, pi.PropertyType); pi.SetValue(list, ovalue, null); } catch(Exception ex) { throw new Exception(string.Format("Unable to set property: {0} to: {1}", propertyName, propertyValue), ex); } return true; }
Published by