Recognize TypeConverterAttributes on properties to override default getter semantics.
[castle.git] / Components / DictionaryAdapter / Castle.Components.DictionaryAdapter / Attributes / DictionaryStringValuesAttribute.cs
bloba0f65e6792d3826311fea90a85964f68b359dab9
1 // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle.Components.DictionaryAdapter
17 using System;
18 using System.Collections;
19 using System.ComponentModel;
20 using System.Reflection;
22 /// <summary>
23 /// Converts all properties to strings.
24 /// </summary>
25 [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Property,
26 AllowMultiple = false, Inherited = true)]
27 public class DictionaryStringValuesAttribute : Attribute, IDictionaryPropertySetter
29 private string format;
31 /// <summary>
32 /// Gets or sets the format.
33 /// </summary>
34 /// <value>The format.</value>
35 public string Format
37 get { return format; }
38 set { format = value; }
41 #region IDictionaryPropertySetter Members
43 object IDictionaryPropertySetter.SetPropertyValue(
44 IDictionaryAdapterFactory factory, IDictionary dictionary,
45 string key, object value, PropertyDescriptor property)
47 if (value != null)
49 return GetPropertyAsString(property.Property, value);
51 return value;
54 #endregion
56 private string GetPropertyAsString(PropertyInfo property, object value)
58 TypeConverter converter = GetTypeConverter(property);
59 if (converter != null)
61 if (converter.CanConvertTo(typeof(string)))
63 return (string) converter.ConvertTo(value, typeof(string));
67 if (!string.IsNullOrEmpty(format))
69 return String.Format(format, value);
71 return value.ToString();
74 private TypeConverter GetTypeConverter(PropertyInfo property)
76 Type converterType = AttributesUtil.GetTypeConverter(property);
77 if (converterType != null)
79 return (TypeConverter) Activator.CreateInstance(converterType);
81 return null;