.NET Wrapper for Text Messaging API

RESTService.cs

- This class provides the basic functionality of interacting with a generic REST service. These services work based on GET and POST HTTP/S requests. This class abstracts those concepts.

Home | Next >
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Net;
using System.IO; 
#endregion

namespace TxtSignal.CoreServices
{
    /// <summary>
    /// ******************************************************************
    /// *                                                                *
    /// * This code was written by your good friends at SplashTone.com.  *
    /// * This code is offered freely in the spirit of knowledge sharing.*
    /// * If you find good use out of it, check out our site and maybe   *
    /// * drop us a line (support@splashtone.com)!                       *
    /// *                                                                *
    /// * SplashTone.com is a site for booking bands online.             *
    /// * SplashTone.com is run by OpenBracketLLC.com.                   *
    /// *                                                                *
    /// ******************************************************************
    /// 
    /// Provides a mechanism for accessing web services implemented over a simple
    /// REST interface (http/s gets and posts). Consumers may either inherit from this class
    /// or simply use it in its regular form.
    /// </summary>
    public class RESTService
    {
        #region Members and Constructors
        private string _serviceUrl;
        private bool _postMethod;
        private Dictionary<string, string> _parameters;

        private string _response;
        private HttpStatusCode _responseCode;

        public RESTService()
        {
            _parameters = new Dictionary<string, string>();
        }
        public RESTService(string serviceUrl) : this()
        {
            this._serviceUrl = serviceUrl;
        }
        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the service to communicate with.
        /// </summary>
        public string ServiceUrl
        {
            get { return _serviceUrl; }
            set { _serviceUrl = value; }
        }

        /// <summary>
        /// True to use the POST method instead of the GET method for
        /// transmitting data.
        /// </summary>
        public virtual bool UsePostMethod
        {
            get { return _postMethod; }
            set { _postMethod = value; }
        }

        /// <summary>
        /// Gets or sets the parameters to send with this service request.
        /// </summary>
        public virtual Dictionary<string, string> Parameters
        {
            get { return _parameters; }
            set { _parameters = value; }
        }

        /// <summary>
        /// Gets the HTTP response code to the service call.
        /// </summary>
        public HttpStatusCode ResponseCode
        {
            get { return _responseCode; }
        }

        /// <summary>
        /// Gets the raw response from the HTTP service.
        /// </summary>
        public string Response
        {
            get { return _response; }
        } 
        #endregion

        #region Public Methods
        /// <summary>
        /// Submits data to the REST service and handles the response.
        /// </summary>
        public void Submit()
        {
            try
            {
                string dataToSend = GetParameterData();
                HttpWebRequest request = CreateRequest(dataToSend);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                ReadResponse(response);

                string statusCodeError = OnHandleStatusCode(_responseCode);
                if (statusCodeError != null)
                {
                    OnFailure(null, statusCodeError);
                }
                else
                {
                    OnSuccess();
                }
            }
            catch (Exception ex)
            {
                OnFailure(ex, null);
            }
        } 
        #endregion

        #region Methods
        /// <summary>
        /// Creates a request to the service in question and prepares the given data
        /// to attach to the request.
        /// </summary>
        /// <param name="dataToSend">The data to send with the request.</param>
        /// <returns>The created request ready to be sent.</returns>
        protected virtual HttpWebRequest CreateRequest(string dataToSend)
        {
            HttpWebRequest request = null;

            if (UsePostMethod)
            {
                request = (HttpWebRequest)HttpWebRequest.Create(_serviceUrl);
                request.Method = System.Net.WebRequestMethods.Http.Post;

                if (!string.IsNullOrEmpty(dataToSend))
                {
                    request.ContentType = "application/x-www-form-urlencoded";

                    using (Stream reqStream = request.GetRequestStream())
                    {
                        using (StreamWriter sWriter = new StreamWriter(reqStream))
                        {
                            sWriter.Write(dataToSend);
                            sWriter.Close();
                        }

                        reqStream.Close();
                    }
                }
            }
            else
            {
                string url = _serviceUrl;
                if (!string.IsNullOrEmpty(dataToSend))
                    url = _serviceUrl + "?" + dataToSend;

                request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Method = System.Net.WebRequestMethods.Http.Get;
            }

            return request;
        }

        /// <summary>
        /// Creates a data querystring of all the parameters of this object. This data
        /// will be used to send to the service.
        /// </summary>
        /// <returns>A querystring of parameters to send to the service.</returns>
        protected virtual string GetParameterData()
        {
            StringBuilder sBuilder = new StringBuilder();
            foreach (string key in _parameters.Keys)
            {
                string val = _parameters[key];

                if (sBuilder.Length > 0)
                    sBuilder.Append("&");
                sBuilder.Append(key + "=" + val);
            }
            return sBuilder.ToString();
        }

        /// <summary>
        /// Reads the response that was given from the request sent to the REST service.
        /// </summary>
        /// <param name="response">The response obtained from the service request.</param>
        protected virtual void ReadResponse(HttpWebResponse response)
        {
            _responseCode = response.StatusCode;
            using (Stream input = response.GetResponseStream())
            {
                using (StreamReader sReader = new StreamReader(input))
                {
                    _response = sReader.ReadToEnd();
                    sReader.Close();
                }
                input.Close();
            }
        }

        /// <summary>
        /// Allows checking of status codes to trigger an error. If this method returns null,
        /// the OnSuccess method will be fired. Otherwise, OnFailure will be called with the message
        /// returned by this method.
        /// </summary>
        /// <param name="code">The status code from the response.</param>
        /// <returns>Null for success, string for the error message.</returns>
        protected virtual string OnHandleStatusCode(HttpStatusCode code)
        {
            return null;
        }

        /// <summary>
        /// Occurs when a transmission was sent and received successfully.
        /// </summary>
        protected virtual void OnSuccess()
        {
            // Nothing to do
        }

        /// <summary>
        /// Occurs when transmission failed for some reason.
        /// </summary>
        /// <param name="ex">Null or the exception that was caught.</param>
        /// <param name="optionalMessage">Null or an error message from parsing the status code.</param>
        protected virtual void OnFailure(Exception ex, string optionalMessage)
        {
            if (ex != null)
                throw ex;
            throw new WebException(optionalMessage);
        } 
        #endregion
    }
}
Home | Next >
Send any comments or questions here and we will do our best to respond! support@splashtone.com.
Bored? Check out our blog.