1 // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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
18 using System
.Collections
;
19 using System
.ComponentModel
;
20 using System
.Reflection
;
23 /// Converts all properties to strings.
25 [AttributeUsage(AttributeTargets
.Interface
| AttributeTargets
.Property
,
26 AllowMultiple
= false, Inherited
= true)]
27 public class DictionaryStringValuesAttribute
: Attribute
, IDictionaryPropertySetter
29 private string format
;
32 /// Gets or sets the format.
34 /// <value>The format.</value>
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
)
49 return GetPropertyAsString(property
.Property
, value);
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
);