object ImportDefaultValue(TypeMapping mapping, string defaultValue) {
if (defaultValue == null)
return null;
if (!(mapping is PrimitiveMapping))
return DBNull.Value;
if (mapping is EnumMapping) {
EnumMapping em = (EnumMapping)mapping;
ConstantMapping[] c = em.Constants;
if (em.IsFlags) {
Hashtable values = new Hashtable();
string[] names = new string[c.Length];
long[] ids = new long[c.Length];
for (int i = 0; i < c.Length; i++) {
ids[i] = em.IsFlags ? 1L << i : (long)i;
names[i] = c[i].Name;
values.Add(c[i].XmlName, ids[i]);
}
// this validates the values
long val = XmlCustomFormatter.ToEnum(defaultValue, values, em.TypeName, true);
return XmlCustomFormatter.FromEnum(val, names, ids, em.TypeDesc.FullName);
}
else {
for (int i = 0; i < c.Length; i++) {
if (c[i].XmlName == defaultValue)
return c[i].Name;
}
}
throw new InvalidOperationException(Res.GetString(Res.XmlInvalidDefaultValue, defaultValue, em.TypeDesc.FullName));
}
// Primitive mapping
PrimitiveMapping pm = (PrimitiveMapping)mapping;
if (!pm.TypeDesc.HasCustomFormatter) {
if (pm.TypeDesc.FormatterName == "String")
return defaultValue;
if (pm.TypeDesc.FormatterName == "DateTime")
return XmlCustomFormatter.ToDateTime(defaultValue);
Type formatter = typeof(XmlConvert);
MethodInfo format = formatter.GetMethod("To" + pm.TypeDesc.FormatterName, new Type[] {typeof(string)});
if (format != null) {
return format.Invoke(formatter, new Object[] {defaultValue});
}
#if DEBUG
Debug.WriteLineIf(DiagnosticsSwitches.XmlSerialization.TraceVerbose, "XmlSerialization::Failed to GetMethod " + formatter.Name + ".To" + pm.TypeDesc.FormatterName);
#endif
}
else {
if (pm.TypeDesc.HasDefaultSupport) {
return XmlCustomFormatter.ToDefaultValue(defaultValue, pm.TypeDesc.FormatterName);
}
}
return DBNull.Value;
}