Initial develop commit

Initial develop commit
This commit is contained in:
Saúl Piña
2016-03-06 18:12:26 -05:00
parent 07cb83b5b9
commit ef79a1c2c1
28 changed files with 3637 additions and 2 deletions

View File

@@ -0,0 +1,49 @@
////
/// ComponentInfo.cs
///
/// Copyright (c) 2016 Saúl Piña <sauljabin@gmail.com>.
///
/// This file is part of xmlrpcwsc.
///
/// xmlrpcwsc is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Lesser General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// xmlrpcwsc is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Lesser General Public License for more details.
///
/// You should have received a copy of the GNU Lesser General Public License
/// along with xmlrpcwsc. If not, see <http://www.gnu.org/licenses/>.
////
using System;
using System.Collections.Generic;
namespace XmlRpc {
/// <summary>
/// Component info
/// </summary>
public sealed class ComponentInfo {
public static readonly string Name = "XML-RPC Web Service Client";
public static readonly string ComponentName = "xmlrpcwsc";
public static readonly string Version = "1.3.0";
/// <summary>
/// To the dictionary
/// </summary>
/// <returns>The dictionary</returns>
public static Dictionary<string, string> ToDictionary() {
Dictionary<string, string> info = new Dictionary<string, string>();
info.Add("Name", Name);
info.Add("ComponentName", ComponentName);
info.Add("Version", Version);
return info;
}
}
}

View File

@@ -0,0 +1,41 @@
////
/// FactoryException.cs
///
/// Copyright (c) 2016 Saúl Piña <sauljabin@gmail.com>.
///
/// This file is part of xmlrpcwsc.
///
/// xmlrpcwsc is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Lesser General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// xmlrpcwsc is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Lesser General Public License for more details.
///
/// You should have received a copy of the GNU Lesser General Public License
/// along with xmlrpcwsc. If not, see <http://www.gnu.org/licenses/>.
////
using System;
namespace XmlRpc {
/// <summary>
/// Factory exception
/// </summary>
public class FactoryException : Exception {
public FactoryException() {
}
public FactoryException(string message) : base(message) {
}
public FactoryException(string message, Exception inner) : base(message, inner) {
}
}
}

View File

