I'm using the library XML-RPC.NET in C# to call an XML-RPC method on my server. The method returns a string when everything is ok, but when an error occurs it returns an XmlRpcStruct.
XML-RPC.NET threw an exception when I got a different return type than I specified in my method signature:
string login(string username, string password);
Exception message: "response contains struct value where string expected"
In the docs of XML-RPC.NET it says this:
"How do I specify data whose type is not known until runtime?
Sometimes the type of a parameter, return value, or struct member is not known until runtime. In this scenario the System.Object datatype should be used. For return values the actual type can be determined at runtime and handled appropriately."
So I changed my return type to object and now it works. However now I don't know how to handle the return value. If it's of type XmlRpcStruct I wan't to convert it to my Error class. Otherwise I treat it as a string. How do I convert it to my Error class? Does XML-RPC-NET have a convert method or something I can call?
public interface Proxy : IXmlRpcProxy
{
[XmlRpcMethod("login")]
object login(string username, string password);
}
// When the login method fails I get an XmlRpcStruct that has a
// key "status" with a string value. I'd like to cast the returned
// XmlRpcStruct to my Error class. How?
public class Error : XmlRpcStruct
{
public string status;
}
And then when I call the method:
object ret = proxy.login("admin", "1234");
Type t = ret.GetType();
if (t == typeof(XmlRpcStruct))
{
// This will set err to null even though ret is not null
// How do I convert it?
Error err = ret as Error;
}
else
{
string result = (string)ret;
}
Is there an easier method of doing this? I could just set my method to a return type of string and then do try/catch around the method-call, but then I lose the status message returned in the Error.
What if your Error class were to hold a XmlRpcStruct variable:
Then you can assign your XmlRpcStruct to the Error object's variable:
And you'll still have access to the original XmlRpcStruct through the Error class's variable without losing it to a try statement. There might be a better way to achieve this with inheritance, but this is a quick fix.