Converting Int32 to DTS.DTSPackagePriorityClass

  • Thread starter Thread starter Keith Patrick
  • Start date Start date
K

Keith Patrick

I have some generic .Net objects that I want to use to populate some
DTS-based COM objects. To keep things clean and simply, I have added
attributes to map the properties between each other rather than set each
property manually. However, I get invalid type errors when I hit some of
the COM enumerations, like DTS.DTSPackagePriorityClass. Is there some way
to dynamically do:

DTS.DTSPackagePriorityClass targVal = (DTS.DTSPackagePriorityClass) 2;


I tried Convert.ChangeType, but it won't work, because apparently,
DTSPackagePriorityClass does not implement IConvertible. I even tried this
(not exactly, as my code is much more generic), but it is syntactially
incorrect:
Int32 sourceVal = 2;
DTS.DTSPackagePriorityClass targVal = sourceVal as targVal.GetType();
 
I stand corrected: DTSPackagePriorityClass *is* IConvertible (and a regular,
static cast works), but it just seems to have some problem with dynamically
casting
 
Found a workaround of some type. Basically, I can try to Convert.ChangeType
first, in case it *can* convert. My catch clause then handles this
particular type of occurrence by statically casting the variable to Enum.
If it isn't an example of this scenario, then another ICE gets thrown,
correctly. Otherwise, I now have an Enum (Big thanks to MS for providng
Enum and Array classes!), which doesn't have the problem in ChangeType that
Int32 has. So basically, I have a fallback where I convert to an
intermediate type that is more compatible with the COM enumerations.
 
For reference, here is the code:

private DTS.IDTSStdObject PopulateComObject(DTS.IDTSStdObject comObject,
XmlBasedItem item) {
foreach (PropertyInfo property in item.GetType().GetProperties()) {
foreach (ConfigurationPropertyAttribute attribute in
property.GetCustomAttributes(typeof(ConfigurationPropertyAttribute),true)) {
if ((attribute.ComPropertyName != null) &&
(attribute.ComPropertyName.Length > 0)) {
Object sourceValue = property.GetValue(item,null);
Object targetValue = null;
PropertyInfo targetProperty =
comObject.GetType().GetProperty(attribute.ComPropertyName);
try {
targetValue =
Convert.ChangeType(sourceValue,targetProperty.PropertyType);
}
catch (InvalidCastException) {
// One quick try of converting to an Enum, since a lot of
COM stuff uses
// them, and Convert.ChangeType does not handle this for
some reason.
targetValue =
Enum.Parse(targetProperty.PropertyType,sourceValue.ToString());
}
targetProperty.SetValue(comObject,targetValue,null);
}
}
}
return comObject;
}
 
Back
Top