|
1 /* |
|
2 * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). |
|
3 * All rights reserved. |
|
4 * This component and the accompanying materials are made available |
|
5 * under the terms of "Eclipse Public License v1.0" |
|
6 * which accompanies this distribution, and is available |
|
7 * at the URL "http://www.eclipse.org/legal/epl-v10.html". |
|
8 * |
|
9 * Initial Contributors: |
|
10 * Nokia Corporation - initial contribution. |
|
11 * |
|
12 * Contributors: |
|
13 * |
|
14 * Description: |
|
15 * |
|
16 */ |
|
17 using System; |
|
18 using System.Xml; |
|
19 using System.Text; |
|
20 using System.IO; |
|
21 using System.ComponentModel; |
|
22 using System.Collections.Generic; |
|
23 |
|
24 namespace SymbianUtils.Settings |
|
25 { |
|
26 internal static class XmlSettingsValueConverter<T> |
|
27 { |
|
28 public static T Convert( XmlSettingsValue aValue, T aDefault ) |
|
29 { |
|
30 bool defaultApplied = false; |
|
31 return Convert( aValue, aDefault, out defaultApplied ); |
|
32 } |
|
33 |
|
34 public static T Convert( XmlSettingsValue aValue, T aDefault, out bool aDefaultApplied ) |
|
35 { |
|
36 T ret = aDefault; |
|
37 aDefaultApplied = true; |
|
38 // |
|
39 Type srcType = aValue.Value.GetType(); |
|
40 Type destType = aDefault.GetType(); |
|
41 // |
|
42 try |
|
43 { |
|
44 // Don't need to convert if source and destination types are |
|
45 // identical. |
|
46 if ( srcType == destType ) |
|
47 { |
|
48 ret = (T) aValue.Value; |
|
49 } |
|
50 else |
|
51 { |
|
52 // Don't try to convert empty strings. |
|
53 if ( aValue.Value is string && destType != typeof( string ) ) |
|
54 { |
|
55 string val = ( (string) aValue.Value ).Trim(); |
|
56 if ( val == string.Empty ) |
|
57 { |
|
58 return aDefault; |
|
59 } |
|
60 } |
|
61 |
|
62 // Try the type converter instead |
|
63 TypeConverter converter = TypeDescriptor.GetConverter( destType ); |
|
64 if ( converter.CanConvertFrom( srcType ) ) |
|
65 { |
|
66 if ( aValue.Value is string ) |
|
67 { |
|
68 string text = (string) aValue.Value; |
|
69 ret = (T) converter.ConvertFromInvariantString( text ); |
|
70 } |
|
71 else |
|
72 { |
|
73 ret = (T) converter.ConvertFrom( aValue.Value ); |
|
74 } |
|
75 aDefaultApplied = false; |
|
76 } |
|
77 else |
|
78 { |
|
79 SymbianUtils.SymDebug.SymDebugger.Break(); |
|
80 } |
|
81 } |
|
82 } |
|
83 catch ( System.FormatException ) |
|
84 { |
|
85 SymbianUtils.SymDebug.SymDebugger.Break(); |
|
86 } |
|
87 // |
|
88 return ret; |
|
89 } |
|
90 } |
|
91 } |
|
92 |
|
93 |