diff --git a/src/IXmlRpcProxy.cs b/src/IXmlRpcProxy.cs index 120234b..0fb3c6c 100644 --- a/src/IXmlRpcProxy.cs +++ b/src/IXmlRpcProxy.cs @@ -25,98 +25,99 @@ DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; -using System.Collections; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Text; namespace CookComputing.XmlRpc { - public interface IXmlRpcProxy - { - bool AllowAutoRedirect { get; set; } + public interface IXmlRpcProxy + { + bool AllowAutoRedirect { get; set; } - void AttachLogger(XmlRpcLogger logger); + void AttachLogger(XmlRpcLogger logger); #if (!COMPACT_FRAMEWORK && !SILVERLIGHT && !SILVERLIGHT) - X509CertificateCollection ClientCertificates { get; } + X509CertificateCollection ClientCertificates { get; } #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) - string ConnectionGroupName { get; set; } + string ConnectionGroupName { get; set; } #endif - CookieContainer CookieContainer { get; } + CookieContainer CookieContainer { get; } - [Browsable(false)] - ICredentials Credentials { get; set; } + [Browsable(false)] + ICredentials Credentials { get; set; } #if (!COMPACT_FRAMEWORK && !FX1_0 && !SILVERLIGHT) - bool EnableCompression { get; set;} + bool EnableCompression { get; set; } - bool Expect100Continue { get; set; } + bool Expect100Continue { get; set; } - bool UseNagleAlgorithm { get; set; } + bool UseNagleAlgorithm { get; set; } #endif - [Browsable(false)] - WebHeaderCollection Headers { get; } + [Browsable(false)] + WebHeaderCollection Headers { get; } - Guid Id { get; } + Guid Id { get; } - int Indentation { get; set; } + int Indentation { get; set; } - bool KeepAlive { get; set; } + bool KeepAlive { get; set; } - XmlRpcNonStandard NonStandard { get; set; } + XmlRpcNonStandard NonStandard { get; set; } - bool PreAuthenticate { get; set; } + bool PreAuthenticate { get; set; } #if (!SILVERLIGHT) - [Browsable(false)] - System.Version ProtocolVersion { get; set; } + [Browsable(false)] + System.Version ProtocolVersion { get; set; } #endif #if (!SILVERLIGHT) - [Browsable(false)] - IWebProxy Proxy { get; set; } + [Browsable(false)] + IWebProxy Proxy { get; set; } #endif - [Browsable(false)] - CookieCollection ResponseCookies { get; } + [Browsable(false)] + CookieCollection ResponseCookies { get; } - [Browsable(false)] - WebHeaderCollection ResponseHeaders { get; } + [Browsable(false)] + WebHeaderCollection ResponseHeaders { get; } - int Timeout { get; set; } + int Timeout { get; set; } - string Url { get; set; } + string Url { get; set; } - bool UseEmptyElementTags { get; set; } + bool UseEmptyElementTags { get; set; } - bool UseEmptyParamsTag { get; set; } + bool UseEmptyParamsTag { get; set; } - bool UseIndentation { get; set; } + bool UseIndentation { get; set; } - bool UseIntTag { get; set; } + bool UseIntTag { get; set; } - bool UseStringTag { get; set; } + bool UseStringTag { get; set; } - string UserAgent { get; set; } + string UserAgent { get; set; } - [Browsable(false)] - Encoding XmlEncoding { get; set; } + [Browsable(false)] + Encoding XmlEncoding { get; set; } - string XmlRpcMethod { get; set; } + string XmlRpcMethod { get; set; } - // introspecton methods - string[] SystemListMethods(); - object[] SystemMethodSignature(string MethodName); - string SystemMethodHelp(string MethodName); + string DateTimeFormat { get; set; } - // events - event XmlRpcRequestEventHandler RequestEvent; - event XmlRpcResponseEventHandler ResponseEvent; + // introspecton methods + string[] SystemListMethods(); + object[] SystemMethodSignature(string MethodName); + string SystemMethodHelp(string MethodName); - } + // events + event XmlRpcRequestEventHandler RequestEvent; + event XmlRpcResponseEventHandler ResponseEvent; + + } } diff --git a/src/XmlRpcClientProtocol.cs b/src/XmlRpcClientProtocol.cs index 4fc678e..987626d 100644 --- a/src/XmlRpcClientProtocol.cs +++ b/src/XmlRpcClientProtocol.cs @@ -25,8 +25,6 @@ DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; -using System.Collections; -using System.Diagnostics; using System.IO; using System.Net; using System.Reflection; @@ -35,968 +33,974 @@ DEALINGS IN THE SOFTWARE. namespace CookComputing.XmlRpc { - public class XmlRpcClientProtocol : + public class XmlRpcClientProtocol : #if (!SILVERLIGHT) Component, #endif IXmlRpcProxy - { - WebSettings webSettings = new WebSettings(); - XmlRpcFormatSettings XmlRpcFormatSettings = new XmlRpcFormatSettings(); + { + WebSettings webSettings = new WebSettings(); + XmlRpcFormatSettings XmlRpcFormatSettings = new XmlRpcFormatSettings(); - private CookieCollection _responseCookies; - private WebHeaderCollection _responseHeaders; - private XmlRpcNonStandard _nonStandard; - private string _url = null; - private string _xmlRpcMethod = null; + private CookieCollection _responseCookies; + private WebHeaderCollection _responseHeaders; + private XmlRpcNonStandard _nonStandard; + private string _url = null; + private string _xmlRpcMethod = null; - private Guid _id = Util.NewGuid(); + private Guid _id = Util.NewGuid(); - static XmlRpcClientProtocol() - { + static XmlRpcClientProtocol() + { #if (SILVERLIGHT) WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp); WebRequest.RegisterPrefix("https://", System.Net.Browser.WebRequestCreator.ClientHttp); #endif - } + } #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) - public XmlRpcClientProtocol(System.ComponentModel.IContainer container) - { - container.Add(this); - InitializeComponent(); - } + public XmlRpcClientProtocol(System.ComponentModel.IContainer container) + { + container.Add(this); + InitializeComponent(); + } #endif - public XmlRpcClientProtocol() - { - InitializeComponent(); - } + public XmlRpcClientProtocol() + { + InitializeComponent(); + } - public object Invoke( - MethodBase mb, - params object[] Parameters) - { - return Invoke(this, mb as MethodInfo, Parameters); - } + public object Invoke( + MethodBase mb, + params object[] Parameters) + { + return Invoke(this, mb as MethodInfo, Parameters); + } - public object Invoke( - MethodInfo mi, - params object[] Parameters) - { - return Invoke(this, mi, Parameters); - } + public object Invoke( + MethodInfo mi, + params object[] Parameters) + { + return Invoke(this, mi, Parameters); + } - public object Invoke( - string MethodName, - params object[] Parameters) - { - return Invoke(this, MethodName, Parameters); - } + public object Invoke( + string MethodName, + params object[] Parameters) + { + return Invoke(this, MethodName, Parameters); + } - public object Invoke( - Object clientObj, - string methodName, - params object[] parameters) - { - MethodInfo mi = GetMethodInfoFromName(clientObj, methodName, parameters); - return Invoke(this, mi, parameters); - } + public object Invoke( + Object clientObj, + string methodName, + params object[] parameters) + { + MethodInfo mi = GetMethodInfoFromName(clientObj, methodName, parameters); + return Invoke(this, mi, parameters); + } - public object Invoke( - Object clientObj, - MethodInfo mi, - params object[] parameters) - { + public object Invoke( + Object clientObj, + MethodInfo mi, + params object[] parameters) + { #if (SILVERLIGHT) throw new NotSupportedException(); #else - _responseHeaders = null; - _responseCookies = null; - WebRequest webReq = null; - object reto = null; - try - { - string useUrl = GetEffectiveUrl(clientObj); - webReq = GetWebRequest(new Uri(useUrl)); - XmlRpcRequest req = MakeXmlRpcRequest(webReq, mi, parameters, - clientObj, _xmlRpcMethod, _id); - SetProperties(webReq); - SetRequestHeaders(Headers, webReq); + _responseHeaders = null; + _responseCookies = null; + WebRequest webReq = null; + object reto = null; + try + { + string useUrl = GetEffectiveUrl(clientObj); + webReq = GetWebRequest(new Uri(useUrl)); + XmlRpcRequest req = MakeXmlRpcRequest(webReq, mi, parameters, + clientObj, _xmlRpcMethod, _id); + SetProperties(webReq); + SetRequestHeaders(Headers, webReq); #if (!COMPACT_FRAMEWORK) - SetClientCertificates(ClientCertificates, webReq); + SetClientCertificates(ClientCertificates, webReq); #endif - Stream serStream = null; - Stream reqStream = null; - bool logging = (RequestEvent != null); - if (!logging) - serStream = reqStream = webReq.GetRequestStream(); - else - serStream = new MemoryStream(2000); - try - { - var serializer = new XmlRpcRequestSerializer(XmlRpcFormatSettings); - serializer.SerializeRequest(serStream, req); - if (logging) - { - reqStream = webReq.GetRequestStream(); - serStream.Position = 0; - Util.CopyStream(serStream, reqStream); - reqStream.Flush(); - serStream.Position = 0; - OnRequest(new XmlRpcRequestEventArgs(req.proxyId, req.number, - serStream)); - } - } - finally - { - if (reqStream != null) - reqStream.Close(); - } - HttpWebResponse webResp = GetWebResponse(webReq) as HttpWebResponse; - _responseCookies = webResp.Cookies; - _responseHeaders = webResp.Headers; - Stream respStm = null; - Stream deserStream; - logging = (ResponseEvent != null); - try - { - respStm = webResp.GetResponseStream(); + Stream serStream = null; + Stream reqStream = null; + bool logging = (RequestEvent != null); + if (!logging) + serStream = reqStream = webReq.GetRequestStream(); + else + serStream = new MemoryStream(2000); + try + { + var serializer = new XmlRpcRequestSerializer(XmlRpcFormatSettings); + serializer.SerializeRequest(serStream, req); + if (logging) + { + reqStream = webReq.GetRequestStream(); + serStream.Position = 0; + Util.CopyStream(serStream, reqStream); + reqStream.Flush(); + serStream.Position = 0; + OnRequest(new XmlRpcRequestEventArgs(req.proxyId, req.number, + serStream)); + } + } + finally + { + if (reqStream != null) + reqStream.Close(); + } + HttpWebResponse webResp = GetWebResponse(webReq) as HttpWebResponse; + _responseCookies = webResp.Cookies; + _responseHeaders = webResp.Headers; + Stream respStm = null; + Stream deserStream; + logging = (ResponseEvent != null); + try + { + respStm = webResp.GetResponseStream(); #if (!COMPACT_FRAMEWORK && !FX1_0) - respStm = MaybeDecompressStream((HttpWebResponse)webResp, - respStm); + respStm = MaybeDecompressStream((HttpWebResponse)webResp, + respStm); #endif - if (!logging) - { - deserStream = respStm; - } - else - { - deserStream = new MemoryStream(2000); - Util.CopyStream(respStm, deserStream); - deserStream.Flush(); - deserStream.Position = 0; - } - if (logging) - { - OnResponse(new XmlRpcResponseEventArgs(req.proxyId, req.number, - deserStream)); - deserStream.Position = 0; - } - XmlRpcResponse resp = ReadResponse(req, webResp, deserStream); - reto = resp.retVal; - } - finally - { - if (respStm != null) - respStm.Close(); - } - } - finally - { - if (webReq != null) - webReq = null; - } - return reto; + if (!logging) + { + deserStream = respStm; + } + else + { + deserStream = new MemoryStream(2000); + Util.CopyStream(respStm, deserStream); + deserStream.Flush(); + deserStream.Position = 0; + } + if (logging) + { + OnResponse(new XmlRpcResponseEventArgs(req.proxyId, req.number, + deserStream)); + deserStream.Position = 0; + } + XmlRpcResponse resp = ReadResponse(req, webResp, deserStream); + reto = resp.retVal; + } + finally + { + if (respStm != null) + respStm.Close(); + } + } + finally + { + if (webReq != null) + webReq = null; + } + return reto; #endif - } + } - public bool AllowAutoRedirect - { - get { return webSettings.AllowAutoRedirect; } - set { webSettings.AllowAutoRedirect = value; } - } + public bool AllowAutoRedirect + { + get { return webSettings.AllowAutoRedirect; } + set { webSettings.AllowAutoRedirect = value; } + } #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) - [Browsable(false)] - public X509CertificateCollection ClientCertificates - { - get { return webSettings.ClientCertificates; } - } + [Browsable(false)] + public X509CertificateCollection ClientCertificates + { + get { return webSettings.ClientCertificates; } + } #endif #if (!COMPACT_FRAMEWORK) - public string ConnectionGroupName - { - get { return webSettings.ConnectionGroupName; } - set { webSettings.ConnectionGroupName = value; } - } + public string ConnectionGroupName + { + get { return webSettings.ConnectionGroupName; } + set { webSettings.ConnectionGroupName = value; } + } #endif - [Browsable(false)] - public ICredentials Credentials - { - get { return webSettings.Credentials; } - set { webSettings.Credentials = value; } - } + [Browsable(false)] + public ICredentials Credentials + { + get { return webSettings.Credentials; } + set { webSettings.Credentials = value; } + } #if (!COMPACT_FRAMEWORK && !FX1_0) - public bool EnableCompression - { - get { return webSettings.EnableCompression; } - set { webSettings.EnableCompression = value; } - } + public bool EnableCompression + { + get { return webSettings.EnableCompression; } + set { webSettings.EnableCompression = value; } + } #endif - [Browsable(false)] - public WebHeaderCollection Headers - { - get { return webSettings.Headers; } - } + [Browsable(false)] + public WebHeaderCollection Headers + { + get { return webSettings.Headers; } + } #if (!COMPACT_FRAMEWORK && !FX1_0 && !SILVERLIGHT) - public bool Expect100Continue - { - get { return webSettings.Expect100Continue; } - set { webSettings.Expect100Continue = value; } - } + public bool Expect100Continue + { + get { return webSettings.Expect100Continue; } + set { webSettings.Expect100Continue = value; } + } - public bool UseNagleAlgorithm - { - get { return webSettings.UseNagleAlgorithm; } - set { webSettings.UseNagleAlgorithm = value; } - } + public bool UseNagleAlgorithm + { + get { return webSettings.UseNagleAlgorithm; } + set { webSettings.UseNagleAlgorithm = value; } + } #endif - public CookieContainer CookieContainer - { - get { return webSettings.CookieContainer; } - } + public CookieContainer CookieContainer + { + get { return webSettings.CookieContainer; } + } - public Guid Id - { - get { return _id; } - } + public Guid Id + { + get { return _id; } + } - public int Indentation - { - get { return XmlRpcFormatSettings.Indentation; } - set { XmlRpcFormatSettings.Indentation = value; } - } + public int Indentation + { + get { return XmlRpcFormatSettings.Indentation; } + set { XmlRpcFormatSettings.Indentation = value; } + } - public bool KeepAlive - { - get { return webSettings.KeepAlive; } - set { webSettings.KeepAlive = value; } - } + public bool KeepAlive + { + get { return webSettings.KeepAlive; } + set { webSettings.KeepAlive = value; } + } - public XmlRpcNonStandard NonStandard - { - get { return _nonStandard; } - set { _nonStandard = value; } - } + public XmlRpcNonStandard NonStandard + { + get { return _nonStandard; } + set { _nonStandard = value; } + } - public bool PreAuthenticate - { - get { return webSettings.PreAuthenticate; } - set { webSettings.PreAuthenticate = value; } - } + public bool PreAuthenticate + { + get { return webSettings.PreAuthenticate; } + set { webSettings.PreAuthenticate = value; } + } #if (!SILVERLIGHT) - [Browsable(false)] - public System.Version ProtocolVersion - { - get { return webSettings.ProtocolVersion; } - set { webSettings.ProtocolVersion = value; } - } + [Browsable(false)] + public System.Version ProtocolVersion + { + get { return webSettings.ProtocolVersion; } + set { webSettings.ProtocolVersion = value; } + } #endif #if (!SILVERLIGHT) - [Browsable(false)] - public IWebProxy Proxy - { - get { return webSettings.Proxy; } - set { webSettings.Proxy = value; } - } + [Browsable(false)] + public IWebProxy Proxy + { + get { return webSettings.Proxy; } + set { webSettings.Proxy = value; } + } #endif - public CookieCollection ResponseCookies - { - get { return _responseCookies; } - } + public CookieCollection ResponseCookies + { + get { return _responseCookies; } + } - public WebHeaderCollection ResponseHeaders - { - get { return _responseHeaders; } - } + public WebHeaderCollection ResponseHeaders + { + get { return _responseHeaders; } + } - public int Timeout - { - get { return webSettings.Timeout; } - set { webSettings.Timeout = value; } - } + public int Timeout + { + get { return webSettings.Timeout; } + set { webSettings.Timeout = value; } + } - public string Url - { - get { return _url; } - set { _url = value; } - } + public string Url + { + get { return _url; } + set { _url = value; } + } - public bool UseEmptyElementTags - { - get { return XmlRpcFormatSettings.UseEmptyElementTags; } - set { XmlRpcFormatSettings.UseEmptyElementTags = value; } - } + public bool UseEmptyElementTags + { + get { return XmlRpcFormatSettings.UseEmptyElementTags; } + set { XmlRpcFormatSettings.UseEmptyElementTags = value; } + } - public bool UseEmptyParamsTag - { - get { return XmlRpcFormatSettings.UseEmptyParamsTag; } - set { XmlRpcFormatSettings.UseEmptyParamsTag = value; } - } + public bool UseEmptyParamsTag + { + get { return XmlRpcFormatSettings.UseEmptyParamsTag; } + set { XmlRpcFormatSettings.UseEmptyParamsTag = value; } + } - public bool UseIndentation - { - get { return XmlRpcFormatSettings.UseIndentation; } - set { XmlRpcFormatSettings.UseIndentation = value; } - } + public bool UseIndentation + { + get { return XmlRpcFormatSettings.UseIndentation; } + set { XmlRpcFormatSettings.UseIndentation = value; } + } - public bool UseIntTag - { - get { return XmlRpcFormatSettings.UseIntTag; } - set { XmlRpcFormatSettings.UseIntTag = value; } - } + public bool UseIntTag + { + get { return XmlRpcFormatSettings.UseIntTag; } + set { XmlRpcFormatSettings.UseIntTag = value; } + } - public string UserAgent - { - get { return webSettings.UserAgent; } - set { webSettings.UserAgent = value; } - } + public string UserAgent + { + get { return webSettings.UserAgent; } + set { webSettings.UserAgent = value; } + } - public bool UseStringTag - { - get { return XmlRpcFormatSettings.UseStringTag; } - set { XmlRpcFormatSettings.UseStringTag = value; } - } + public bool UseStringTag + { + get { return XmlRpcFormatSettings.UseStringTag; } + set { XmlRpcFormatSettings.UseStringTag = value; } + } - [Browsable(false)] - public Encoding XmlEncoding - { - get { return XmlRpcFormatSettings.XmlEncoding; } - set { XmlRpcFormatSettings.XmlEncoding = value; } - } + [Browsable(false)] + public Encoding XmlEncoding + { + get { return XmlRpcFormatSettings.XmlEncoding; } + set { XmlRpcFormatSettings.XmlEncoding = value; } + } - public string XmlRpcMethod - { - get { return _xmlRpcMethod; } - set { _xmlRpcMethod = value; } - } + public string XmlRpcMethod + { + get { return _xmlRpcMethod; } + set { _xmlRpcMethod = value; } + } - public void SetProperties(WebRequest webReq) - { + public string DateTimeFormat + { + get { return XmlRpcFormatSettings.DateTimeFormat; } + set { XmlRpcFormatSettings.DateTimeFormat = value; } + } + + public void SetProperties(WebRequest webReq) + { #if (!SILVERLIGHT) - if (Proxy != null) - webReq.Proxy = Proxy; + if (Proxy != null) + webReq.Proxy = Proxy; #endif - HttpWebRequest httpReq = (HttpWebRequest)webReq; + HttpWebRequest httpReq = (HttpWebRequest)webReq; #if (!SILVERLIGHT) - httpReq.UserAgent = UserAgent; - httpReq.ProtocolVersion = ProtocolVersion; - httpReq.KeepAlive = KeepAlive; - httpReq.AllowAutoRedirect = AllowAutoRedirect; - webReq.PreAuthenticate = PreAuthenticate; - webReq.Timeout = Timeout; - // Compact Framework sets this to false by default - (webReq as HttpWebRequest).AllowWriteStreamBuffering = true; + httpReq.UserAgent = UserAgent; + httpReq.ProtocolVersion = ProtocolVersion; + httpReq.KeepAlive = KeepAlive; + httpReq.AllowAutoRedirect = AllowAutoRedirect; + webReq.PreAuthenticate = PreAuthenticate; + webReq.Timeout = Timeout; + // Compact Framework sets this to false by default + (webReq as HttpWebRequest).AllowWriteStreamBuffering = true; #endif - httpReq.CookieContainer = CookieContainer; + httpReq.CookieContainer = CookieContainer; #if (!COMPACT_FRAMEWORK && !FX1_0 && !SILVERLIGHT) - httpReq.ServicePoint.Expect100Continue = Expect100Continue; - httpReq.ServicePoint.UseNagleAlgorithm = UseNagleAlgorithm; + httpReq.ServicePoint.Expect100Continue = Expect100Continue; + httpReq.ServicePoint.UseNagleAlgorithm = UseNagleAlgorithm; #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) - webReq.ConnectionGroupName = ConnectionGroupName; + webReq.ConnectionGroupName = ConnectionGroupName; #endif #if (!SILVERLIGHT) - webReq.Credentials = Credentials; + webReq.Credentials = Credentials; #else webReq.Credentials = Credentials; webReq.UseDefaultCredentials = false; #endif -#if (!COMPACT_FRAMEWORK && !FX1_0 &&!SILVERLIGHT) - if (EnableCompression) - webReq.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); +#if (!COMPACT_FRAMEWORK && !FX1_0 && !SILVERLIGHT) + if (EnableCompression) + webReq.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); #endif - } + } - private void SetRequestHeaders( - WebHeaderCollection headers, - WebRequest webReq) - { - foreach (string key in headers) - { + private void SetRequestHeaders( + WebHeaderCollection headers, + WebRequest webReq) + { + foreach (string key in headers) + { #if (!SILVERLIGHT) - webReq.Headers.Add(key, headers[key]); -#endif - } - } + webReq.Headers.Add(key, headers[key]); +#endif + } + } #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) - private void SetClientCertificates( - X509CertificateCollection certificates, - WebRequest webReq) - { - foreach (X509Certificate certificate in certificates) - { - HttpWebRequest httpReq = (HttpWebRequest)webReq; - httpReq.ClientCertificates.Add(certificate); - } - } + private void SetClientCertificates( + X509CertificateCollection certificates, + WebRequest webReq) + { + foreach (X509Certificate certificate in certificates) + { + HttpWebRequest httpReq = (HttpWebRequest)webReq; + httpReq.ClientCertificates.Add(certificate); + } + } #endif - XmlRpcRequest MakeXmlRpcRequest(WebRequest webReq, MethodInfo mi, - object[] parameters, object clientObj, string xmlRpcMethod, - Guid proxyId) - { - webReq.Method = "POST"; - webReq.ContentType = "text/xml"; - string rpcMethodName = XmlRpcTypeInfo.GetRpcMethodName(mi); - XmlRpcRequest req = new XmlRpcRequest(rpcMethodName, parameters, mi, - xmlRpcMethod, proxyId); - return req; - } + XmlRpcRequest MakeXmlRpcRequest(WebRequest webReq, MethodInfo mi, + object[] parameters, object clientObj, string xmlRpcMethod, + Guid proxyId) + { + webReq.Method = "POST"; + webReq.ContentType = "text/xml"; + string rpcMethodName = XmlRpcTypeInfo.GetRpcMethodName(mi); + XmlRpcRequest req = new XmlRpcRequest(rpcMethodName, parameters, mi, + xmlRpcMethod, proxyId); + return req; + } - XmlRpcResponse ReadResponse( - XmlRpcRequest req, - WebResponse webResp, - Stream respStm) - { - HttpWebResponse httpResp = (HttpWebResponse)webResp; - if (httpResp.StatusCode != HttpStatusCode.OK) - { - // status 400 is used for errors caused by the client - // status 500 is used for server errors (not server application - // errors which are returned as fault responses) - if (httpResp.StatusCode == HttpStatusCode.BadRequest) - throw new XmlRpcException(httpResp.StatusDescription); - else - throw new XmlRpcServerException(httpResp.StatusDescription); - } - var deserializer = new XmlRpcResponseDeserializer(); - deserializer.NonStandard = _nonStandard; - Type retType = req.mi.ReturnType; - XmlRpcResponse xmlRpcResp - = deserializer.DeserializeResponse(respStm, req.ReturnType); - return xmlRpcResp; - } + XmlRpcResponse ReadResponse( + XmlRpcRequest req, + WebResponse webResp, + Stream respStm) + { + HttpWebResponse httpResp = (HttpWebResponse)webResp; + if (httpResp.StatusCode != HttpStatusCode.OK) + { + // status 400 is used for errors caused by the client + // status 500 is used for server errors (not server application + // errors which are returned as fault responses) + if (httpResp.StatusCode == HttpStatusCode.BadRequest) + throw new XmlRpcException(httpResp.StatusDescription); + else + throw new XmlRpcServerException(httpResp.StatusDescription); + } + var deserializer = new XmlRpcResponseDeserializer(); + deserializer.NonStandard = _nonStandard; + Type retType = req.mi.ReturnType; + XmlRpcResponse xmlRpcResp + = deserializer.DeserializeResponse(respStm, req.ReturnType); + return xmlRpcResp; + } - MethodInfo GetMethodInfoFromName(object clientObj, string methodName, - object[] parameters) - { - Type[] paramTypes = new Type[0]; - if (parameters != null) - { - paramTypes = new Type[parameters.Length]; - for (int i = 0; i < paramTypes.Length; i++) - { - if (parameters[i] == null) - throw new XmlRpcNullParameterException("Null parameters are invalid"); - paramTypes[i] = parameters[i].GetType(); - } - } - Type type = clientObj.GetType(); - MethodInfo mi = type.GetMethod(methodName, paramTypes); - if (mi == null) - { - try - { - mi = type.GetMethod(methodName); - } - catch (System.Reflection.AmbiguousMatchException) - { - throw new XmlRpcInvalidParametersException("Method parameters match " - + "the signature of more than one method"); - } - if (mi == null) - throw new Exception( - "Invoke on non-existent or non-public proxy method"); - else - throw new XmlRpcInvalidParametersException("Method parameters do " - + "not match signature of any method called " + methodName); - } - return mi; - } + MethodInfo GetMethodInfoFromName(object clientObj, string methodName, + object[] parameters) + { + Type[] paramTypes = new Type[0]; + if (parameters != null) + { + paramTypes = new Type[parameters.Length]; + for (int i = 0; i < paramTypes.Length; i++) + { + if (parameters[i] == null) + throw new XmlRpcNullParameterException("Null parameters are invalid"); + paramTypes[i] = parameters[i].GetType(); + } + } + Type type = clientObj.GetType(); + MethodInfo mi = type.GetMethod(methodName, paramTypes); + if (mi == null) + { + try + { + mi = type.GetMethod(methodName); + } + catch (System.Reflection.AmbiguousMatchException) + { + throw new XmlRpcInvalidParametersException("Method parameters match " + + "the signature of more than one method"); + } + if (mi == null) + throw new Exception( + "Invoke on non-existent or non-public proxy method"); + else + throw new XmlRpcInvalidParametersException("Method parameters do " + + "not match signature of any method called " + methodName); + } + return mi; + } - public IAsyncResult BeginInvoke( - MethodBase mb, - object[] parameters, - AsyncCallback callback, - object outerAsyncState) - { - return BeginInvoke(mb as MethodInfo, parameters, this, callback, - outerAsyncState); - } + public IAsyncResult BeginInvoke( + MethodBase mb, + object[] parameters, + AsyncCallback callback, + object outerAsyncState) + { + return BeginInvoke(mb as MethodInfo, parameters, this, callback, + outerAsyncState); + } - public IAsyncResult BeginInvoke( - MethodInfo mi, - object[] parameters, - AsyncCallback callback, - object outerAsyncState) - { - return BeginInvoke(mi, parameters, this, callback, - outerAsyncState); - } + public IAsyncResult BeginInvoke( + MethodInfo mi, + object[] parameters, + AsyncCallback callback, + object outerAsyncState) + { + return BeginInvoke(mi, parameters, this, callback, + outerAsyncState); + } - public IAsyncResult BeginInvoke( - string methodName, - object[] parameters, - object clientObj, - AsyncCallback callback, - object outerAsyncState) - { - MethodInfo mi = GetMethodInfoFromName(clientObj, methodName, parameters); - return BeginInvoke(mi, parameters, this, callback, - outerAsyncState); - } + public IAsyncResult BeginInvoke( + string methodName, + object[] parameters, + object clientObj, + AsyncCallback callback, + object outerAsyncState) + { + MethodInfo mi = GetMethodInfoFromName(clientObj, methodName, parameters); + return BeginInvoke(mi, parameters, this, callback, + outerAsyncState); + } - public IAsyncResult BeginInvoke( - MethodInfo mi, - object[] parameters, - object clientObj, - AsyncCallback callback, - object outerAsyncState) - { - string useUrl = GetEffectiveUrl(clientObj); - WebRequest webReq = GetWebRequest(new Uri(useUrl)); - XmlRpcRequest xmlRpcReq = MakeXmlRpcRequest(webReq, mi, - parameters, clientObj, _xmlRpcMethod, _id); - SetProperties(webReq); - SetRequestHeaders(Headers, webReq); + public IAsyncResult BeginInvoke( + MethodInfo mi, + object[] parameters, + object clientObj, + AsyncCallback callback, + object outerAsyncState) + { + string useUrl = GetEffectiveUrl(clientObj); + WebRequest webReq = GetWebRequest(new Uri(useUrl)); + XmlRpcRequest xmlRpcReq = MakeXmlRpcRequest(webReq, mi, + parameters, clientObj, _xmlRpcMethod, _id); + SetProperties(webReq); + SetRequestHeaders(Headers, webReq); #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) - SetClientCertificates(ClientCertificates, webReq); + SetClientCertificates(ClientCertificates, webReq); #endif - XmlRpcAsyncResult asr = new XmlRpcAsyncResult(this, xmlRpcReq, XmlRpcFormatSettings, - webReq, callback, outerAsyncState, 0); - webReq.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), - asr); - if (!asr.IsCompleted) - asr.CompletedSynchronously = false; - return asr; - } - - static void GetRequestStreamCallback(IAsyncResult asyncResult) - { - XmlRpcAsyncResult clientResult - = (XmlRpcAsyncResult)asyncResult.AsyncState; - clientResult.CompletedSynchronously = asyncResult.CompletedSynchronously; - try - { - Stream serStream = null; - Stream reqStream = null; - bool logging = (clientResult.ClientProtocol.RequestEvent != null); - if (!logging) - { - serStream = reqStream - = clientResult.Request.EndGetRequestStream(asyncResult); - } - else - serStream = new MemoryStream(2000); - try - { - XmlRpcRequest req = clientResult.XmlRpcRequest; - var serializer = new XmlRpcRequestSerializer(); - if (clientResult.XmlRpcFormatSettings.XmlEncoding != null) - serializer.XmlEncoding = clientResult.XmlRpcFormatSettings.XmlEncoding; - serializer.UseEmptyElementTags = clientResult.XmlRpcFormatSettings.UseEmptyElementTags; - serializer.UseEmptyParamsTag = clientResult.XmlRpcFormatSettings.UseEmptyParamsTag; - serializer.UseIndentation = clientResult.XmlRpcFormatSettings.UseIndentation; - serializer.Indentation = clientResult.XmlRpcFormatSettings.Indentation; - serializer.UseIntTag = clientResult.XmlRpcFormatSettings.UseIntTag; - serializer.UseStringTag = clientResult.XmlRpcFormatSettings.UseStringTag; - serializer.SerializeRequest(serStream, req); - if (logging) - { - reqStream = clientResult.Request.EndGetRequestStream(asyncResult); - serStream.Position = 0; - Util.CopyStream(serStream, reqStream); - reqStream.Flush(); - serStream.Position = 0; - clientResult.ClientProtocol.OnRequest( - new XmlRpcRequestEventArgs(req.proxyId, req.number, serStream)); - } - } - finally - { - if (reqStream != null) - reqStream.Close(); - } - clientResult.Request.BeginGetResponse( - new AsyncCallback(GetResponseCallback), clientResult); - } - catch (Exception ex) - { - ProcessAsyncException(clientResult, ex); - } - } + XmlRpcAsyncResult asr = new XmlRpcAsyncResult(this, xmlRpcReq, XmlRpcFormatSettings, + webReq, callback, outerAsyncState, 0); + webReq.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), + asr); + if (!asr.IsCompleted) + asr.CompletedSynchronously = false; + return asr; + } - static void GetResponseCallback(IAsyncResult asyncResult) - { - XmlRpcAsyncResult result = (XmlRpcAsyncResult)asyncResult.AsyncState; - result.CompletedSynchronously = asyncResult.CompletedSynchronously; - try - { - result.Response = result.ClientProtocol.GetWebResponse(result.Request, - asyncResult); - } - catch (Exception ex) - { - ProcessAsyncException(result, ex); - if (result.Response == null) - return; - } - ReadAsyncResponse(result); - } + static void GetRequestStreamCallback(IAsyncResult asyncResult) + { + XmlRpcAsyncResult clientResult + = (XmlRpcAsyncResult)asyncResult.AsyncState; + clientResult.CompletedSynchronously = asyncResult.CompletedSynchronously; + try + { + Stream serStream = null; + Stream reqStream = null; + bool logging = (clientResult.ClientProtocol.RequestEvent != null); + if (!logging) + { + serStream = reqStream + = clientResult.Request.EndGetRequestStream(asyncResult); + } + else + serStream = new MemoryStream(2000); + try + { + XmlRpcRequest req = clientResult.XmlRpcRequest; + var serializer = new XmlRpcRequestSerializer(); + if (clientResult.XmlRpcFormatSettings.XmlEncoding != null) + serializer.XmlEncoding = clientResult.XmlRpcFormatSettings.XmlEncoding; + serializer.UseEmptyElementTags = clientResult.XmlRpcFormatSettings.UseEmptyElementTags; + serializer.UseEmptyParamsTag = clientResult.XmlRpcFormatSettings.UseEmptyParamsTag; + serializer.UseIndentation = clientResult.XmlRpcFormatSettings.UseIndentation; + serializer.Indentation = clientResult.XmlRpcFormatSettings.Indentation; + serializer.UseIntTag = clientResult.XmlRpcFormatSettings.UseIntTag; + serializer.UseStringTag = clientResult.XmlRpcFormatSettings.UseStringTag; + serializer.SerializeRequest(serStream, req); + if (logging) + { + reqStream = clientResult.Request.EndGetRequestStream(asyncResult); + serStream.Position = 0; + Util.CopyStream(serStream, reqStream); + reqStream.Flush(); + serStream.Position = 0; + clientResult.ClientProtocol.OnRequest( + new XmlRpcRequestEventArgs(req.proxyId, req.number, serStream)); + } + } + finally + { + if (reqStream != null) + reqStream.Close(); + } + clientResult.Request.BeginGetResponse( + new AsyncCallback(GetResponseCallback), clientResult); + } + catch (Exception ex) + { + ProcessAsyncException(clientResult, ex); + } + } - static void ReadAsyncResponse(XmlRpcAsyncResult result) - { - if (result.Response.ContentLength == 0) - { - result.Complete(); - return; - } - try - { - result.ResponseStream = result.Response.GetResponseStream(); - ReadAsyncResponseStream(result); - } - catch (Exception ex) - { - ProcessAsyncException(result, ex); - } - } + static void GetResponseCallback(IAsyncResult asyncResult) + { + XmlRpcAsyncResult result = (XmlRpcAsyncResult)asyncResult.AsyncState; + result.CompletedSynchronously = asyncResult.CompletedSynchronously; + try + { + result.Response = result.ClientProtocol.GetWebResponse(result.Request, + asyncResult); + } + catch (Exception ex) + { + ProcessAsyncException(result, ex); + if (result.Response == null) + return; + } + ReadAsyncResponse(result); + } - static void ReadAsyncResponseStream(XmlRpcAsyncResult result) - { - IAsyncResult asyncResult; - do - { - byte[] buff = result.Buffer; - long contLen = result.Response.ContentLength; - if (buff == null) - { - if (contLen == -1) - result.Buffer = new Byte[1024]; - else - result.Buffer = new Byte[contLen]; - } - else - { - if (contLen != -1 && contLen > result.Buffer.Length) - result.Buffer = new Byte[contLen]; - } - buff = result.Buffer; - asyncResult = result.ResponseStream.BeginRead(buff, 0, buff.Length, - new AsyncCallback(ReadResponseCallback), result); - if (!asyncResult.CompletedSynchronously) - return; - } - while (!(ProcessAsyncResponseStreamResult(result, asyncResult))); - } + static void ReadAsyncResponse(XmlRpcAsyncResult result) + { + if (result.Response.ContentLength == 0) + { + result.Complete(); + return; + } + try + { + result.ResponseStream = result.Response.GetResponseStream(); + ReadAsyncResponseStream(result); + } + catch (Exception ex) + { + ProcessAsyncException(result, ex); + } + } - static bool ProcessAsyncResponseStreamResult(XmlRpcAsyncResult result, - IAsyncResult asyncResult) - { - int endReadLen = result.ResponseStream.EndRead(asyncResult); - long contLen = result.Response.ContentLength; - bool completed; - if (endReadLen == 0) - completed = true; - else if (contLen > 0 && endReadLen == contLen) - { - result.ResponseBufferedStream = new MemoryStream(result.Buffer); - completed = true; - } - else - { - if (result.ResponseBufferedStream == null) - { - result.ResponseBufferedStream = new MemoryStream(result.Buffer.Length); - } - result.ResponseBufferedStream.Write(result.Buffer, 0, endReadLen); - completed = false; - } - if (completed) - result.Complete(); - return completed; - } + static void ReadAsyncResponseStream(XmlRpcAsyncResult result) + { + IAsyncResult asyncResult; + do + { + byte[] buff = result.Buffer; + long contLen = result.Response.ContentLength; + if (buff == null) + { + if (contLen == -1) + result.Buffer = new Byte[1024]; + else + result.Buffer = new Byte[contLen]; + } + else + { + if (contLen != -1 && contLen > result.Buffer.Length) + result.Buffer = new Byte[contLen]; + } + buff = result.Buffer; + asyncResult = result.ResponseStream.BeginRead(buff, 0, buff.Length, + new AsyncCallback(ReadResponseCallback), result); + if (!asyncResult.CompletedSynchronously) + return; + } + while (!(ProcessAsyncResponseStreamResult(result, asyncResult))); + } + static bool ProcessAsyncResponseStreamResult(XmlRpcAsyncResult result, + IAsyncResult asyncResult) + { + int endReadLen = result.ResponseStream.EndRead(asyncResult); + long contLen = result.Response.ContentLength; + bool completed; + if (endReadLen == 0) + completed = true; + else if (contLen > 0 && endReadLen == contLen) + { + result.ResponseBufferedStream = new MemoryStream(result.Buffer); + completed = true; + } + else + { + if (result.ResponseBufferedStream == null) + { + result.ResponseBufferedStream = new MemoryStream(result.Buffer.Length); + } + result.ResponseBufferedStream.Write(result.Buffer, 0, endReadLen); + completed = false; + } + if (completed) + result.Complete(); + return completed; + } - static void ReadResponseCallback(IAsyncResult asyncResult) - { - XmlRpcAsyncResult result = (XmlRpcAsyncResult)asyncResult.AsyncState; - result.CompletedSynchronously = asyncResult.CompletedSynchronously; - if (asyncResult.CompletedSynchronously) - return; - try - { - bool completed = ProcessAsyncResponseStreamResult(result, asyncResult); - if (!completed) - ReadAsyncResponseStream(result); - } - catch (Exception ex) - { - ProcessAsyncException(result, ex); - } - } - static void ProcessAsyncException(XmlRpcAsyncResult clientResult, - Exception ex) - { - WebException webex = ex as WebException; - if (webex != null && webex.Response != null) - { - clientResult.Response = webex.Response; - return; - } - if (clientResult.IsCompleted) - throw new Exception("error during async processing"); - clientResult.Complete(ex); - } + static void ReadResponseCallback(IAsyncResult asyncResult) + { + XmlRpcAsyncResult result = (XmlRpcAsyncResult)asyncResult.AsyncState; + result.CompletedSynchronously = asyncResult.CompletedSynchronously; + if (asyncResult.CompletedSynchronously) + return; + try + { + bool completed = ProcessAsyncResponseStreamResult(result, asyncResult); + if (!completed) + ReadAsyncResponseStream(result); + } + catch (Exception ex) + { + ProcessAsyncException(result, ex); + } + } - public object EndInvoke( - IAsyncResult asr) - { - return EndInvoke(asr, null); - } + static void ProcessAsyncException(XmlRpcAsyncResult clientResult, + Exception ex) + { + WebException webex = ex as WebException; + if (webex != null && webex.Response != null) + { + clientResult.Response = webex.Response; + return; + } + if (clientResult.IsCompleted) + throw new Exception("error during async processing"); + clientResult.Complete(ex); + } - public T EndInvoke(IAsyncResult asr) - { - return (T)EndInvoke(asr, typeof(T)); - } + public object EndInvoke( + IAsyncResult asr) + { + return EndInvoke(asr, null); + } - public object EndInvoke(IAsyncResult asr, Type returnType) - { - object reto = null; - Stream responseStream = null; - try - { - XmlRpcAsyncResult clientResult = (XmlRpcAsyncResult)asr; - if (clientResult.Exception != null) - throw clientResult.Exception; - if (clientResult.EndSendCalled) - throw new Exception("dup call to EndSend"); - clientResult.EndSendCalled = true; - if (clientResult.XmlRpcRequest != null && returnType != null) - clientResult.XmlRpcRequest.ReturnType = returnType; - HttpWebResponse webResp = (HttpWebResponse)clientResult.WaitForResponse(); - clientResult._responseCookies = webResp.Cookies; - clientResult._responseHeaders = webResp.Headers; - responseStream = clientResult.ResponseBufferedStream; - if (ResponseEvent != null) - { - OnResponse(new XmlRpcResponseEventArgs( - clientResult.XmlRpcRequest.proxyId, - clientResult.XmlRpcRequest.number, - responseStream)); - responseStream.Position = 0; + public T EndInvoke(IAsyncResult asr) + { + return (T)EndInvoke(asr, typeof(T)); } + + public object EndInvoke(IAsyncResult asr, Type returnType) + { + object reto = null; + Stream responseStream = null; + try + { + XmlRpcAsyncResult clientResult = (XmlRpcAsyncResult)asr; + if (clientResult.Exception != null) + throw clientResult.Exception; + if (clientResult.EndSendCalled) + throw new Exception("dup call to EndSend"); + clientResult.EndSendCalled = true; + if (clientResult.XmlRpcRequest != null && returnType != null) + clientResult.XmlRpcRequest.ReturnType = returnType; + HttpWebResponse webResp = (HttpWebResponse)clientResult.WaitForResponse(); + clientResult._responseCookies = webResp.Cookies; + clientResult._responseHeaders = webResp.Headers; + responseStream = clientResult.ResponseBufferedStream; + if (ResponseEvent != null) + { + OnResponse(new XmlRpcResponseEventArgs( + clientResult.XmlRpcRequest.proxyId, + clientResult.XmlRpcRequest.number, + responseStream)); + responseStream.Position = 0; + } #if (!COMPACT_FRAMEWORK && !FX1_0 && !SILVERLIGHT) - responseStream = MaybeDecompressStream((HttpWebResponse)webResp, - responseStream); + responseStream = MaybeDecompressStream((HttpWebResponse)webResp, + responseStream); #endif - XmlRpcResponse resp = ReadResponse(clientResult.XmlRpcRequest, - webResp, responseStream); - reto = resp.retVal; - } - finally - { - if (responseStream != null) - responseStream.Close(); - } - return reto; - } + XmlRpcResponse resp = ReadResponse(clientResult.XmlRpcRequest, + webResp, responseStream); + reto = resp.retVal; + } + finally + { + if (responseStream != null) + responseStream.Close(); + } + return reto; + } - string GetEffectiveUrl(object clientObj) - { - // client can either have define URI in attribute or have set it - // via proxy's ServiceURI property - but must exist by now - if (!string.IsNullOrEmpty(Url)) - return Url; - string useUrl = XmlRpcTypeInfo.GetUrlFromAttribute(clientObj.GetType()); - if (!string.IsNullOrEmpty(useUrl)) - return useUrl; - throw new XmlRpcMissingUrl("Proxy XmlRpcUrl attribute or Url " - + "property not set."); - } + string GetEffectiveUrl(object clientObj) + { + // client can either have define URI in attribute or have set it + // via proxy's ServiceURI property - but must exist by now + if (!string.IsNullOrEmpty(Url)) + return Url; + string useUrl = XmlRpcTypeInfo.GetUrlFromAttribute(clientObj.GetType()); + if (!string.IsNullOrEmpty(useUrl)) + return useUrl; + throw new XmlRpcMissingUrl("Proxy XmlRpcUrl attribute or Url " + + "property not set."); + } - [XmlRpcMethod("system.listMethods")] - public string[] SystemListMethods() - { - return (string[])Invoke("SystemListMethods", new Object[0]); - } + [XmlRpcMethod("system.listMethods")] + public string[] SystemListMethods() + { + return (string[])Invoke("SystemListMethods", new Object[0]); + } - [XmlRpcMethod("system.listMethods")] - public IAsyncResult BeginSystemListMethods( - AsyncCallback Callback, - object State) - { - return BeginInvoke("SystemListMethods", new object[0], this, Callback, - State); - } + [XmlRpcMethod("system.listMethods")] + public IAsyncResult BeginSystemListMethods( + AsyncCallback Callback, + object State) + { + return BeginInvoke("SystemListMethods", new object[0], this, Callback, + State); + } - public string[] EndSystemListMethods(IAsyncResult AsyncResult) - { - return (string[])EndInvoke(AsyncResult); - } + public string[] EndSystemListMethods(IAsyncResult AsyncResult) + { + return (string[])EndInvoke(AsyncResult); + } - [XmlRpcMethod("system.methodSignature")] - public object[] SystemMethodSignature(string MethodName) - { - return (object[])Invoke("SystemMethodSignature", - new Object[] { MethodName }); - } + [XmlRpcMethod("system.methodSignature")] + public object[] SystemMethodSignature(string MethodName) + { + return (object[])Invoke("SystemMethodSignature", + new Object[] { MethodName }); + } - [XmlRpcMethod("system.methodSignature")] - public IAsyncResult BeginSystemMethodSignature( - string MethodName, - AsyncCallback Callback, - object State) - { - return BeginInvoke("SystemMethodSignature", - new Object[] { MethodName }, this, Callback, State); - } + [XmlRpcMethod("system.methodSignature")] + public IAsyncResult BeginSystemMethodSignature( + string MethodName, + AsyncCallback Callback, + object State) + { + return BeginInvoke("SystemMethodSignature", + new Object[] { MethodName }, this, Callback, State); + } - public Array EndSystemMethodSignature(IAsyncResult AsyncResult) - { - return (Array)EndInvoke(AsyncResult); - } + public Array EndSystemMethodSignature(IAsyncResult AsyncResult) + { + return (Array)EndInvoke(AsyncResult); + } - [XmlRpcMethod("system.methodHelp")] - public string SystemMethodHelp(string MethodName) - { - return (string)Invoke("SystemMethodHelp", - new Object[] { MethodName }); - } + [XmlRpcMethod("system.methodHelp")] + public string SystemMethodHelp(string MethodName) + { + return (string)Invoke("SystemMethodHelp", + new Object[] { MethodName }); + } - [XmlRpcMethod("system.methodHelp")] - public IAsyncResult BeginSystemMethodHelp( - string MethodName, - AsyncCallback Callback, - object State) - { - return BeginInvoke("SystemMethodHelp", - new Object[] { MethodName }, this, Callback, State); - } + [XmlRpcMethod("system.methodHelp")] + public IAsyncResult BeginSystemMethodHelp( + string MethodName, + AsyncCallback Callback, + object State) + { + return BeginInvoke("SystemMethodHelp", + new Object[] { MethodName }, this, Callback, State); + } - public string EndSystemMethodHelp(IAsyncResult AsyncResult) - { - return (string)EndInvoke(AsyncResult); - } + public string EndSystemMethodHelp(IAsyncResult AsyncResult) + { + return (string)EndInvoke(AsyncResult); + } - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + } - protected virtual WebRequest GetWebRequest(Uri uri) - { - WebRequest req = WebRequest.Create(uri); - return req; - } + protected virtual WebRequest GetWebRequest(Uri uri) + { + WebRequest req = WebRequest.Create(uri); + return req; + } - protected virtual WebResponse GetWebResponse(WebRequest request) - { + protected virtual WebResponse GetWebResponse(WebRequest request) + { #if (SILVERLIGHT) throw new NotSupportedException(); #else - WebResponse ret = null; - try - { - ret = request.GetResponse(); - } - catch (WebException ex) - { - if (ex.Response == null) - throw; - ret = ex.Response; - } - return ret; + WebResponse ret = null; + try + { + ret = request.GetResponse(); + } + catch (WebException ex) + { + if (ex.Response == null) + throw; + ret = ex.Response; + } + return ret; #endif - } + } #if (!COMPACT_FRAMEWORK && !FX1_0 && !SILVERLIGHT) - // support for gzip and deflate - protected Stream MaybeDecompressStream(HttpWebResponse httpWebResp, - Stream respStream) - { - Stream decodedStream; - string contentEncoding = httpWebResp.ContentEncoding.ToLower(); - string coen = httpWebResp.Headers["Content-Encoding"]; - if (contentEncoding.Contains("gzip")) - { - decodedStream = new System.IO.Compression.GZipStream(respStream, - System.IO.Compression.CompressionMode.Decompress); - } - else if (contentEncoding.Contains("deflate")) - { - decodedStream = new System.IO.Compression.DeflateStream(respStream, - System.IO.Compression.CompressionMode.Decompress); - } - else - decodedStream = respStream; - return decodedStream; - } + // support for gzip and deflate + protected Stream MaybeDecompressStream(HttpWebResponse httpWebResp, + Stream respStream) + { + Stream decodedStream; + string contentEncoding = httpWebResp.ContentEncoding.ToLower(); + string coen = httpWebResp.Headers["Content-Encoding"]; + if (contentEncoding.Contains("gzip")) + { + decodedStream = new System.IO.Compression.GZipStream(respStream, + System.IO.Compression.CompressionMode.Decompress); + } + else if (contentEncoding.Contains("deflate")) + { + decodedStream = new System.IO.Compression.DeflateStream(respStream, + System.IO.Compression.CompressionMode.Decompress); + } + else + decodedStream = respStream; + return decodedStream; + } #endif - protected virtual WebResponse GetWebResponse(WebRequest request, - IAsyncResult result) - { - return request.EndGetResponse(result); - } + protected virtual WebResponse GetWebResponse(WebRequest request, + IAsyncResult result) + { + return request.EndGetResponse(result); + } - public void AttachLogger(XmlRpcLogger logger) - { - logger.SubscribeTo(this); - } + public void AttachLogger(XmlRpcLogger logger) + { + logger.SubscribeTo(this); + } - public event XmlRpcRequestEventHandler RequestEvent; - public event XmlRpcResponseEventHandler ResponseEvent; + public event XmlRpcRequestEventHandler RequestEvent; + public event XmlRpcResponseEventHandler ResponseEvent; - protected virtual void OnRequest(XmlRpcRequestEventArgs e) - { - if (RequestEvent != null) - { - RequestEvent(this, e); - } - } + protected virtual void OnRequest(XmlRpcRequestEventArgs e) + { + if (RequestEvent != null) + { + RequestEvent(this, e); + } + } - internal bool LogResponse - { - get { return ResponseEvent != null; } - } + internal bool LogResponse + { + get { return ResponseEvent != null; } + } - protected virtual void OnResponse(XmlRpcResponseEventArgs e) - { - if (ResponseEvent != null) - { - ResponseEvent(this, e); - } - } + protected virtual void OnResponse(XmlRpcResponseEventArgs e) + { + if (ResponseEvent != null) + { + ResponseEvent(this, e); + } + } - internal void InternalOnResponse(XmlRpcResponseEventArgs e) - { - OnResponse(e); + internal void InternalOnResponse(XmlRpcResponseEventArgs e) + { + OnResponse(e); + } } - } - -//#if (COMPACT_FRAMEWORK && ) -// // dummy attribute because System.ComponentModel.Browsable is not -// // support in the compact framework -// [AttributeUsage(AttributeTargets.Property)] -// public class BrowsableAttribute : Attribute -// { -// public BrowsableAttribute(bool dummy) -// { -// } -// } -//#endif - - public delegate void XmlRpcRequestEventHandler(object sender, - XmlRpcRequestEventArgs args); - - public delegate void XmlRpcResponseEventHandler(object sender, - XmlRpcResponseEventArgs args); + + //#if (COMPACT_FRAMEWORK && ) + // // dummy attribute because System.ComponentModel.Browsable is not + // // support in the compact framework + // [AttributeUsage(AttributeTargets.Property)] + // public class BrowsableAttribute : Attribute + // { + // public BrowsableAttribute(bool dummy) + // { + // } + // } + //#endif + + public delegate void XmlRpcRequestEventHandler(object sender, + XmlRpcRequestEventArgs args); + + public delegate void XmlRpcResponseEventHandler(object sender, + XmlRpcResponseEventArgs args); } diff --git a/src/XmlRpcFormatSettings.cs b/src/XmlRpcFormatSettings.cs index d775e18..72ba4f7 100644 --- a/src/XmlRpcFormatSettings.cs +++ b/src/XmlRpcFormatSettings.cs @@ -23,63 +23,28 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -using System; -using System.Collections.Generic; using System.Text; namespace CookComputing.XmlRpc { - public class XmlRpcFormatSettings - { - public int Indentation + public class XmlRpcFormatSettings { - get { return m_indentation; } - set { m_indentation = value; } - } - int m_indentation = 2; + public int Indentation { get; set; } = 2; - public bool UseEmptyElementTags - { - get { return m_bUseEmptyElementTag; } - set { m_bUseEmptyElementTag = value; } - } - bool m_bUseEmptyElementTag = true; + public bool UseEmptyElementTags { get; set; } = true; - public bool UseEmptyParamsTag - { - get { return m_bUseEmptyParamsTag; } - set { m_bUseEmptyParamsTag = value; } - } - bool m_bUseEmptyParamsTag = true; + public bool UseEmptyParamsTag { get; set; } = true; - public bool UseIndentation - { - get { return m_bUseIndentation; } - set { m_bUseIndentation = value; } - } - bool m_bUseIndentation = true; + public bool UseIndentation { get; set; } = true; - public bool UseIntTag - { - get { return m_useIntTag; } - set { m_useIntTag = value; } - } - bool m_useIntTag; + public bool UseIntTag { get; set; } - public bool UseStringTag - { - get { return m_useStringTag; } - set { m_useStringTag = value; } - } - bool m_useStringTag = true; + public bool UseStringTag { get; set; } = true; - public Encoding XmlEncoding - { - get { return m_encoding; } - set { m_encoding = value; } - } - Encoding m_encoding = null; + public Encoding XmlEncoding { get; set; } = null; + + public bool OmitXmlDeclaration { get; set; } - public bool OmitXmlDeclaration { get; set; } - } + public string DateTimeFormat { get; set; } = "yyyyMMdd'T'HH':'mm':'ss"; + } } diff --git a/src/XmlRpcSerializer.cs b/src/XmlRpcSerializer.cs index 13d9bcc..feb0940 100644 --- a/src/XmlRpcSerializer.cs +++ b/src/XmlRpcSerializer.cs @@ -27,520 +27,522 @@ DEALINGS IN THE SOFTWARE. namespace CookComputing.XmlRpc { - using System; - using System.Collections; - using System.Globalization; - using System.IO; - using System.Reflection; - using System.Text; - using System.Text.RegularExpressions; - using System.Threading; - using System.Xml; - using System.Collections.Generic; - - public class XmlRpcSerializer - { - protected XmlRpcFormatSettings XmlRpcFormatSettings { get; private set; } - - public XmlRpcSerializer() + using System; + using System.Globalization; + using System.IO; + using System.Reflection; + using System.Text; + using System.Xml; + using System.Collections.Generic; + + public class XmlRpcSerializer { - XmlRpcFormatSettings = new XmlRpcFormatSettings(); - } + protected XmlRpcFormatSettings XmlRpcFormatSettings { get; private set; } - public XmlRpcSerializer(XmlRpcFormatSettings settings) - { - XmlRpcFormatSettings = settings; - } + public XmlRpcSerializer() + { + XmlRpcFormatSettings = new XmlRpcFormatSettings(); + } - public int Indentation - { - get { return XmlRpcFormatSettings.Indentation; } - set { XmlRpcFormatSettings.Indentation = value; } - } + public XmlRpcSerializer(XmlRpcFormatSettings settings) + { + XmlRpcFormatSettings = settings; + } - public bool UseEmptyElementTags - { - get { return XmlRpcFormatSettings.UseEmptyElementTags; } - set { XmlRpcFormatSettings.UseEmptyElementTags = value; } - } + public int Indentation + { + get { return XmlRpcFormatSettings.Indentation; } + set { XmlRpcFormatSettings.Indentation = value; } + } - public bool UseEmptyParamsTag - { - get { return XmlRpcFormatSettings.UseEmptyParamsTag; } - set { XmlRpcFormatSettings.UseEmptyParamsTag = value; } - } + public bool UseEmptyElementTags + { + get { return XmlRpcFormatSettings.UseEmptyElementTags; } + set { XmlRpcFormatSettings.UseEmptyElementTags = value; } + } - public bool UseIndentation - { - get { return XmlRpcFormatSettings.UseIndentation; } - set { XmlRpcFormatSettings.UseIndentation = value; } - } + public bool UseEmptyParamsTag + { + get { return XmlRpcFormatSettings.UseEmptyParamsTag; } + set { XmlRpcFormatSettings.UseEmptyParamsTag = value; } + } - public bool UseIntTag - { - get { return XmlRpcFormatSettings.UseIntTag; } - set { XmlRpcFormatSettings.UseIntTag = value; } - } + public bool UseIndentation + { + get { return XmlRpcFormatSettings.UseIndentation; } + set { XmlRpcFormatSettings.UseIndentation = value; } + } - public bool UseStringTag - { - get { return XmlRpcFormatSettings.UseStringTag; } - set { XmlRpcFormatSettings.UseStringTag = value; } - } + public bool UseIntTag + { + get { return XmlRpcFormatSettings.UseIntTag; } + set { XmlRpcFormatSettings.UseIntTag = value; } + } - public Encoding XmlEncoding - { - get { return XmlRpcFormatSettings.XmlEncoding; } - set { XmlRpcFormatSettings.XmlEncoding = value; } - } + public bool UseStringTag + { + get { return XmlRpcFormatSettings.UseStringTag; } + set { XmlRpcFormatSettings.UseStringTag = value; } + } - //#if (DEBUG) - public - //#endif - void Serialize( - XmlWriter xtw, - Object o, - MappingActions mappingActions) - { - Serialize(xtw, o, mappingActions, new List()); - } + public Encoding XmlEncoding + { + get { return XmlRpcFormatSettings.XmlEncoding; } + set { XmlRpcFormatSettings.XmlEncoding = value; } + } - //#if (DEBUG) - public - //#endif - void Serialize( - XmlWriter xtw, - Object o, - MappingActions mappingActions, - List nestedObjs) - { - if (nestedObjs.Contains(o)) - throw new XmlRpcUnsupportedTypeException(nestedObjs[0].GetType(), - "Cannot serialize recursive data structure"); - nestedObjs.Add(o); - try - { - xtw.WriteStartElement("", "value", ""); - XmlRpcType xType = XmlRpcTypeInfo.GetXmlRpcType(o); - if (xType == XmlRpcType.tArray) + public string DateTimeFormat { - xtw.WriteStartElement("", "array", ""); - xtw.WriteStartElement("", "data", ""); - Array a = (Array)o; - foreach (Object aobj in a) - { - //if (aobj == null) - // throw new XmlRpcMappingSerializeException(String.Format( - // "Items in array cannot be null ({0}[]).", - //o.GetType().GetElementType())); - Serialize(xtw, aobj, mappingActions, nestedObjs); - } - WriteFullEndElement(xtw); - WriteFullEndElement(xtw); + get { return XmlRpcFormatSettings.DateTimeFormat; } + set { XmlRpcFormatSettings.DateTimeFormat = value; } } - else if (xType == XmlRpcType.tMultiDimArray) + + //#if (DEBUG) + public + //#endif + void Serialize( + XmlWriter xtw, + Object o, + MappingActions mappingActions) { - Array mda = (Array)o; - int[] indices = new int[mda.Rank]; - BuildArrayXml(xtw, mda, 0, indices, mappingActions, nestedObjs); + Serialize(xtw, o, mappingActions, new List()); } - else if (xType == XmlRpcType.tBase64) + + //#if (DEBUG) + public + //#endif + void Serialize( + XmlWriter xtw, + Object o, + MappingActions mappingActions, + List nestedObjs) { - byte[] buf = (byte[])o; - xtw.WriteStartElement("", "base64", ""); - xtw.WriteBase64(buf, 0, buf.Length); - WriteFullEndElement(xtw); + if (nestedObjs.Contains(o)) + throw new XmlRpcUnsupportedTypeException(nestedObjs[0].GetType(), + "Cannot serialize recursive data structure"); + nestedObjs.Add(o); + try + { + xtw.WriteStartElement("", "value", ""); + XmlRpcType xType = XmlRpcTypeInfo.GetXmlRpcType(o); + if (xType == XmlRpcType.tArray) + { + xtw.WriteStartElement("", "array", ""); + xtw.WriteStartElement("", "data", ""); + Array a = (Array)o; + foreach (Object aobj in a) + { + //if (aobj == null) + // throw new XmlRpcMappingSerializeException(String.Format( + // "Items in array cannot be null ({0}[]).", + //o.GetType().GetElementType())); + Serialize(xtw, aobj, mappingActions, nestedObjs); + } + WriteFullEndElement(xtw); + WriteFullEndElement(xtw); + } + else if (xType == XmlRpcType.tMultiDimArray) + { + Array mda = (Array)o; + int[] indices = new int[mda.Rank]; + BuildArrayXml(xtw, mda, 0, indices, mappingActions, nestedObjs); + } + else if (xType == XmlRpcType.tBase64) + { + byte[] buf = (byte[])o; + xtw.WriteStartElement("", "base64", ""); + xtw.WriteBase64(buf, 0, buf.Length); + WriteFullEndElement(xtw); + } + else if (xType == XmlRpcType.tBoolean) + { + bool boolVal = (bool)o; + if (boolVal) + WriteFullElementString(xtw, "boolean", "1"); + else + WriteFullElementString(xtw, "boolean", "0"); + } + else if (xType == XmlRpcType.tDateTime) + { + DateTime dt = (DateTime)o; + string sdt = dt.ToString(DateTimeFormat, DateTimeFormatInfo.InvariantInfo); + WriteFullElementString(xtw, "dateTime.iso8601", sdt); + } + else if (xType == XmlRpcType.tDouble) + { + double doubleVal = (double)o; + WriteFullElementString(xtw, "double", doubleVal.ToString(null, + CultureInfo.InvariantCulture)); + } + else if (xType == XmlRpcType.tHashtable) + { + xtw.WriteStartElement("", "struct", ""); + XmlRpcStruct xrs = o as XmlRpcStruct; + foreach (object obj in xrs.Keys) + { + string skey = obj as string; + xtw.WriteStartElement("", "member", ""); + WriteFullElementString(xtw, "name", skey); + Serialize(xtw, xrs[skey], mappingActions, nestedObjs); + WriteFullEndElement(xtw); + } + WriteFullEndElement(xtw); + } + else if (xType == XmlRpcType.tInt32) + { + o = SerializeInt32(xtw, o, mappingActions); + } + else if (xType == XmlRpcType.tInt64) + { + o = SerializeInt64(xtw, o, mappingActions); + } + else if (xType == XmlRpcType.tString) + { + SerializeString(xtw, o); + } + else if (xType == XmlRpcType.tStruct) + { + MappingActions structActions + = GetMappingActions(o.GetType(), mappingActions); + xtw.WriteStartElement("", "struct", ""); + MemberInfo[] mis = o.GetType().GetMembers(); + foreach (MemberInfo mi in mis) + { + if (Attribute.IsDefined(mi, typeof(NonSerializedAttribute))) + continue; + if (mi.MemberType == MemberTypes.Field) + { + FieldInfo fi = (FieldInfo)mi; + string member = fi.Name; + Attribute attrchk = Attribute.GetCustomAttribute(fi, + typeof(XmlRpcMemberAttribute)); + if (attrchk != null && attrchk is XmlRpcMemberAttribute) + { + string mmbr = ((XmlRpcMemberAttribute)attrchk).Member; + if (mmbr != "") + member = mmbr; + } + MappingActions memberActions = MemberMappingActions(o.GetType(), + fi.Name, structActions); + if (fi.GetValue(o) == null) + { + if (memberActions.NullMappingAction == NullMappingAction.Ignore) + continue; + else if (memberActions.NullMappingAction == NullMappingAction.Error) + throw new XmlRpcMappingSerializeException(@"Member """ + member + + @""" of struct """ + o.GetType().Name + @""" cannot be null."); + } + xtw.WriteStartElement("", "member", ""); + WriteFullElementString(xtw, "name", member); + Serialize(xtw, fi.GetValue(o), memberActions, nestedObjs); + WriteFullEndElement(xtw); + } + else if (mi.MemberType == MemberTypes.Property) + { + PropertyInfo pi = (PropertyInfo)mi; + string member = pi.Name; + Attribute attrchk = Attribute.GetCustomAttribute(pi, + typeof(XmlRpcMemberAttribute)); + if (attrchk != null && attrchk is XmlRpcMemberAttribute) + { + string mmbr = ((XmlRpcMemberAttribute)attrchk).Member; + if (mmbr != "") + member = mmbr; + } + MappingActions memberActions = MemberMappingActions(o.GetType(), + pi.Name, structActions); + if (pi.GetValue(o, null) == null) + { + if (memberActions.NullMappingAction == NullMappingAction.Ignore) + continue; + else if (memberActions.NullMappingAction == NullMappingAction.Error) + throw new XmlRpcMappingSerializeException(@"Member """ + member + + @""" of struct """ + o.GetType().Name + @""" cannot be null."); + } + xtw.WriteStartElement("", "member", ""); + WriteFullElementString(xtw, "name", member); + Serialize(xtw, pi.GetValue(o, null), memberActions, nestedObjs); + WriteFullEndElement(xtw); + } + } + WriteFullEndElement(xtw); + } + else if (xType == XmlRpcType.tVoid) + WriteFullElementString(xtw, "string", ""); + else if (xType == XmlRpcType.tNil) + { + xtw.WriteStartElement("nil"); + WriteFullEndElement(xtw); + } + else + throw new XmlRpcUnsupportedTypeException(o.GetType()); + WriteFullEndElement(xtw); + } + catch (System.NullReferenceException) + { + throw new XmlRpcNullReferenceException("Attempt to serialize data " + + "containing null reference"); + } + finally + { + nestedObjs.RemoveAt(nestedObjs.Count - 1); + } } - else if (xType == XmlRpcType.tBoolean) + + private void SerializeString(XmlWriter xtw, Object o) { - bool boolVal = (bool)o; - if (boolVal) - WriteFullElementString(xtw, "boolean", "1"); - else - WriteFullElementString(xtw, "boolean", "0"); + try + { + if (UseStringTag) + { + WriteFullElementString(xtw, "string", (string)o); + } + else + xtw.WriteString((string)o); + } + catch (ArgumentException ex) + { + string msg = string.Format("Unable to serialize string to XML: {0}", ex.Message); + throw new XmlRpcException(msg, ex); + } } - else if (xType == XmlRpcType.tDateTime) + + private Object SerializeInt64(XmlWriter xtw, Object o, MappingActions mappingActions) { - DateTime dt = (DateTime)o; - string sdt = dt.ToString("yyyyMMdd'T'HH':'mm':'ss", - DateTimeFormatInfo.InvariantInfo); - WriteFullElementString(xtw, "dateTime.iso8601", sdt); + if (o.GetType().IsEnum) + { + if (mappingActions.EnumMapping == EnumMapping.String) + { + SerializeString(xtw, o.ToString()); + } + else + o = Convert.ToInt64(o); + } + WriteFullElementString(xtw, "i8", o.ToString()); + return o; } - else if (xType == XmlRpcType.tDouble) + + private Object SerializeInt32(XmlWriter xtw, Object o, MappingActions mappingActions) { - double doubleVal = (double)o; - WriteFullElementString(xtw, "double", doubleVal.ToString(null, - CultureInfo.InvariantCulture)); + if (o.GetType().IsEnum) + { + if (mappingActions.EnumMapping == EnumMapping.String) + { + SerializeString(xtw, o.ToString()); + return o; + } + else + o = Convert.ToInt32(o); + } + if (UseIntTag) + WriteFullElementString(xtw, "int", o.ToString()); + else + WriteFullElementString(xtw, "i4", o.ToString()); + return o; } - else if (xType == XmlRpcType.tHashtable) + + void BuildArrayXml( + XmlWriter xtw, + Array ary, + int CurRank, + int[] indices, + MappingActions mappingActions, + List nestedObjs) { - xtw.WriteStartElement("", "struct", ""); - XmlRpcStruct xrs = o as XmlRpcStruct; - foreach (object obj in xrs.Keys) - { - string skey = obj as string; - xtw.WriteStartElement("", "member", ""); - WriteFullElementString(xtw, "name", skey); - Serialize(xtw, xrs[skey], mappingActions, nestedObjs); + xtw.WriteStartElement("", "array", ""); + xtw.WriteStartElement("", "data", ""); + if (CurRank < (ary.Rank - 1)) + { + for (int i = 0; i < ary.GetLength(CurRank); i++) + { + indices[CurRank] = i; + xtw.WriteStartElement("", "value", ""); + BuildArrayXml(xtw, ary, CurRank + 1, indices, mappingActions, nestedObjs); + WriteFullEndElement(xtw); + } + } + else + { + for (int i = 0; i < ary.GetLength(CurRank); i++) + { + indices[CurRank] = i; + Serialize(xtw, ary.GetValue(indices), mappingActions, nestedObjs); + } + } + WriteFullEndElement(xtw); WriteFullEndElement(xtw); - } - WriteFullEndElement(xtw); } - else if (xType == XmlRpcType.tInt32) + + struct FaultStruct { - o = SerializeInt32(xtw, o, mappingActions); + public int faultCode; + public string faultString; } - else if (xType == XmlRpcType.tInt64) + + struct FaultStructStringCode { - o = SerializeInt64(xtw, o, mappingActions); + public string faultCode; + public string faultString; } - else if (xType == XmlRpcType.tString) + + public void SerializeFaultResponse( + Stream stm, + XmlRpcFaultException faultEx) { - SerializeString(xtw, o); + FaultStruct fs; + fs.faultCode = faultEx.FaultCode; + fs.faultString = faultEx.FaultString; + XmlWriter xtw = XmlRpcXmlWriter.Create(stm, XmlRpcFormatSettings); + xtw.WriteStartDocument(); + xtw.WriteStartElement("", "methodResponse", ""); + xtw.WriteStartElement("", "fault", ""); + Serialize(xtw, fs, new MappingActions { NullMappingAction = NullMappingAction.Error }); + WriteFullEndElement(xtw); + WriteFullEndElement(xtw); + xtw.Flush(); } - else if (xType == XmlRpcType.tStruct) + + protected XmlWriterSettings ConfigureXmlFormat() { - MappingActions structActions - = GetMappingActions(o.GetType(), mappingActions); - xtw.WriteStartElement("", "struct", ""); - MemberInfo[] mis = o.GetType().GetMembers(); - foreach (MemberInfo mi in mis) - { - if (Attribute.IsDefined(mi, typeof(NonSerializedAttribute))) - continue; - if (mi.MemberType == MemberTypes.Field) + if (UseIndentation) { - FieldInfo fi = (FieldInfo)mi; - string member = fi.Name; - Attribute attrchk = Attribute.GetCustomAttribute(fi, - typeof(XmlRpcMemberAttribute)); - if (attrchk != null && attrchk is XmlRpcMemberAttribute) - { - string mmbr = ((XmlRpcMemberAttribute)attrchk).Member; - if (mmbr != "") - member = mmbr; - } - MappingActions memberActions = MemberMappingActions(o.GetType(), - fi.Name, structActions); - if (fi.GetValue(o) == null) - { - if (memberActions.NullMappingAction == NullMappingAction.Ignore) - continue; - else if (memberActions.NullMappingAction == NullMappingAction.Error) - throw new XmlRpcMappingSerializeException(@"Member """ + member + - @""" of struct """ + o.GetType().Name + @""" cannot be null."); - } - xtw.WriteStartElement("", "member", ""); - WriteFullElementString(xtw, "name", member); - Serialize(xtw, fi.GetValue(o), memberActions, nestedObjs); - WriteFullEndElement(xtw); + return new XmlWriterSettings + { + Indent = true, + IndentChars = new string(' ', Indentation), + Encoding = XmlEncoding, + NewLineHandling = NewLineHandling.None, + }; } - else if (mi.MemberType == MemberTypes.Property) + else { - PropertyInfo pi = (PropertyInfo)mi; - string member = pi.Name; - Attribute attrchk = Attribute.GetCustomAttribute(pi, - typeof(XmlRpcMemberAttribute)); - if (attrchk != null && attrchk is XmlRpcMemberAttribute) - { - string mmbr = ((XmlRpcMemberAttribute)attrchk).Member; - if (mmbr != "") - member = mmbr; - } - MappingActions memberActions = MemberMappingActions(o.GetType(), - pi.Name, structActions); - if (pi.GetValue(o, null) == null) - { - if (memberActions.NullMappingAction == NullMappingAction.Ignore) - continue; - else if (memberActions.NullMappingAction == NullMappingAction.Error) - throw new XmlRpcMappingSerializeException(@"Member """ + member + - @""" of struct """ + o.GetType().Name + @""" cannot be null."); - } - xtw.WriteStartElement("", "member", ""); - WriteFullElementString(xtw, "name", member); - Serialize(xtw, pi.GetValue(o, null), memberActions, nestedObjs); - WriteFullEndElement(xtw); + return new XmlWriterSettings + { + Indent = false, + Encoding = XmlEncoding + }; } - } - WriteFullEndElement(xtw); } - else if (xType == XmlRpcType.tVoid) - WriteFullElementString(xtw, "string", ""); - else if (xType == XmlRpcType.tNil) + + protected void WriteFullEndElement(XmlWriter xtw) { - xtw.WriteStartElement("nil"); - WriteFullEndElement(xtw); + if (UseEmptyElementTags) { xtw.WriteEndElement(); } else { xtw.WriteFullEndElement(); } } - else - throw new XmlRpcUnsupportedTypeException(o.GetType()); - WriteFullEndElement(xtw); - } - catch (System.NullReferenceException) - { - throw new XmlRpcNullReferenceException("Attempt to serialize data " - + "containing null reference"); - } - finally - { - nestedObjs.RemoveAt(nestedObjs.Count - 1); - } - } - private void SerializeString(XmlWriter xtw, Object o) - { - try - { - if (UseStringTag) + protected void WriteFullElementString(XmlWriter xtw, string name, string value) { - WriteFullElementString(xtw, "string", (string)o); + if (UseEmptyElementTags) + xtw.WriteElementString(name, value); + else + { + xtw.WriteStartElement(name); + xtw.WriteString(value); + xtw.WriteFullEndElement(); + } } - else - xtw.WriteString((string)o); - } - catch (ArgumentException ex) - { - string msg = string.Format("Unable to serialize string to XML: {0}", ex.Message); - throw new XmlRpcException(msg, ex); - } - } - private Object SerializeInt64(XmlWriter xtw, Object o, MappingActions mappingActions) - { - if (o.GetType().IsEnum) - { - if (mappingActions.EnumMapping == EnumMapping.String) + string StackDump(MappingStack parseStack) { - SerializeString(xtw, o.ToString()); + StringBuilder sb = new StringBuilder(); + foreach (string elem in parseStack) + { + sb.Insert(0, elem); + sb.Insert(0, " : "); + } + sb.Insert(0, parseStack.MappingType); + sb.Insert(0, "["); + sb.Append("]"); + return sb.ToString(); } - else - o = Convert.ToInt64(o); - } - WriteFullElementString(xtw, "i8", o.ToString()); - return o; - } - private Object SerializeInt32(XmlWriter xtw, Object o, MappingActions mappingActions) - { - if (o.GetType().IsEnum) - { - if (mappingActions.EnumMapping == EnumMapping.String) + public bool IsStructParamsMethod(MethodInfo mi) { - SerializeString(xtw, o.ToString()); - return o; + if (mi == null) + return false; + bool ret = false; + Attribute attr = Attribute.GetCustomAttribute(mi, + typeof(XmlRpcMethodAttribute)); + if (attr != null) + { + XmlRpcMethodAttribute mattr = (XmlRpcMethodAttribute)attr; + ret = mattr.StructParams; + } + return ret; } - else - o = Convert.ToInt32(o); - } - if (UseIntTag) - WriteFullElementString(xtw, "int", o.ToString()); - else - WriteFullElementString(xtw, "i4", o.ToString()); - return o; - } - void BuildArrayXml( - XmlWriter xtw, - Array ary, - int CurRank, - int[] indices, - MappingActions mappingActions, - List nestedObjs) - { - xtw.WriteStartElement("", "array", ""); - xtw.WriteStartElement("", "data", ""); - if (CurRank < (ary.Rank - 1)) - { - for (int i = 0; i < ary.GetLength(CurRank); i++) + MappingActions MemberMappingActions( + Type type, + string memberName, + MappingActions currentActions) { - indices[CurRank] = i; - xtw.WriteStartElement("", "value", ""); - BuildArrayXml(xtw, ary, CurRank + 1, indices, mappingActions, nestedObjs); - WriteFullEndElement(xtw); + // if struct member has mapping action attribute, override the current + // mapping action else just return the current action + if (type == null) + return currentActions; + MemberInfo[] mis = type.GetMember(memberName); + if (mis == null || mis.Length == 0) + return currentActions; + var ret = GetMappingActions(mis[0], currentActions); + return ret; } - } - else - { - for (int i = 0; i < ary.GetLength(CurRank); i++) + + protected MappingActions GetTypeMappings(MethodInfo mi, MappingActions mappingActions) { - indices[CurRank] = i; - Serialize(xtw, ary.GetValue(indices), mappingActions, nestedObjs); + if (mi != null) + { + var declaringType = mi != null ? mi.DeclaringType : null; + foreach (Type itf in declaringType.GetInterfaces()) + { + mappingActions = GetMappingActions(itf, mappingActions); + } + mappingActions = GetMappingActions(declaringType, mappingActions); + } + return mappingActions; } - } - WriteFullEndElement(xtw); - WriteFullEndElement(xtw); - } - - struct FaultStruct - { - public int faultCode; - public string faultString; - } - struct FaultStructStringCode - { - public string faultCode; - public string faultString; - } - - public void SerializeFaultResponse( - Stream stm, - XmlRpcFaultException faultEx) - { - FaultStruct fs; - fs.faultCode = faultEx.FaultCode; - fs.faultString = faultEx.FaultString; - XmlWriter xtw = XmlRpcXmlWriter.Create(stm, XmlRpcFormatSettings); - xtw.WriteStartDocument(); - xtw.WriteStartElement("", "methodResponse", ""); - xtw.WriteStartElement("", "fault", ""); - Serialize(xtw, fs, new MappingActions { NullMappingAction = NullMappingAction.Error }); - WriteFullEndElement(xtw); - WriteFullEndElement(xtw); - xtw.Flush(); - } - - protected XmlWriterSettings ConfigureXmlFormat() - { - if (UseIndentation) - { - return new XmlWriterSettings - { - Indent = true, - IndentChars = new string(' ', Indentation), - Encoding = XmlEncoding, - NewLineHandling = NewLineHandling.None, - }; - } - else - { - return new XmlWriterSettings + protected MappingActions GetMappingActions(ICustomAttributeProvider cap, + MappingActions mappingActions) { - Indent = false, - Encoding = XmlEncoding - }; - } - } - - protected void WriteFullEndElement(XmlWriter xtw) - { - if (UseEmptyElementTags) { xtw.WriteEndElement(); } else { xtw.WriteFullEndElement(); } - } - - protected void WriteFullElementString(XmlWriter xtw, string name, string value) - { - if (UseEmptyElementTags) - xtw.WriteElementString(name, value); - else - { - xtw.WriteStartElement(name); - xtw.WriteString(value); - xtw.WriteFullEndElement(); - } - } - - string StackDump(MappingStack parseStack) - { - StringBuilder sb = new StringBuilder(); - foreach (string elem in parseStack) - { - sb.Insert(0, elem); - sb.Insert(0, " : "); - } - sb.Insert(0, parseStack.MappingType); - sb.Insert(0, "["); - sb.Append("]"); - return sb.ToString(); - } - - public bool IsStructParamsMethod(MethodInfo mi) - { - if (mi == null) - return false; - bool ret = false; - Attribute attr = Attribute.GetCustomAttribute(mi, - typeof(XmlRpcMethodAttribute)); - if (attr != null) - { - XmlRpcMethodAttribute mattr = (XmlRpcMethodAttribute)attr; - ret = mattr.StructParams; - } - return ret; - } - - MappingActions MemberMappingActions( - Type type, - string memberName, - MappingActions currentActions) - { - // if struct member has mapping action attribute, override the current - // mapping action else just return the current action - if (type == null) - return currentActions; - MemberInfo[] mis = type.GetMember(memberName); - if (mis == null || mis.Length == 0) - return currentActions; - var ret = GetMappingActions(mis[0], currentActions); - return ret; - } + if (cap == null) + return mappingActions; + var ret = new MappingActions + { + EnumMapping = mappingActions.EnumMapping, + NullMappingAction = mappingActions.NullMappingAction + }; + var nullMappingAttr = GetAttribute(cap); + if (nullMappingAttr != null) + ret.NullMappingAction = nullMappingAttr.Action; + else + { + // check for missing mapping attribute for backwards compatibility + var missingAttr = GetAttribute(cap); + if (missingAttr != null) + ret.NullMappingAction = MapToNullMappingAction(missingAttr.Action); + } + var enumAttr = GetAttribute(cap); + if (enumAttr != null) + ret.EnumMapping = ((XmlRpcEnumMappingAttribute)enumAttr).Mapping; + return ret; + } - protected MappingActions GetTypeMappings(MethodInfo mi, MappingActions mappingActions) - { - if (mi != null) - { - var declaringType = mi != null ? mi.DeclaringType : null; - foreach (Type itf in declaringType.GetInterfaces()) + static T GetAttribute(ICustomAttributeProvider cap) where T : class { - mappingActions = GetMappingActions(itf, mappingActions); + var attrs = cap.GetCustomAttributes(typeof(T), true); + return attrs.Length == 0 ? null : attrs[0] as T; } - mappingActions = GetMappingActions(declaringType, mappingActions); - } - return mappingActions; - } - - protected MappingActions GetMappingActions(ICustomAttributeProvider cap, - MappingActions mappingActions) - { - if (cap == null) - return mappingActions; - var ret = new MappingActions - { - EnumMapping = mappingActions.EnumMapping, - NullMappingAction = mappingActions.NullMappingAction - }; - var nullMappingAttr = GetAttribute(cap); - if (nullMappingAttr != null) - ret.NullMappingAction = nullMappingAttr.Action; - else - { - // check for missing mapping attribute for backwards compatibility - var missingAttr = GetAttribute(cap); - if (missingAttr != null) - ret.NullMappingAction = MapToNullMappingAction(missingAttr.Action); - } - var enumAttr = GetAttribute(cap); - if (enumAttr != null) - ret.EnumMapping = ((XmlRpcEnumMappingAttribute)enumAttr).Mapping; - return ret; - } - static T GetAttribute(ICustomAttributeProvider cap) where T : class - { - var attrs = cap.GetCustomAttributes(typeof(T), true); - return attrs.Length == 0 ? null : attrs[0] as T; - } - - static NullMappingAction MapToNullMappingAction(MappingAction missingMappingAction) - { - switch (missingMappingAction) - { - case MappingAction.Error: - return NullMappingAction.Error; - case MappingAction.Ignore: - return NullMappingAction.Ignore; - default: - throw new XmlRpcException("Unexpected missingMappingAction in MapToNullMappingAction"); - } + static NullMappingAction MapToNullMappingAction(MappingAction missingMappingAction) + { + switch (missingMappingAction) + { + case MappingAction.Error: + return NullMappingAction.Error; + case MappingAction.Ignore: + return NullMappingAction.Ignore; + default: + throw new XmlRpcException("Unexpected missingMappingAction in MapToNullMappingAction"); + } + } } - } }