Example #1
0
        /// <inheritdoc/>
        public ISmsSendResult SendSms(ISms sms)
        {
            try
            {
                if (!sms?.IsValid(_smsServiceConfig) ?? true)
                {
                    throw new Exception("Invalid SMS request.");
                }

                var paramDict = new Dictionary <string, string>();
                paramDict.Add(_smsServiceConfig.MessageMask, sms.Message);
                paramDict.Add(_smsServiceConfig.RecepientMask, sms.Recepient);
                _smsServiceConfig?.RequestParameters?.ToList()?.ForEach(x => paramDict?.Add(x.Key, x.Value));
                HttpWebRequest request   = null;
                string         postData  = null;
                byte[]         postBytes = null;

                switch (_smsServiceConfig.RequestContentType)
                {
                case RequestContentType.FormData:
                    NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(string.Empty);
                    paramDict?.ToList()?.ForEach(x => outgoingQueryString.Add(x.Key, x.Value));
                    postData            = outgoingQueryString?.ToString();
                    postBytes           = _smsServiceConfig.Encoding.GetBytes(postData);
                    request             = (HttpWebRequest)WebRequest.Create(_smsServiceConfig.BaseUrl);
                    request.ContentType = "application/form-data";
                    break;

                case RequestContentType.JSON:
                    postData            = JsonConvert.SerializeObject(paramDict);
                    postBytes           = _smsServiceConfig.Encoding.GetBytes(postData);
                    request             = (HttpWebRequest)WebRequest.Create(_smsServiceConfig.BaseUrl);
                    request.ContentType = "application/json";
                    break;

                default:    //Handles Enums.RequestContentType.URL too
                    string @params = String.Join("&&", paramDict?.Select(x => $"{x.Key}={x.Value}")?.ToArray());
                    string url     = _smsServiceConfig.BaseUrl + '?' + @params;
                    request = (HttpWebRequest)WebRequest.Create(url);
                    break;
                }

                request.Method = _smsServiceConfig.RequestMethod.Method;
                if (postBytes != null)
                {
                    using (var stream = request.GetRequestStream())
                    {
                        stream.Write(postBytes, 0, postBytes.Length);
                    }
                }

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                return(new SmsSendResult(sms.Recepient, response.StatusCode, response.GetResponseStream()));
            }
            catch (Exception e)
            {
                return(new SmsSendResult(sms.Recepient, e.Message));
            }
        }