Topic: Error - TargetInvocationException
Description: TargetInvocationException can be thrown when trying to deserialize a property that is a double or single datatype when using the SerializationInfo object on a Serialized object.
Notes: This is the following set up
1. Remoting is used between the Web Server and a remoting server
2. An Object/DomainObject/Model has a property of type double or single
3. The middle-tier (Remoting Server) sets the value of the double or single datatype property.
4. The Web Server, deserializes the object and causes a TargetInvocationException to be thrown.
1. Let's assume you have an object that is being returned to the Web Server from the middle-tier in a remoting call. Any Object, just make an object that is serializable and has a property of type Double or Single.
[
Serializable()]
public
class MySampleClass : System.Runtime.Serialization.ISerializable
{
private double _MyDoubleProperty;
public MySampleClass()
{
_MyDoubleProperty = Double.MinValue;
}
public MySampleClass(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
_MyDoubleProperty = Double.MinValue;
// default (current version) serialization follows
_MyDoubleProperty = info.GetDouble("_MyDoubleProperty")
return;
}
public bool MyDoubleProperty
{
get
{
return _MyDoubleProperty;
}
set
{
_MyDoubleProperty= value;
}
}
}
2. In the middle-tier (Remote Server), populate the property. But the catch is, do a divide by zero on the Single or Double datatype.
double numerator = 15;
double denominator = 0;
MySampleClass myClass = new MySampleClass();
myClass.MyDoubleProperty = numerator / denominator;
What you'll notice is that when you have a Double or Single datatype, you will actually get the "Infinity" Value assigned to the datatype. There are numerous articles on this and is not the main topic of this article, so we'll move on.
Well, later when the object gets sent back to the Web Server, it will cause a Deserialization error if you are using the SerializationInfo property.
The whole thing is caused by the the fact that when Deserializing using the SerializationInfo object, the GetDouble method does not interpret the "Infinity" value properly.
To get around this, make sure in the middle-tier whenever you are attempting to divide by zero, put a check in there to ensure that you do not get the "Infinity" value.
Example:
double numerator = 15;
double denominator = 0;
MySampleClass myClass = new MySampleClass();
if ( denominator != 0 )
{
myClass.MyDoubleProperty = numerator / denominator;
}