@@ -0,0 +1,48 @@
////
/// AssemblyInfo.cs
///
/// Copyright (c) 2016 Saúl Piña <sauljabin@gmail.com>.
///
/// This file is part of xmlrpcwsc.
///
/// xmlrpcwsc is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Lesser General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// xmlrpcwsc is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Lesser General Public License for more details.
///
/// You should have received a copy of the GNU Lesser General Public License
/// along with xmlrpcwsc. If not, see <http://www.gnu.org/licenses/>.
////
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("XmlRpc Web Service Client")]
[assembly: AssemblyDescription("XmlRpc Web Service Client")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("xmlrpcwsc")]
[assembly: AssemblyCopyright("Copyright (c) 2016 Saúl Piña")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.3.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

156
xmlrpcwsc/RequestFactory.cs Normal file
View File

@@ -0,0 +1,156 @@
////
/// RequestFactory.cs
///
/// Copyright (c) 2016 Saúl Piña <sauljabin@gmail.com>.
///
/// This file is part of xmlrpcwsc.
///
/// xmlrpcwsc is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Lesser General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// xmlrpcwsc is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Lesser General Public License for more details.
///
/// You should have received a copy of the GNU Lesser General Public License
/// along with xmlrpcwsc. If not, see <http://www.gnu.org/licenses/>.
////
using System;
using System.Xml;
using System.Collections.Generic;
namespace XmlRpc {
/// <summary>
/// XML-RPC request factory
/// </summary>
public class RequestFactory {
/// <summary>
/// Builds the xml request
/// </summary>
/// <returns>The xml request</returns>
/// <param name="request">Request</param>
public static XmlDocument BuildRequest(XmlRpcRequest request) {
XmlDocument doc = new XmlDocument();
XmlElement xmlMethodCall = doc.CreateElement("methodCall");
doc.AppendChild(xmlMethodCall);
XmlElement xmlMethodName = doc.CreateElement("methodName");
xmlMethodName.InnerText = request.MethodName ?? "";
xmlMethodCall.AppendChild(xmlMethodName);
XmlElement xmlParams = doc.CreateElement("params");
xmlMethodCall.AppendChild(xmlParams);
if (request.GetParamsCount() <= 0)
return doc;
List<object> parameters = request.GetParams();
foreach (object parameter in parameters) {
XmlElement xmlParam = doc.CreateElement("param");
xmlParams.AppendChild(xmlParam);
xmlParam.AppendChild(doc.ImportNode(BuildXmlValue(parameter), true));
}
return doc;
}
/// <summary>
/// Builds the xml value
/// </summary>
/// <returns>The xml value</returns>
/// <param name="value">Value</param>
private static XmlElement BuildXmlValue(object value) {
XmlDocument doc = new XmlDocument();
XmlElement xmlValue = doc.CreateElement("value");
if (value is bool) {
XmlElement xmlType = doc.CreateElement("boolean");
xmlType.InnerText = (bool)value ? "1" : "0";
xmlValue.AppendChild(xmlType);
} else if (value is int) {
XmlElement xmlType = doc.CreateElement("int");
xmlType.InnerText = value.ToString();
xmlValue.AppendChild(xmlType);
} else if (value is double) {
XmlElement xmlType = doc.CreateElement("double");
xmlType.InnerText = value.ToString();
xmlValue.AppendChild(xmlType);
} else if (value is DateTime) {
XmlElement xmlType = doc.CreateElement("dateTime.iso8601");
// EXAMPLE 19980717T14:08:55
xmlType.InnerText = string.Format("{0:yyyyMMdd'T'HH:mm:ss}", value);
xmlValue.AppendChild(xmlType);
} else if (value is byte[]) {
XmlElement xmlType = doc.CreateElement("base64");
xmlType.InnerText = Convert.ToBase64String((byte[])value);
xmlValue.AppendChild(xmlType);
} else if (value is Dictionary<string, object>) {
XmlElement xmlType = doc.CreateElement("struct");
xmlValue.AppendChild(xmlType);
foreach (KeyValuePair<string, object> item in (Dictionary<string, object>) value) {
XmlElement xmlMember = doc.CreateElement("member");
xmlType.AppendChild(xmlMember);
XmlElement xmlName = doc.CreateElement("name");
xmlName.InnerText = item.Key;
xmlMember.AppendChild(xmlName);
xmlMember.AppendChild(doc.ImportNode(BuildXmlValue(item.Value), true));
}
} else if (value is List<object>) {
XmlElement xmlType = doc.CreateElement("array");
xmlValue.AppendChild(xmlType);
XmlElement xmlData = doc.CreateElement("data");
xmlType.AppendChild(xmlData);
foreach (object item in (List<object>) value) {
xmlData.AppendChild(doc.ImportNode(BuildXmlValue(item), true));
}
} else if (value is object[]) {
XmlElement xmlType = doc.CreateElement("array");
xmlValue.AppendChild(xmlType);
XmlElement xmlData = doc.CreateElement("data");
xmlType.AppendChild(xmlData);
foreach (object item in (object[]) value) {
xmlData.AppendChild(doc.ImportNode(BuildXmlValue(item), true));
}
} else {
XmlElement xmlType = doc.CreateElement("string");
xmlType.InnerText = value.ToString();
xmlValue.AppendChild(xmlType);
}
return xmlValue;
}
}
}

View File

@@ -0,0 +1,152 @@
////
/// ResponseFactory.cs
///
/// Copyright (c) 2016 Saúl Piña <sauljabin@gmail.com>.
///
/// This file is part of xmlrpcwsc.
///
/// xmlrpcwsc is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Lesser General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// xmlrpcwsc is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Lesser General Public License for more details.
///
/// You should have received a copy of the GNU Lesser General Public License
/// along with xmlrpcwsc. If not, see <http://www.gnu.org/licenses/>.
////
using System;
using System.Xml;
using System.Collections.Generic;
using System.Globalization;
using System.Collections;
namespace XmlRpc {
/// <summary>
/// XML-RPC response factory
/// </summary>
public class ResponseFactory {
public static XmlRpcResponse BuildResponse(XmlDocument response) {
XmlNodeList xmlMethodResponseList = response.GetElementsByTagName("methodResponse");
if (xmlMethodResponseList.Count <= 0) {
throw new FactoryException("XML file malformed, no tag methodResponse");
}
XmlElement xmlMethodResponse = (XmlElement)xmlMethodResponseList.Item(0);
if (xmlMethodResponse.FirstChild == null) {
throw new FactoryException("XML file malformed, methodResponse child");
}
XmlElement xmlFirst = (XmlElement)xmlMethodResponse.FirstChild;
if (xmlFirst.Name.Equals("fault")) {
object objectValue = BuildObjectValue((XmlElement)xmlFirst.FirstChild);
Dictionary<string, object> faultStruct = (Dictionary<string, object>)objectValue;
int faultCode = (int)faultStruct["faultCode"];
string faultString = (string)faultStruct["faultString"];
return new XmlRpcResponse(faultCode, faultString, faultStruct);
} else if (xmlFirst.Name.Equals("params")) {
XmlElement xmlParam = (XmlElement)xmlFirst.FirstChild;
if (xmlParam == null || !xmlParam.Name.Equals("param")) {
throw new FactoryException("XML file malformed, no tag param");
}
return new XmlRpcResponse(BuildObjectValue((XmlElement)xmlParam.FirstChild));
} else {
throw new FactoryException("XML file malformed, methodResponse child");
}
}
private static object BuildObjectValue(XmlElement value) {
if (value == null || !value.Name.Equals("value")) {
throw new FactoryException("XML file malformed, need value tag");
}
XmlElement xmlType = (XmlElement)value.FirstChild;
if (xmlType == null) {
throw new FactoryException("XML file malformed, need type tag in value tag");
}
string stringType = xmlType.Name;
if (stringType.Equals("int") || stringType.Equals("i4")) {
return int.Parse(xmlType.InnerText);
} else if (stringType.Equals("boolean")) {
return xmlType.InnerText.Equals("1");
} else if (stringType.Equals("double")) {
return double.Parse(xmlType.InnerText);
} else if (stringType.Equals("base64")) {
return Convert.FromBase64String(xmlType.InnerText);
} else if (stringType.Equals("dateTime.iso8601") || stringType.Equals("dateTime") || stringType.Equals("date")) {
// EXAMPLE 19980717T14:08:55
return DateTime.ParseExact(xmlType.InnerText, "yyyyMMdd'T'HH:mm:ss", CultureInfo.InvariantCulture);
} else if (stringType.Equals("array")) {
List<object> objectValue = new List<object>();
XmlElement xmlData = (XmlElement)xmlType.FirstChild;
if (xmlData == null || !xmlData.Name.Equals("data")) {
throw new FactoryException("XML file malformed, need data tag in array tag");
}
IEnumerator iteValues = xmlData.GetEnumerator();
while (iteValues.MoveNext()) {
XmlElement xmlValue = (XmlElement)iteValues.Current;
objectValue.Add(BuildObjectValue(xmlValue));
}
return objectValue;
} else if (stringType.Equals("struct")) {
Dictionary<string, object> objectValue = new Dictionary<string, object>();
IEnumerator iteMember = xmlType.GetEnumerator();
while (iteMember.MoveNext()) {
XmlElement xmlMember = (XmlElement)iteMember.Current;
IEnumerator iteMemberValues = xmlMember.GetEnumerator();
string name = "";
object innerObject = null;
while (iteMemberValues.MoveNext()) {
XmlElement xmlMemberValue = (XmlElement)iteMemberValues.Current;
if (xmlMemberValue.Name == "name") {
name = xmlMemberValue.InnerText;
} else if (xmlMemberValue.Name == "value") {
innerObject = BuildObjectValue(xmlMemberValue);
}
}
if (innerObject != null && !string.IsNullOrEmpty(name))
objectValue.Add(name, innerObject);
}
return objectValue;
} else {
return xmlType.InnerText;
}
}
}
}

View File

@@ -0,0 +1,340 @@
////
/// WebServiceConnection.cs
///
/// Copyright (c) 2016 Saúl Piña <sauljabin@gmail.com>.
///
/// This file is part of xmlrpcwsc.
///
/// xmlrpcwsc is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Lesser General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// xmlrpcwsc is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Lesser General Public License for more details.
///
/// You should have received a copy of the GNU Lesser General Public License
/// along with xmlrpcwsc. If not, see <http://www.gnu.org/licenses/>.
////
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Threading;
namespace XmlRpc {
/// <summary>
/// This class send a stream data xml.
/// </summary>
public class WebServiceConnection {
public static readonly string DefaultContentType = "text/xml; charset=UTF-8";
public static readonly string DefaultRequestMethod = "POST";
public static readonly int DefaultTimeout = 5000;
public static readonly int DefaultAttempts = 1;
public static readonly int DefaultAttemptsTimeout = 500;
public static readonly int DefaultConnectionLimit = 2;
public static readonly ICredentials DefaultCredentials = CredentialCache.DefaultCredentials;
public static readonly IWebProxy DefaultWebProxy = WebRequest.DefaultWebProxy;
private int connectionLimit;
private int attempts;
private int attemptsTimeout;
private int timeout;
private string appName;
/// <summary>
/// For connection simultaneously
/// </summary>
public int ConnectionLimit {
get {
return connectionLimit;
}
set {
if (value <= 0)
connectionLimit = DefaultConnectionLimit;
else
connectionLimit = value;
}
}
/// <summary>
/// Attempts for request
/// </summary>
public int Attempts {
get {
return attempts;
}
set {
if (value <= 0)
attempts = DefaultAttempts;
else
attempts = value;
}
}
/// <summary>
/// Gets or sets the attempts timeout. Default: WebServiceConnection.DefaultAttemptsTimeout
/// </summary>
/// <value>The attempts timeout</value>
public int AttemptsTimeout {
get {
return attemptsTimeout;
}
set {
if (value <= 0)
attemptsTimeout = DefaultTimeout;
else
attemptsTimeout = value;
}
}
/// <summary>
/// Timeout for request. Default: WebServiceConnection.DefaultTimeout
/// </summary>
public int Timeout {
get {
return timeout;
}
set {
if (value <= 0)
timeout = DefaultTimeout;
else
timeout = value;
}
}
/// <summary>
/// Gets or sets the name of the app
/// </summary>
/// <value>The name of the app</value>
public string AppName {
get {
return appName;
}
set {
if (appName == null)
appName = "";
else
appName = value;
}
}
/// <summary>
/// total Attempts for request
/// </summary>
public int AttemptsRequest {
get;
protected set;
}
/// <summary>
/// Total time for request
/// </summary>
public int TimeRequest {
get;
protected set;
}
/// <summary>
/// Proxy. Default: WebServiceConnection.DefaultProxy
/// </summary>
public IWebProxy Proxy {
get;
set;
}
/// <summary>
/// Credentials. Default: WebServiceConnection.DefaultCredentials
/// </summary>
public ICredentials Credentials {
get;
set;
}
/// <summary>
/// Url for connect
/// </summary>
public string Url {
get;
set;
}
/// <summary>
/// Path for connect
/// </summary>
public string Path {
get;
set;
}
/// <summary>
/// Data typ. Default: WebServiceConnection.DefaultContentType
/// </summary>
public string ContentType {
get;
set;
}
/// <summary>
/// Method for request. Default: WebServiceConnection.DefaultRequestMethod
/// </summary>
public string RequestMethod {
get;
set;
}
/// <summary>
/// Gets the user agent
/// </summary>
/// <returns>The user agent</returns>
public string GetUserAgent() {
return string.Format("{0} ({1}/{2}/{3}/{4}) {5}", ComponentInfo.Name, ComponentInfo.ComponentName, ComponentInfo.Version, ".NET", Environment.OSVersion, AppName).Trim();
}
/// <summary>
/// Build the Url for WebService Connection
/// </summary>
/// <returns>Url for create HttpWebRequest</returns>
private string GetWebServiceUrl() {
if (Path == null)
return Url;
string urlTemp = Url;
if (urlTemp.EndsWith("/"))
urlTemp = urlTemp.Substring(0, urlTemp.Length - 1);
string path = Path;
if (path.StartsWith("/"))
path = path.Substring(1);
return String.Format("{0}/{1}", urlTemp, path);
}
/// <summary>
/// Default constructor
/// </summary>
public WebServiceConnection() {
Timeout = DefaultTimeout;
ContentType = DefaultContentType;
RequestMethod = DefaultRequestMethod;
Credentials = DefaultCredentials;
Attempts = DefaultAttempts;
ConnectionLimit = DefaultConnectionLimit;
AttemptsTimeout = DefaultAttemptsTimeout;
Proxy = DefaultWebProxy;
Url = "";
AppName = "";
}
/// <summary>
/// FOR SSL
/// </summary>
/// <param name="sender"></param>
/// <param name="certificate"></param>
/// <param name="chain"></param>
/// <param name="sslPolicyErrors"></param>
/// <returns></returns>
private bool OnValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
return true;
}
/// <summary>
/// Send data in xml format
/// </summary>
/// <param name="dataRequest">Xml Document</param>
/// <returns>Xml Response</returns>
public XmlDocument SendRequest(XmlDocument dataRequest) {
return SendRequest(dataRequest.OuterXml);
}
/// <summary>
/// Send string data
/// </summary>
/// <param name="dataRequest">Data</param>
/// <returns>Xml Response</returns>
public XmlDocument SendRequest(string dataRequest) {
if (string.IsNullOrEmpty(Url))
throw new WebServiceException("URL must be different than empty or null");
ServicePointManager.ServerCertificateValidationCallback = OnValidateCertificate;
ServicePointManager.DefaultConnectionLimit = ConnectionLimit;
ServicePointManager.Expect100Continue = false;
TimeSpan startTime = TimeSpan.FromMilliseconds(Environment.TickCount);
AttemptsRequest = 0;
bool successful = false;
string dataResponse = "";
XmlDocument xmlDocument = new XmlDocument();
while (!successful) {
AttemptsRequest++;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GetWebServiceUrl());
request.Timeout = Timeout;
request.KeepAlive = false;
request.Method = RequestMethod;
request.UserAgent = GetUserAgent();
byte[] bytesData = Encoding.UTF8.GetBytes(dataRequest);
request.ContentType = ContentType;
request.ContentLength = bytesData.Length;
if (Proxy != null)
request.Proxy = Proxy;
if (Credentials != null)
request.Credentials = Credentials;
try {
Stream requestStreamData = request.GetRequestStream();
requestStreamData.Write(bytesData, 0, bytesData.Length);
requestStreamData.Close();
WebResponse response = request.GetResponse();
Stream responseStreamData = response.GetResponseStream();
StreamReader readResponseStreamData = new StreamReader(responseStreamData, Encoding.UTF8);
dataResponse = readResponseStreamData.ReadToEnd();
readResponseStreamData.Close();
responseStreamData.Close();
response.Close();
xmlDocument.LoadXml(dataResponse);
successful = true;
} catch (Exception e) {
if (AttemptsRequest >= Attempts) {
TimeRequest = (int)TimeSpan.FromMilliseconds(Environment.TickCount).Subtract(startTime).Duration().TotalMilliseconds;
if (e.GetType().Equals(typeof(WebException))) {
WebException we = (WebException)e;
if (we.Status == WebExceptionStatus.Timeout) {
throw new WebServiceTimeoutException("Timeout exception, operation has expired", e);
}
}
throw new WebServiceException("Error sending request", e);
} else {
Thread.Sleep(AttemptsTimeout);
continue;
}
}
}
TimeRequest = (int)TimeSpan.FromMilliseconds(Environment.TickCount).Subtract(startTime).Duration().TotalMilliseconds;
return xmlDocument;
}
}
}

