1 // Copyright 2004-2008 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
.MicroKernel
.SubSystems
.Conversion
18 using System
.Collections
;
20 using Castle
.Core
.Configuration
;
23 public class DictionaryConverter
: AbstractTypeConverter
25 public override bool CanHandleType(Type type
)
27 return (type
== typeof(IDictionary
) || type
== typeof(Hashtable
));
30 public override object PerformConversion(String
value, Type targetType
)
32 throw new NotImplementedException();
35 public override object PerformConversion(IConfiguration configuration
, Type targetType
)
37 System
.Diagnostics
.Debug
.Assert( targetType
== typeof(IDictionary
) || targetType
== typeof(Hashtable
) );
39 Hashtable dict
= new Hashtable();
41 String keyTypeName
= configuration
.Attributes
["keyType"];
42 Type defaultKeyType
= typeof(String
);
44 String valueTypeName
= configuration
.Attributes
["valueType"];
45 Type defaultValueType
= typeof(String
);
47 if (keyTypeName
!= null)
49 defaultKeyType
= (Type
) Context
.Composition
.PerformConversion( keyTypeName
, typeof(Type
) );
51 if (valueTypeName
!= null)
53 defaultValueType
= (Type
) Context
.Composition
.PerformConversion( valueTypeName
, typeof(Type
) );
56 foreach(IConfiguration itemConfig
in configuration
.Children
)
60 String keyValue
= itemConfig
.Attributes
["key"];
64 throw new ConverterException("You must provide a key for the dictionary entry");
67 Type convertKeyTo
= defaultKeyType
;
69 if (itemConfig
.Attributes
["keyType"] != null)
71 convertKeyTo
= (Type
) Context
.Composition
.PerformConversion(
72 itemConfig
.Attributes
["keyType"], typeof(Type
) );
75 object key
= Context
.Composition
.PerformConversion(keyValue
, convertKeyTo
);
77 // Preparing the value
79 Type convertValueTo
= defaultValueType
;
81 if (itemConfig
.Attributes
["valueType"] != null)
83 convertValueTo
= (Type
) Context
.Composition
.PerformConversion(
84 itemConfig
.Attributes
["valueType"], typeof(Type
) );
89 if (itemConfig
.Children
.Count
== 0)
91 value = Context
.Composition
.PerformConversion(
92 itemConfig
, convertValueTo
);
96 value = Context
.Composition
.PerformConversion(
97 itemConfig
.Children
[0], convertValueTo
);
100 dict
.Add( key
, value );