//============================================================ // ICOMPARABLE IMPLEMENTATION //============================================================ #region CompareTo(object obj) /// <summary> /// Compares the current instance with another object of the same type. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns>A 32-bit signed integer that indicates the relative order of the objects being compared.</returns> /// <exception cref="ArgumentException">The <paramref name="obj"/> is not the expected <see cref="Type"/>.</exception> public int CompareTo(object obj) { //------------------------------------------------------------ // If target is a null reference, instance is greater //------------------------------------------------------------ if (obj == null) { return(1); } //------------------------------------------------------------ // Determine comparison result using property state of objects //------------------------------------------------------------ XmlRpcArrayValue value = obj as XmlRpcArrayValue; if (value != null) { int result = XmlRpcMessage.CompareSequence(this.Values, value.Values); return(result); } else { throw new ArgumentException(String.Format(null, "obj is not of type {0}, type was found to be '{1}'.", this.GetType().FullName, obj.GetType().FullName), "obj"); } }
/// <summary> /// Sends the specified message to an XML-RPC server to execute a remote procedure call. /// This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes. /// </summary> /// <param name="message">A <see cref="XmlRpcMessage"/> that represents the information needed to execute the remote procedure call.</param> /// <param name="userToken">A user-defined object that is passed to the method invoked when the asynchronous operation completes.</param> /// <remarks> /// <para> /// To receive notification when the remote procedure call has been sent or the operation has been cancelled, add an event handler to the <see cref="SendCompleted"/> event. /// You can cancel a <see cref="SendAsync(XmlRpcMessage, Object)"/> operation by calling the <see cref="SendAsyncCancel()"/> method. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">The <paramref name="message"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="InvalidOperationException">The <see cref="Host"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception> /// <exception cref="InvalidOperationException">This <see cref="XmlRpcClient"/> has a <see cref="SendAsync(XmlRpcMessage, Object)"/> call in progress.</exception> //[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)] public void SendAsync(XmlRpcMessage message, Object userToken) { Guard.ArgumentNotNull(message, "message"); if (this.Host == null) { throw new InvalidOperationException(String.Format(null, "Unable to send XML-RPC message. The Host property has not been initialized. \n\r Message payload: {0}", message)); } else if (this.SendOperationInProgress) { throw new InvalidOperationException(String.Format(null, "Unable to send XML-RPC message. The XmlRpcClient has a SendAsync call in progress. \n\r Message payload: {0}", message)); } this.SendOperationInProgress = true; this.AsyncSendHasBeenCancelled = false; asyncHttpWebRequest = XmlRpcClient.CreateWebRequest(this.Host, this.UserAgent, message, this.UseDefaultCredentials, this.clientOptions); object[] state = new object[6] { asyncHttpWebRequest, this, this.Host, message, this.clientOptions, userToken }; IAsyncResult result = asyncHttpWebRequest.BeginGetResponse(new AsyncCallback(AsyncSendCallback), state); ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(AsyncTimeoutCallback), state, this.Timeout, true); }
/// <summary> /// Called when a corresponding asynchronous send operation completes. /// </summary> /// <param name="result">The result of the asynchronous operation.</param> private static void AsyncSendCallback(IAsyncResult result) { XmlRpcResponse response = null; WebRequest httpWebRequest = null; XmlRpcClient client = null; Uri host = null; XmlRpcMessage message = null; WebRequestOptions options = null; object userToken = null; if (result.IsCompleted) { object[] parameters = (object[])result.AsyncState; httpWebRequest = parameters[0] as WebRequest; client = parameters[1] as XmlRpcClient; host = parameters[2] as Uri; message = parameters[3] as XmlRpcMessage; options = parameters[4] as WebRequestOptions; userToken = parameters[5]; if (client != null) { WebResponse httpWebResponse = (WebResponse)httpWebRequest.EndGetResponse(result); response = new XmlRpcResponse(httpWebResponse); client.OnMessageSent(new XmlRpcMessageSentEventArgs(host, message, response, options, userToken)); client.SendOperationInProgress = false; } } }
//============================================================ // ICOMPARABLE IMPLEMENTATION //============================================================ #region CompareTo(object obj) /// <summary> /// Compares the current instance with another object of the same type. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns>A 32-bit signed integer that indicates the relative order of the objects being compared.</returns> /// <exception cref="ArgumentException">The <paramref name="obj"/> is not the expected <see cref="Type"/>.</exception> public int CompareTo(object obj) { //------------------------------------------------------------ // If target is a null reference, instance is greater //------------------------------------------------------------ if (obj == null) { return(1); } //------------------------------------------------------------ // Determine comparison result using property state of objects //------------------------------------------------------------ XmlRpcMessage value = obj as XmlRpcMessage; if (value != null) { int result = String.Compare(this.Encoding.WebName, value.Encoding.WebName, StringComparison.OrdinalIgnoreCase); result = result | String.Compare(this.MethodName, value.MethodName, StringComparison.OrdinalIgnoreCase); result = result | XmlRpcMessage.CompareSequence(this.Parameters, value.Parameters); return(result); } else { throw new ArgumentException(String.Format(null, "obj is not of type {0}, type was found to be '{1}'.", this.GetType().FullName, obj.GetType().FullName), "obj"); } }
/// <summary> /// Initializes a new instance of the <see cref="XmlRpcMessageSentEventArgs"/> class using the supplied parameters. /// </summary> /// <param name="host">A <see cref="Uri"/> that represents the URL of the host computer used for the XML-RPC transaction.</param> /// <param name="message">An <see cref="XmlRpcMessage"/> that represents the remote procedure call payload.</param> /// <param name="response">An <see cref="XmlRpcResponse"/> that represents the response to the remote procedure call.</param> /// <param name="options">A <see cref="WebRequestOptions"/> that holds options that should be applied to web requests.</param> /// <param name="state">A <see cref="Object"/> containing state information that was passed to the asynchronous send operation. This parameter may be <b>null</b>.</param> /// <exception cref="ArgumentNullException">The <paramref name="host"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="message"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="response"/> is a null reference (Nothing in Visual Basic).</exception> public XmlRpcMessageSentEventArgs(Uri host, XmlRpcMessage message, XmlRpcResponse response, WebRequestOptions options, Object state) { Guard.ArgumentNotNull(host, "host"); Guard.ArgumentNotNull(message, "message"); Guard.ArgumentNotNull(response, "response"); eventHost = host; eventMessage = message; eventResponse = response; eventOptions = options ?? new WebRequestOptions(); eventUserToken = state; }
/// <summary> /// Initializes a new instance of the <see cref="XmlRpcMessageSentEventArgs"/> class using the supplied parameters. /// </summary> /// <param name="host">A <see cref="Uri"/> that represents the URL of the host computer used for the XML-RPC transaction.</param> /// <param name="message">An <see cref="XmlRpcMessage"/> that represents the remote procedure call payload.</param> /// <param name="response">An <see cref="XmlRpcResponse"/> that represents the response to the remote procedure call.</param> /// <param name="credentials">A <see cref="ICredentials"/> that represents the authentication credentials utilized by the client when making the remote procedure call. This parameter may be <b>null</b>.</param> /// <param name="proxy">A <see cref="IWebProxy"/> that represents the web proxy utilized by the client to proxy the remote procedure call. This parameter may be <b>null</b>.</param> /// <param name="state">A <see cref="Object"/> containing state information that was passed to the asynchronous send operation. This parameter may be <b>null</b>.</param> /// <exception cref="ArgumentNullException">The <paramref name="host"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="message"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="response"/> is a null reference (Nothing in Visual Basic).</exception> public XmlRpcMessageSentEventArgs(Uri host, XmlRpcMessage message, XmlRpcResponse response, ICredentials credentials, IWebProxy proxy, Object state) { Guard.ArgumentNotNull(host, "host"); Guard.ArgumentNotNull(message, "message"); Guard.ArgumentNotNull(response, "response"); eventHost = host; eventMessage = message; eventResponse = response; eventOptions = new WebRequestOptions(credentials, proxy); eventUserToken = state; }
/// <summary> /// Initializes a new <see cref="WebRequest"/> suitable for sending a remote procedure call using the supplied host, user agent, message, credentials, and proxy. /// </summary> /// <param name="host">A <see cref="Uri"/> that represents the URL of the host computer used for XML-RPC transactions.</param> /// <param name="userAgent">Information such as the application name, version, host operating system, and language.</param> /// <param name="message">A <see cref="XmlRpcMessage"/> that represents the information needed to execute the remote procedure call.</param> /// <param name="useDefaultCredentials"> /// Controls whether the <see cref="CredentialCache.DefaultCredentials">DefaultCredentials</see> are sent when making remote procedure calls. /// </param> /// <param name="options">A <see cref="WebRequestOptions"/> that holds options that should be applied to web requests.</param> /// <exception cref="ArgumentNullException">The <paramref name="host"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="userAgent"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="userAgent"/> is an empty string.</exception> /// <exception cref="ArgumentNullException">The <paramref name="message"/> is a null reference (Nothing in Visual Basic).</exception> private static WebRequest CreateWebRequest(Uri host, string userAgent, XmlRpcMessage message, bool useDefaultCredentials, WebRequestOptions options) { HttpWebRequest httpRequest = null; byte[] payloadData; Guard.ArgumentNotNull(host, "host"); Guard.ArgumentNotNullOrEmptyString(userAgent, "userAgent"); Guard.ArgumentNotNull(message, "message"); using (MemoryStream stream = new MemoryStream()) { XmlWriterSettings settings = new XmlWriterSettings(); settings.ConformanceLevel = ConformanceLevel.Document; settings.Encoding = message.Encoding; settings.Indent = true; settings.OmitXmlDeclaration = false; using (XmlWriter writer = XmlWriter.Create(stream, settings)) { message.WriteTo(writer); writer.Flush(); } stream.Seek(0, SeekOrigin.Begin); payloadData = message.Encoding.GetBytes((new StreamReader(stream)).ReadToEnd()); } httpRequest = (HttpWebRequest)HttpWebRequest.Create(host); httpRequest.Method = "POST"; httpRequest.ContentLength = payloadData.Length; httpRequest.ContentType = String.Format(null, "text/xml; charset={0}", message.Encoding.WebName); httpRequest.UserAgent = userAgent; if (options != null) { options.ApplyOptions(httpRequest); } if (useDefaultCredentials) { httpRequest.Credentials = CredentialCache.DefaultCredentials; } using (Stream stream = httpRequest.GetRequestStream()) { stream.Write(payloadData, 0, payloadData.Length); } return(httpRequest); }
/// <summary> /// Initializes a new instance of the <see cref="XmlRpcMessageSentEventArgs"/> class using the supplied parameters. /// </summary> /// <param name="host">A <see cref="Uri"/> that represents the URL of the host computer used for the XML-RPC transaction.</param> /// <param name="message">An <see cref="XmlRpcMessage"/> that represents the remote procedure call payload.</param> /// <param name="response">An <see cref="XmlRpcResponse"/> that represents the response to the remote procedure call.</param> /// <param name="credentials">A <see cref="ICredentials"/> that represents the authentication credentials utilized by the client when making the remote procedure call. This parameter may be <b>null</b>.</param> /// <param name="proxy">A <see cref="IWebProxy"/> that represents the web proxy utilized by the client to proxy the remote procedure call. This parameter may be <b>null</b>.</param> /// <param name="state">A <see cref="Object"/> containing state information that was passed to the asynchronous send operation. This parameter may be <b>null</b>.</param> /// <exception cref="ArgumentNullException">The <paramref name="host"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="message"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="response"/> is a null reference (Nothing in Visual Basic).</exception> public XmlRpcMessageSentEventArgs(Uri host, XmlRpcMessage message, XmlRpcResponse response, ICredentials credentials, IWebProxy proxy, Object state) { //------------------------------------------------------------ // Validate parameters //------------------------------------------------------------ Guard.ArgumentNotNull(host, "host"); Guard.ArgumentNotNull(message, "message"); Guard.ArgumentNotNull(response, "response"); //------------------------------------------------------------ // Initialize class members //------------------------------------------------------------ eventHost = host; eventMessage = message; eventResponse = response; eventOptions = new WebRequestOptions(credentials, proxy); eventUserToken = state; }
/// <summary> /// Compares the current instance with another object of the same type. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns>A 32-bit signed integer that indicates the relative order of the objects being compared.</returns> /// <exception cref="ArgumentException">The <paramref name="obj"/> is not the expected <see cref="Type"/>.</exception> public int CompareTo(object obj) { if (obj == null) { return(1); } XmlRpcArrayValue value = obj as XmlRpcArrayValue; if (value != null) { int result = XmlRpcMessage.CompareSequence(this.Values, value.Values); return(result); } else { throw new ArgumentException(String.Format(null, "obj is not of type {0}, type was found to be '{1}'.", this.GetType().FullName, obj.GetType().FullName), "obj"); } }
//============================================================ // CLASS SUMMARY //============================================================ /// <summary> /// Provides example code for the XmlRpcClient class. /// </summary> public static void ClassExample() { #region XmlRpcClient // Initialize the XML-RPC client XmlRpcClient client = new XmlRpcClient(); client.Host = new Uri("http://bob.example.net/xmlrpcserver"); // Construct a Pingback peer-to-peer notification XML-RPC message XmlRpcMessage message = new XmlRpcMessage("pingback.ping"); message.Encoding = Encoding.UTF8; message.Parameters.Add(new XmlRpcScalarValue("http://alice.example.org/#p123")); // sourceURI message.Parameters.Add(new XmlRpcScalarValue("http://bob.example.net/#foo")); // targetURI // Send a synchronous pingback ping XmlRpcResponse response = client.Send(message); // Verify response to the trackback ping if (response != null) { if (response.Fault != null) { XmlRpcStructureMember faultCode = response.Fault["faultCode"]; XmlRpcStructureMember faultMessage = response.Fault["faultString"]; if (faultCode != null && faultMessage != null) { // Handle the pingback ping error condition that occurred } } else { XmlRpcScalarValue successInformation = response.Parameter as XmlRpcScalarValue; if (successInformation != null) { // Pingback request was successful, return should be a string containing information the server deems useful. } } } #endregion }
/// <summary> /// Compares the current instance with another object of the same type. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns>A 32-bit signed integer that indicates the relative order of the objects being compared.</returns> /// <exception cref="ArgumentException">The <paramref name="obj"/> is not the expected <see cref="Type"/>.</exception> public int CompareTo(object obj) { if (obj == null) { return(1); } XmlRpcMessage value = obj as XmlRpcMessage; if (value != null) { int result = String.Compare(this.Encoding.WebName, value.Encoding.WebName, StringComparison.OrdinalIgnoreCase); result = result | String.Compare(this.MethodName, value.MethodName, StringComparison.OrdinalIgnoreCase); result = result | XmlRpcMessage.CompareSequence(this.Parameters, value.Parameters); return(result); } else { throw new ArgumentException(String.Format(null, "obj is not of type {0}, type was found to be '{1}'.", this.GetType().FullName, obj.GetType().FullName), "obj"); } }
/// <summary> /// Sends the specified message to an XML-RPC server to execute a remote procedure call. /// </summary> /// <param name="message">A <see cref="XmlRpcMessage"/> that represents the information needed to execute the remote procedure call.</param> /// <returns>A <see cref="XmlRpcResponse"/> that represents the server's response to the remote procedure call.</returns> /// <exception cref="ArgumentNullException">The <paramref name="message"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="InvalidOperationException">The <see cref="Host"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception> /// <exception cref="InvalidOperationException">This <see cref="XmlRpcClient"/> has a <see cref="SendAsync(XmlRpcMessage, Object)"/> call in progress.</exception> public XmlRpcResponse Send(XmlRpcMessage message) { XmlRpcResponse response = null; Guard.ArgumentNotNull(message, "message"); if (this.Host == null) { throw new InvalidOperationException(String.Format(null, "Unable to send XML-RPC message. The Host property has not been initialized. \n\r Message payload: {0}", message)); } else if (this.SendOperationInProgress) { throw new InvalidOperationException(String.Format(null, "Unable to send XML-RPC message. The XmlRpcClient has a SendAsync call in progress. \n\r Message payload: {0}", message)); } WebRequest webRequest = XmlRpcClient.CreateWebRequest(this.Host, this.UserAgent, message, this.UseDefaultCredentials, this.clientOptions); using (WebResponse webResponse = (WebResponse)webRequest.GetResponse()) { response = new XmlRpcResponse(webResponse); } return(response); }
/// <summary> /// Initializes a new <see cref="WebRequest"/> suitable for sending a remote procedure call using the supplied host, user agent, message, credentials, and proxy. /// </summary> /// <param name="host">A <see cref="Uri"/> that represents the URL of the host computer used for XML-RPC transactions.</param> /// <param name="userAgent">Information such as the application name, version, host operating system, and language.</param> /// <param name="message">A <see cref="XmlRpcMessage"/> that represents the information needed to execute the remote procedure call.</param> /// <param name="useDefaultCredentials"> /// Controls whether the <see cref="CredentialCache.DefaultCredentials">DefaultCredentials</see> are sent when making remote procedure calls. /// </param> /// <param name="options">A <see cref="WebRequestOptions"/> that holds options that should be applied to web requests.</param> /// <exception cref="ArgumentNullException">The <paramref name="host"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="userAgent"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="userAgent"/> is an empty string.</exception> /// <exception cref="ArgumentNullException">The <paramref name="message"/> is a null reference (Nothing in Visual Basic).</exception> private static WebRequest CreateWebRequest(Uri host, string userAgent, XmlRpcMessage message, bool useDefaultCredentials, WebRequestOptions options) { //------------------------------------------------------------ // Local members //------------------------------------------------------------ HttpWebRequest httpRequest = null; byte[] payloadData; //------------------------------------------------------------ // Validate parameters //------------------------------------------------------------ Guard.ArgumentNotNull(host, "host"); Guard.ArgumentNotNullOrEmptyString(userAgent, "userAgent"); Guard.ArgumentNotNull(message, "message"); //------------------------------------------------------------ // Build the XML-RPC payload data //------------------------------------------------------------ using(MemoryStream stream = new MemoryStream()) { XmlWriterSettings settings = new XmlWriterSettings(); settings.ConformanceLevel = ConformanceLevel.Document; settings.Encoding = message.Encoding; settings.Indent = true; settings.OmitXmlDeclaration = false; using(XmlWriter writer = XmlWriter.Create(stream, settings)) { message.WriteTo(writer); writer.Flush(); } stream.Seek(0, SeekOrigin.Begin); payloadData = message.Encoding.GetBytes((new StreamReader(stream)).ReadToEnd()); } //------------------------------------------------------------ // Build HTTP web request used to send a remote procedure call //------------------------------------------------------------ httpRequest = (HttpWebRequest)HttpWebRequest.Create(host); httpRequest.Method = "POST"; httpRequest.ContentLength = payloadData.Length; httpRequest.ContentType = String.Format(null, "text/xml; charset={0}", message.Encoding.WebName); httpRequest.UserAgent = userAgent; if (options != null) options.ApplyOptions(httpRequest); if(useDefaultCredentials) { httpRequest.Credentials = CredentialCache.DefaultCredentials; } using (Stream stream = httpRequest.GetRequestStream()) { stream.Write(payloadData, 0, payloadData.Length); } return httpRequest; }
public void SendAsync(XmlRpcMessage message, Object userToken) { //------------------------------------------------------------ // Validate parameter //------------------------------------------------------------ Guard.ArgumentNotNull(message, "message"); //------------------------------------------------------------ // Validate client state //------------------------------------------------------------ if (this.Host == null) { throw new InvalidOperationException(String.Format(null, "Unable to send XML-RPC message. The Host property has not been initialized. \n\r Message payload: {0}", message)); } else if (this.SendOperationInProgress) { throw new InvalidOperationException(String.Format(null, "Unable to send XML-RPC message. The XmlRpcClient has a SendAsync call in progress. \n\r Message payload: {0}", message)); } //------------------------------------------------------------ // Set async operation tracking indicators //------------------------------------------------------------ this.SendOperationInProgress = true; this.AsyncSendHasBeenCancelled = false; //------------------------------------------------------------ // Build HTTP web request used to send the remote procedure call //------------------------------------------------------------ asyncHttpWebRequest = XmlRpcClient.CreateWebRequest(this.Host, this.UserAgent, message, this.UseDefaultCredentials, this.clientOptions); //------------------------------------------------------------ // Get the async response to the web request //------------------------------------------------------------ object[] state = new object[6] { asyncHttpWebRequest, this, this.Host, message, this.clientOptions, userToken }; IAsyncResult result = asyncHttpWebRequest.BeginGetResponse(new AsyncCallback(AsyncSendCallback), state); //------------------------------------------------------------ // Register the timeout callback //------------------------------------------------------------ ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(AsyncTimeoutCallback), state, this.Timeout, true); }
/// <summary> /// Sends the specified message to an XML-RPC server to execute a remote procedure call. /// </summary> /// <param name="message">A <see cref="XmlRpcMessage"/> that represents the information needed to execute the remote procedure call.</param> /// <returns>A <see cref="XmlRpcResponse"/> that represents the server's response to the remote procedure call.</returns> /// <exception cref="ArgumentNullException">The <paramref name="message"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="InvalidOperationException">The <see cref="Host"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception> /// <exception cref="InvalidOperationException">This <see cref="XmlRpcClient"/> has a <see cref="SendAsync(XmlRpcMessage, Object)"/> call in progress.</exception> public XmlRpcResponse Send(XmlRpcMessage message) { //------------------------------------------------------------ // Local members //------------------------------------------------------------ XmlRpcResponse response = null; //------------------------------------------------------------ // Validate parameter //------------------------------------------------------------ Guard.ArgumentNotNull(message, "message"); //------------------------------------------------------------ // Validate client state //------------------------------------------------------------ if(this.Host == null) { throw new InvalidOperationException(String.Format(null, "Unable to send XML-RPC message. The Host property has not been initialized. \n\r Message payload: {0}", message)); } else if (this.SendOperationInProgress) { throw new InvalidOperationException(String.Format(null, "Unable to send XML-RPC message. The XmlRpcClient has a SendAsync call in progress. \n\r Message payload: {0}", message)); } //------------------------------------------------------------ // Execute the remote procedure call //------------------------------------------------------------ WebRequest webRequest = XmlRpcClient.CreateWebRequest(this.Host, this.UserAgent, message, this.UseDefaultCredentials, this.clientOptions); using (WebResponse webResponse = (WebResponse)webRequest.GetResponse()) { response = new XmlRpcResponse(webResponse); } return response; }