View File

@@ -0,0 +1,41 @@
////
/// WebServiceException.cs
///
/// Copyright (c) 2016 Saúl Piña <sauljabin@gmail.com>.
///
/// This file is part of xmlrpcwsc.
///
/// xmlrpcwsc is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Lesser General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// xmlrpcwsc is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Lesser General Public License for more details.
///
/// You should have received a copy of the GNU Lesser General Public License
/// along with xmlrpcwsc. If not, see <http://www.gnu.org/licenses/>.
////
using System;
namespace XmlRpc {
/// <summary>
/// Web service exception
/// </summary>
public class WebServiceException : Exception {
public WebServiceException() {
}
public WebServiceException(string message) : base(message) {
}
public WebServiceException(string message, Exception inner) : base(message, inner) {
}
}
}

View File

@@ -0,0 +1,42 @@
////
/// WebServiceTimeoutException.cs
///
/// Copyright (c) 2016 Saúl Piña <sauljabin@gmail.com>.
///
/// This file is part of xmlrpcwsc.
///
/// xmlrpcwsc is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Lesser General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// xmlrpcwsc is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Lesser General Public License for more details.
///
/// You should have received a copy of the GNU Lesser General Public License
/// along with xmlrpcwsc. If not, see <http://www.gnu.org/licenses/>.
////
using System;
using System.Collections.Generic;
using System.Text;
namespace XmlRpc {
/// <summary>
/// Web service timeout exception
/// </summary>
public class WebServiceTimeoutException : WebServiceException {
public WebServiceTimeoutException() {
}
public WebServiceTimeoutException(string message) : base(message) {
}
public WebServiceTimeoutException(string message, Exception inner) : base(message, inner) {
}
}
}

