Some time ago I faced with unclear problem: when I tried to add value to the SPWeb property bag like this:
SetProperty method is just wrapper over AllProperties collection which may be more familiar to developers:
As you can see in the code above boolean values are added to the property bag. Surprisingly this code caused type mismatch exception during web.Update() call:
Specified data type does not match the current data type of the property.
at Microsoft.SharePoint.Utilities.SPUtility.UpdateArrayFromHashtable(Object& o, Hashtable ht)
What was even more interesting, is that only one boolean value caused this error (e.g. “Foo” on the example above), i.e. when I commented this single line, code became working having other boolean variables stored into the property bag.
I checked SPUtility.UpdateArrayFromHashtable() method in reflector. It is not the clearest method I saw in my experience. Let’s try to investigate what it actually does. According to its name it updates array of properties (2 dimensional) from Hashtable which stores local copies, i.e. properties which are not saved to content database yet. Lets check how it is called from SPWeb.Update() method:
Type mismatch exception is thrown from the following part of the UpdateArrayFromHashtable() method:
ObjectType has Type type (i.e. array of types) which is initialized in static constructor of SPUtility class:
As you can see “type” variable in the code above contains type of the current property (current loop step property) from Hashtable which as you remember contains list of local unsaved copies. I.e. in our case it contains bool type.
Another interesting variable is “num5”. It contains index in ObjectType array (i.e. values from interval [0..3]) for the property type. Important that if Hashtable contains property with the same name which already exists in the properties array, num5 will contain index for type of this existing property. Check lines 9-13 above:
(hastable variable here is just converted array of existing properties). Let’s return to the code which throws exception. Lines 28-29 shows us that num5 contains value 1,2 or 3 (i.e. that previous type of property was string, int or DateTime) and that current type is not the same which was before update:
But how property with the same name but different type came to the property bag? When I asked colleagues about it I found that previously for workaround of another problem this property was added to the property bag via PowerShell:
As you can see it was added using string. Code which reads this property may work both with strings and booleans (property bag returns instance of object type), that’s why it was not mentioned before. But when we tried to update it using boolean value it failed with type mismatch exception.
In order to fix it, just remove old property from the property bag:
After that code which adds boolean values into property bag will work.