135
xmlrpcwsc/XmlRpcClient.cs Normal file
View File

@@ -0,0 +1,135 @@
////
/// XmlRpcClient.cs
///
/// Copyright (c) 2016 Saúl Piña <sauljabin@gmail.com>.
///
/// This file is part of xmlrpcwsc.
///
/// xmlrpcwsc is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Lesser General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// xmlrpcwsc is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Lesser General Public License for more details.
///
/// You should have received a copy of the GNU Lesser General Public License
/// along with xmlrpcwsc. If not, see <http://www.gnu.org/licenses/>.
////
using System;
using System.Xml;
using System.IO;
using System.Text;
using System.Collections.Generic;
namespace XmlRpc {
/// <summary>
/// XML-RPC client
/// </summary>
public class XmlRpcClient : WebServiceConnection {
protected XmlDocument xmlRequest;
protected XmlDocument xmlResponse;
protected XmlRpcRequest request;
protected XmlRpcResponse response;
/// <summary>
/// Gets the xml request
/// </summary>
/// <returns>The xml request</returns>
public XmlDocument GetXmlRequest() {
return xmlRequest;
}
/// <summary>
/// Gets the xml response
/// </summary>
/// <returns>The xml response</returns>
public XmlDocument GetXmlResponse() {
return xmlResponse;
}
/// <summary>
/// Writes the request
/// </summary>
/// <param name="fileName">File name</param>
public void WriteRequest(String fileName) {
TextWriter streamWriter = new StreamWriter(fileName, false, Encoding.UTF8);
WriteRequest(streamWriter);
}
/// <summary>
/// Writes the request
/// </summary>
/// <param name="outStream">Out stream</param>
public void WriteRequest(TextWriter outStream) {
xmlRequest.Save(outStream);
}
/// <summary>
/// Writes the response
/// </summary>
/// <param name="fileName">File name</param>
public void WriteResponse(String fileName) {
TextWriter streamWriter = new StreamWriter(fileName, false, Encoding.UTF8);
WriteResponse(streamWriter);
}
/// <summary>
/// Writes the response
/// </summary>
/// <param name="outStream">Out stream</param>
public void WriteResponse(TextWriter outStream) {
xmlResponse.Save(outStream);
}
/// <summary>
/// Execute the specified methodName and parameters
/// </summary>
/// <param name="methodName">Method name</param>
/// <param name="parameters">Parameters</param>
public XmlRpcResponse Execute(string methodName, List<object> parameters){
return Execute(new XmlRpcRequest(methodName, parameters));
}
/// <summary>
/// Execute the specified methodName and parameters
/// </summary>
/// <param name="methodName">Method name</param>
/// <param name="parameters">Parameters</param>
public XmlRpcResponse Execute(string methodName, object[] parameters){
return Execute(new XmlRpcRequest(methodName, parameters));
}
/// <summary>
/// Execute the specified methodName
/// </summary>
/// <param name="methodName">Method name</param>
public XmlRpcResponse Execute(string methodName){
return Execute(new XmlRpcRequest(methodName));
}
/// <summary>
/// Execute the specified request
/// </summary>
/// <param name="request">Request</param>
public virtual XmlRpcResponse Execute(XmlRpcRequest request){
this.request = request;
XmlDocument xmlRequest = RequestFactory.BuildRequest(request);
this.xmlRequest = xmlRequest;
XmlDocument xmlResponse = SendRequest(xmlRequest);
this.xmlResponse = xmlResponse;
this.response = ResponseFactory.BuildResponse(xmlResponse);
return response;
}
}
}

View File

@@ -0,0 +1,85 @@
////
/// XmlRpcParameter.cs
///
/// Copyright (c) 2016 Saúl Piña <sauljabin@gmail.com>.
///
/// This file is part of xmlrpcwsc.
///
/// xmlrpcwsc is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Lesser General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// xmlrpcwsc is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Lesser General Public License for more details.
///
/// You should have received a copy of the GNU Lesser General Public License
/// along with xmlrpcwsc. If not, see <http://www.gnu.org/licenses/>.
////
using System;
using System.Collections.Generic;
namespace XmlRpc {
/// <summary>
/// XML-RPC Parameter helper
/// </summary>
public class XmlRpcParameter {
/// <summary>
/// Empty the struct.
/// </summary>
/// <returns>The struct</returns>
public static Dictionary<string,object> EmptyStruct() {
return new Dictionary<string,object>();
}
/// <summary>
/// Empty array
/// </summary>
/// <returns>The array</returns>
public static List<object> EmptyArray() {
return new List<object>();
}
/// <summary>
/// As array
/// </summary>
/// <returns>The array.</returns>
/// <param name="list">List.</param>
public static List<object> AsArray(params object[] list) {
List<object> listReturn = new List<object>();
listReturn.AddRange(list);
return listReturn;
}
/// <summary>
/// As struct
/// </summary>
/// <returns>The struct</returns>
/// <param name="list">List</param>
public static Dictionary<string, object> AsStruct(params KeyValuePair<string,object>[] list) {
Dictionary<string,object> dictReturn = new Dictionary<string,object>();
foreach (KeyValuePair<string,object> pair in list) {
dictReturn.Add(pair.Key, pair.Value);
}
return dictReturn;
}
/// <summary>
/// As member
/// </summary>
/// <returns>The member</returns>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
public static KeyValuePair<string,object> AsMember(string key, object value) {
KeyValuePair<string,object> pairReturn = new KeyValuePair<string, object>(key, value);
return pairReturn;
}
}
}

177
xmlrpcwsc/XmlRpcRequest.cs Normal file
View File

@@ -0,0 +1,177 @@
////
/// XmlRpcRequest.cs
///
/// Copyright (c) 2016 Saúl Piña <sauljabin@gmail.com>.
///
/// This file is part of xmlrpcwsc.
///
/// xmlrpcwsc is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Lesser General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// xmlrpcwsc is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Lesser General Public License for more details.
///
/// You should have received a copy of the GNU Lesser General Public License
/// along with xmlrpcwsc. If not, see <http://www.gnu.org/licenses/>.
////
using System;
using System.Collections.Generic;
namespace XmlRpc {
/// <summary>
/// XML-RPC request
/// </summary>
public class XmlRpcRequest {
/// <summary>
/// Gets or sets the name of the method
/// </summary>
/// <value>The name of the method</value>
public string MethodName {
get;
set;
}
/// <summary>
/// Gets or sets the parameters
/// </summary>
/// <value>The parameters</value>
private List<object> Params {
get;
set;
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlRpc.XmlRcpRequest"/> class
/// </summary>
public XmlRpcRequest() {
this.MethodName = "";
this.Params = new List<object>();
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlRpc.XmlRcpRequest"/> class
/// </summary>
/// <param name="methodName">Method name</param>
public XmlRpcRequest(string methodName) {
this.MethodName = methodName ?? "";
this.Params = new List<object>();
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlRpc.XmlRpcRequest"/> class
/// </summary>
/// <param name="methodName">Method name</param>
/// <param name="parameters">Parameters</param>
public XmlRpcRequest(string methodName, params object[] parameters) {
this.MethodName = methodName ?? "";
this.Params = new List<object>();
if (parameters != null)
this.Params.AddRange(parameters);
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlRpc.XmlRcpRequest"/> class
/// </summary>
/// <param name="methodName">Method name</param>
/// <param name="parameters">Parameters.</param>
public XmlRpcRequest(string methodName, List<object> parameters) {
this.MethodName = methodName ?? "";
this.Params = parameters ?? new List<object>();
}
/// <summary>
/// Adds the parameter, if param is DateTime uses DateTime.UtcNow, for dateTime.iso8601 conversion
/// </summary>
/// <param name="param">Parameter</param>
public void AddParam(object param) {
Params.Add(param);
}
/// <summary>
/// Adds the parameters
/// </summary>
/// <param name="parameters">Parameters</param>
public void AddParams(params object[] list) {
Params.AddRange(list);
}
/// <summary>
/// Adds the parameter array
/// </summary>
/// <param name="list">List</param>
public void AddParamArray(params object[] list) {
AddParam(XmlRpcParameter.AsArray(list));
}
/// <summary>
/// Adds the parameter struct
/// </summary>
/// <param name="list">List</param>
public void AddParamStruct(params KeyValuePair<string,object>[] list) {
AddParam(XmlRpcParameter.AsStruct(list));
}
/// <summary>
/// Removes the parameter
/// </summary>
/// <returns>The parameter</returns>
/// <param name="param">Parameter</param>
public void RemoveParam(object param) {
Params.Remove(param);
}
/// <summary>
/// Removes the parameter
/// </summary>
/// <returns>The parameter</returns>
/// <param name="pos">Position</param>
public object RemoveParam(int pos) {
object operation = Params[pos];
RemoveParam(operation);
return operation;
}
/// <summary>
/// Gets the parameter
/// </summary>
/// <returns>The parameter</returns>
/// <param name="pos">Position</param>
public object GetParam(int pos) {
return Params[pos];
}
/// <summary>
/// Gets the parameters
/// </summary>
/// <returns>The parameters</returns>
public List<object> GetParams() {
List<object> temp = new List<object>();
temp.AddRange(Params);
return temp;
}
/// <summary>
/// Gets the parameters count
/// </summary>
/// <returns>The parameters count</returns>
public int GetParamsCount() {
return Params.Count;
}
/// <summary>
/// Clear this instance
/// </summary>
public void Clear() {
Params.Clear();
}
}
}

323
xmlrpcwsc/XmlRpcResponse.cs Normal file
View File

@@ -0,0 +1,323 @@
////
/// XmlRpcResponse.cs
///
/// Copyright (c) 2016 Saúl Piña <sauljabin@gmail.com>.
///
/// This file is part of xmlrpcwsc.
///
/// xmlrpcwsc is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Lesser General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
///
/// xmlrpcwsc is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Lesser General Public License for more details.
///
/// You should have received a copy of the GNU Lesser General Public License
/// along with xmlrpcwsc. If not, see <http://www.gnu.org/licenses/>.
////
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace XmlRpc {
/// <summary>
/// XML-RPC response
/// </summary>
public class XmlRpcResponse {
private bool isFault;
private int faultCode;
private string faultString;
private object value;
/// <summary>
/// Initializes a new instance of the <see cref="XmlRpc.XmlRpcResponse"/> class
/// </summary>
/// <param name="faultCode">Fault code</param>
/// <param name="faultString">Fault string</param>
public XmlRpcResponse(int faultCode, string faultString) {
this.isFault = true;
this.faultCode = faultCode;
this.faultString = faultString;
this.value = null;
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlRpc.XmlRpcResponse"/> class
/// </summary>
/// <param name="faultCode">Fault code</param>
/// <param name="faultString">Fault string</param>
/// <param name="value">Value.</param>
public XmlRpcResponse(int faultCode, string faultString, object value) {
this.isFault = true;
this.faultCode = faultCode;
this.faultString = faultString;
this.value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlRpc.XmlRpcResponse"/> class
/// </summary>
/// <param name="value">Value</param>
public XmlRpcResponse(object value) {
this.isFault = false;
this.faultCode = -1;
this.faultString = null;
this.value = value;
}
/// <summary>
/// Determines whether this instance is fault
/// </summary>
/// <returns><c>true</c> if this instance is fault; otherwise, <c>false</c></returns>
public bool IsFault() {
return isFault;
}
/// <summary>
/// Gets the fault code
/// </summary>
/// <returns>The fault code</returns>
public int GetFaultCode() {
return faultCode;
}
/// <summary>
/// Gets the fault string
/// </summary>
/// <returns>The fault string</returns>
public string GetFaultString() {
return faultString;
}
/// <summary>
/// Gets the value
/// </summary>
/// <returns>The value</returns>
public object GetObject() {
return value;
}
/// <summary>
/// Determines whether this instance is null
/// </summary>
/// <returns><c>true</c> if this instance is null; otherwise, <c>false</c></returns>
public bool IsNull() {
return GetObject() == null;
}
/// <summary>
/// Determines whether this instance is int
/// </summary>
/// <returns><c>true</c> if this instance is int; otherwise, <c>false</c></returns>
public bool IsInt() {
return GetObject() is int;
}
/// <summary>
/// Gets the value int
/// </summary>
/// <returns>The value int</returns>
public int GetInt() {
if (IsNull())
throw new NullReferenceException("The value is null");
else if (IsInt())
return (int)GetObject();
else
throw new InvalidCastException("The value is not of type int");
}
/// <summary>
/// Determines whether this instance is boolean
/// </summary>
/// <returns><c>true</c> if this instance is boolean; otherwise, <c>false</c></returns>
public bool IsBoolean() {
return GetObject() is bool;
}
/// <summary>
/// Gets the value boolean
/// </summary>
/// <returns><c>true</c>, if value boolean was gotten, <c>false</c> otherwise</returns>
public bool GetBoolean() {
if (IsNull())
throw new NullReferenceException("The value is null");
else if (IsBoolean())
return (bool)GetObject();
else
throw new InvalidCastException("The value is not of type bool");
}
/// <summary>
/// Determines whether this instance is string
/// </summary>
/// <returns><c>true</c> if this instance is string; otherwise, <c>false</c></returns>
public bool IsString() {
return GetObject() is string;
}
/// <summary>
/// Gets the value string
/// </summary>
/// <returns>The value string</returns>
public string GetString() {
if (IsNull())
throw new NullReferenceException("The value is null");
else
return ObjectToString(GetObject());
}
/// <summary>
/// Objects to string
/// </summary>
/// <returns>The to string</returns>
/// <param name="value">Value</param>
private string ObjectToString(object value) {
if (value is List<object>) {
StringBuilder stringReturn = new StringBuilder();
stringReturn.Append("[");
foreach (object temp in (List<object>) value) {
stringReturn.Append(ObjectToString(temp));
stringReturn.Append(", ");
}
if (((List<object>)value).Count > 0)
stringReturn.Remove(stringReturn.Length - 2, 2);
stringReturn.Append("]");
return stringReturn.ToString();
} else if (value is Dictionary<string, object>) {
StringBuilder stringReturn = new StringBuilder();
stringReturn.Append("{");
foreach (KeyValuePair<string,object> temp in (Dictionary<string, object>) value) {
stringReturn.Append(temp.Key);
stringReturn.Append(": ");
stringReturn.Append(ObjectToString(temp.Value));
stringReturn.Append(", ");
}
if (((Dictionary<string, object>)value).Count > 0)
stringReturn.Remove(stringReturn.Length - 2, 2);
stringReturn.Append("}");
return stringReturn.ToString();
} else if (value is byte[]) {
return Convert.ToBase64String((byte[])value);
} else {
return value.ToString();
}
}
/// <summary>
/// Determines whether this instance is double
/// </summary>
/// <returns><c>true</c> if this instance is double; otherwise, <c>false</c></returns>
public bool IsDouble() {
return GetObject() is double;
}
/// <summary>
/// Gets the value double
/// </summary>
/// <returns>The value double</returns>
public double GetDouble() {
if (IsNull())
throw new NullReferenceException("The value is null");
else if (IsDouble())
return (double)GetObject();
else
throw new InvalidCastException("The value is not of type double");
}
/// <summary>
/// Determines whether this instance is date time
/// </summary>
/// <returns><c>true</c> if this instance is date time; otherwise, <c>false</c></returns>
public bool IsDateTime() {
return GetObject() is DateTime;
}
/// <summary>
/// Gets the value date time
/// </summary>
/// <returns>The value date time</returns>
public DateTime GetDateTime() {
if (IsNull())
throw new NullReferenceException("The value is null");
else if (IsDateTime())
return (DateTime)GetObject();
else
throw new InvalidCastException("The value is not of type DateTime");
}
/// <summary>
/// Determines whether this instance is byte
/// </summary>
/// <returns><c>true</c> if this instance is byte; otherwise, <c>false</c></returns>
public bool IsByte() {
return GetObject() is byte[];
}
/// <summary>
/// Gets the value byte
/// </summary>
/// <returns>The value byte</returns>
public byte[] GetByte() {
if (IsNull())
throw new NullReferenceException("The value is null");
else if (IsByte())
return (byte[])GetObject();
else
throw new InvalidCastException("The value is not of type byte[]");
}
/// <summary>
/// Determines whether this instance is array
/// </summary>
/// <returns><c>true</c> if this instance is array; otherwise, <c>false</c></returns>
public bool IsArray() {
return GetObject() is List<object>;
}
/// <summary>
/// Gets the value array
/// </summary>
/// <returns>The value array</returns>
public List<object> GetArray() {
if (IsNull())
throw new NullReferenceException("The value is null");
else if (IsArray())
return (List<object>)GetObject();
else
throw new InvalidCastException("The value is not of type List<object>");
}
/// <summary>
/// Determines whether this instance is struct
/// </summary>
/// <returns><c>true</c> if this instance is struct; otherwise, <c>false</c></returns>
public bool IsStruct() {
return GetObject() is Dictionary<string, object>;
}
/// <summary>
/// Gets the value struct
/// </summary>
/// <returns>The value struct</returns>
public Dictionary<string, object> GetStruct() {
if (IsNull())
throw new NullReferenceException("The value is null");
else if (IsStruct())
return (Dictionary<string, object>)GetObject();
else
throw new InvalidCastException("The value is not of type Dictionary<string, object>");
}
}
}

View File

@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{B5FA7348-6454-4545-AC0C-5E94FE53FB6C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>XmlRpc</RootNamespace>
<AssemblyName>xmlrpcwsc</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\build\</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\build\</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ComponentInfo.cs" />
<Compile Include="XmlRpcClient.cs" />
<Compile Include="XmlRpcParameter.cs" />
<Compile Include="XmlRpcRequest.cs" />
<Compile Include="XmlRpcResponse.cs" />
<Compile Include="WebServiceException.cs" />
<Compile Include="WebServiceTimeoutException.cs" />
<Compile Include="WebServiceConnection.cs" />
<Compile Include="RequestFactory.cs" />
<Compile Include="ResponseFactory.cs" />
<Compile Include="FactoryException.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>