コード例 #1
0
        /// <summary>
        /// Handles the API error.
        /// </summary>
        /// <param name="httpResponse">The HTTP response.</param>
        /// <returns></returns>
        private async Task <SendSMSResponse> HandleAPIError(HttpResponseMessage httpResponse)
        {
            SendSMSResponse response;

            String responseContent = await httpResponse.Content.ReadAsStringAsync();

            var isValidObject = responseContent.TryParseJson(out TheSmsWorksExtendedErrorModel errorModel);

            if (isValidObject)
            {
                response = new SendSMSResponse
                {
                    ApiStatusCode = httpResponse.StatusCode,
                    MessageId     = errorModel.Message,
                    Status        = null
                };
            }
            else
            {
                response = new SendSMSResponse
                {
                    ApiStatusCode = httpResponse.StatusCode,
                    MessageId     = responseContent,
                    Status        = null
                };
            }

            return(response);
        }
コード例 #2
0
 public MessageOutput MapNotificationOutput(SendSMSResponse sendSMSResponse)
 {
     return(new MessageOutput
     {
         Response = sendSMSResponse.Response
     });
 }
コード例 #3
0
 public static SendSMSResponse Send(string number, string msg)
 {
     var authResponse = Authenticate();
     SendSMSResponse response = new SendSMSResponse();
     response.status = authResponse.status;
     if (authResponse.status != "AUTH_FAILED")
     {
         response = JsonConvert.DeserializeObject<SendSMSResponse>(MakeRequest(string.Format("http://api.smilesn.com/sendsms?sid={0}&receivenum={1}&textmessage={2}", authResponse.sessionid, number, msg)));
     }
     return response;
 }
コード例 #4
0
        public static SendSMSResponse Send(string number, string msg)
        {
            var             authResponse = Authenticate();
            SendSMSResponse response     = new SendSMSResponse();

            response.status = authResponse.status;
            if (authResponse.status != "AUTH_FAILED")
            {
                response = JsonConvert.DeserializeObject <SendSMSResponse>(MakeRequest(string.Format("http://api.smilesn.com/sendsms?sid={0}&receivenum={1}&textmessage={2}", authResponse.sessionid, number, msg)));
            }
            return(response);
        }
コード例 #5
0
        public void testSendSmsWithDuplicateUidSingle()
        {
            string          uid     = Guid.NewGuid().ToString();
            OutgoingSMS     message = new OutgoingSMS(PANEL_LINE, DESTINATION, "V2::testSendSmsWithDuplicateUidSingle()", uid);
            SendSMSResponse result  = this.client.sendSMS(message);

            Assert.IsInstanceOf <SMSId>(result);
            Assert.IsFalse(((SMSId)result).IsDuplicated);

            message = new OutgoingSMS(PANEL_LINE, DESTINATION, "V2::testSendSmsWithDuplicateUidSingle()", uid);
            result  = this.client.sendSMS(message);
            Assert.IsInstanceOf <SMSId>(result);
            Assert.IsTrue(((SMSId)result).IsDuplicated);
        }
コード例 #6
0
        public void testSendSingleSMS()
        {
            int             initCredit = this.client.getCredit().SmsPageCount;
            OutgoingSMS     message    = new OutgoingSMS(PANEL_LINE, DESTINATION, "V2::testSendSingleSMS()");
            SendSMSResponse response   = client.sendSMS(message);

            Assert.IsInstanceOf <SMSId>(response);
            Status status = this.client.checkStatus(int.Parse(((SMSId)response).Id));

            Assert.IsInstanceOf <Status>(status);
            int finalCredit = this.client.getCredit().SmsPageCount;

            Assert.LessOrEqual(initCredit - finalCredit, 1);
        }
コード例 #7
0
    public tempuri.org.ArrayOfLong SendSMS(string username, string password, tempuri.org.ArrayOfString senderNumbers, tempuri.org.ArrayOfString recipientNumbers, tempuri.org.ArrayOfString messageBodies, tempuri.org.ArrayOfString sendDate, tempuri.org.ArrayOfInt messageClasses, tempuri.org.ArrayOfLong checkingMessageIds)
    {
        SendSMSRequest inValue = new SendSMSRequest();

        inValue.Body                    = new SendSMSRequestBody();
        inValue.Body.username           = username;
        inValue.Body.password           = password;
        inValue.Body.senderNumbers      = senderNumbers;
        inValue.Body.recipientNumbers   = recipientNumbers;
        inValue.Body.messageBodies      = messageBodies;
        inValue.Body.sendDate           = sendDate;
        inValue.Body.messageClasses     = messageClasses;
        inValue.Body.checkingMessageIds = checkingMessageIds;
        SendSMSResponse retVal = ((IV2Soap)(this)).SendSMS(inValue);

        return(retVal.Body.SendSMSResult);
    }
コード例 #8
0
        private async Task SendSMS(TableRow tableRow)
        {
            String sender      = SpecflowTableHelper.GetStringRowValue(tableRow, "Sender");
            String destination = SpecflowTableHelper.GetStringRowValue(tableRow, "Destination");
            String message     = SpecflowTableHelper.GetStringRowValue(tableRow, "Message");

            SendSMSRequest request = new SendSMSRequest
            {
                ConnectionIdentifier = Guid.NewGuid(),
                Sender      = sender,
                Destination = destination,
                Message     = message
            };

            SendSMSResponse sendEmailResponse = await this.TestingContext.DockerHelper.MessagingServiceClient.SendSMS(this.TestingContext.AccessToken, request, CancellationToken.None).ConfigureAwait(false);

            sendEmailResponse.MessageId.ShouldNotBe(Guid.Empty);
        }
コード例 #9
0
        /// <summary>
        /// Sends the SMS.
        /// </summary>
        /// <param name="accessToken">The access token.</param>
        /// <param name="sendSMSRequest">The send SMS request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public async Task <SendSMSResponse> SendSMS(String accessToken,
                                                    SendSMSRequest sendSMSRequest,
                                                    CancellationToken cancellationToken)
        {
            SendSMSResponse response = null;

            String requestUri = this.BuildRequestUrl("/api/sms/");

            try
            {
                String requestSerialised = JsonConvert.SerializeObject(sendSMSRequest);

                StringContent httpContent = new StringContent(requestSerialised, Encoding.UTF8, "application/json");

                // Add the access token to the client headers
                this.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                // Make the Http Call here
                HttpResponseMessage httpResponse = await this.HttpClient.PostAsync(requestUri, httpContent, cancellationToken);

                // Process the response
                String content = await this.HandleResponse(httpResponse, cancellationToken);

                // call was successful so now deserialise the body to the response object
                response = JsonConvert.DeserializeObject <SendSMSResponse>(content);
            }
            catch (Exception ex)
            {
                // An exception has occurred, add some additional information to the message
                Exception exception = new Exception("Error sending sms message.", ex);

                throw exception;
            }

            return(response);
        }
コード例 #10
0
    /// <summary>
    /// This function validates the input fields and if they are valid send sms api is invoked
    /// </summary>
    private void SendSms()
    {
        try
        {
            string        outBoundSmsJson    = string.Empty;
            List <string> destinationNumbers = new List <string>();
            if (!string.IsNullOrEmpty(address.Value))
            {
                string   addressInput      = address.Value;
                string[] multipleAddresses = addressInput.Split(',');
                foreach (string addr in multipleAddresses)
                {
                    if (addr.StartsWith("tel:"))
                    {
                        destinationNumbers.Add(addr);
                    }
                    else
                    {
                        string phoneNumberWithTel = "tel:" + addr;
                        destinationNumbers.Add(phoneNumberWithTel);
                    }
                }
                if (multipleAddresses.Length == 1)
                {
                    SendSMSDataForSingle outBoundSms = new SendSMSDataForSingle();
                    outBoundSms.outboundSMSRequest = new OutboundSMSRequestForSingle();
                    outBoundSms.outboundSMSRequest.notifyDeliveryStatus = chkGetOnlineStatus.Checked;
                    outBoundSms.outboundSMSRequest.address = destinationNumbers[0];
                    outBoundSms.outboundSMSRequest.message = message.SelectedValue;
                    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                    outBoundSmsJson = javaScriptSerializer.Serialize(outBoundSms);
                }
                else
                {
                    SendSMSDataForMultiple outBoundSms = new SendSMSDataForMultiple();
                    outBoundSms.outboundSMSRequest = new OutboundSMSRequestForMultiple();
                    outBoundSms.outboundSMSRequest.notifyDeliveryStatus = chkGetOnlineStatus.Checked;
                    outBoundSms.outboundSMSRequest.address = destinationNumbers;
                    outBoundSms.outboundSMSRequest.message = message.SelectedValue;
                    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                    outBoundSmsJson = javaScriptSerializer.Serialize(outBoundSms);
                }
            }
            else
            {
                sendSMSErrorMessage = "No input provided for Address";
                return;
            }



            string         sendSmsResponseData;
            HttpWebRequest sendSmsRequestObject = (HttpWebRequest)System.Net.WebRequest.Create(string.Empty + this.endPoint + this.sendSMSURL);
            sendSmsRequestObject.Method = "POST";
            sendSmsRequestObject.Headers.Add("Authorization", "Bearer " + this.accessToken);
            sendSmsRequestObject.ContentType = "application/json";
            sendSmsRequestObject.Accept      = "application/json";

            UTF8Encoding encoding  = new UTF8Encoding();
            byte[]       postBytes = encoding.GetBytes(outBoundSmsJson);
            sendSmsRequestObject.ContentLength = postBytes.Length;

            Stream postStream = sendSmsRequestObject.GetRequestStream();
            postStream.Write(postBytes, 0, postBytes.Length);
            postStream.Close();

            HttpWebResponse sendSmsResponseObject = (HttpWebResponse)sendSmsRequestObject.GetResponse();
            using (StreamReader sendSmsResponseStream = new StreamReader(sendSmsResponseObject.GetResponseStream()))
            {
                sendSmsResponseData = sendSmsResponseStream.ReadToEnd();
                JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
                sendSMSResponseData = new SendSMSResponse();
                sendSMSResponseData.outBoundSMSResponse = new OutBoundSMSResponse();
                sendSMSResponseData = (SendSMSResponse)deserializeJsonObject.Deserialize(sendSmsResponseData, typeof(SendSMSResponse));
                if (!chkGetOnlineStatus.Checked)
                {
                    Session["lastSentSMSID"] = sendSMSResponseData.outBoundSMSResponse.messageId;
                    messageId.Value          = Session["lastSentSMSID"].ToString();
                }
                sendSMSSuccessMessage = "Success";
                sendSmsResponseStream.Close();
            }
        }
        catch (WebException we)
        {
            string errorResponse = string.Empty;

            try
            {
                using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
                {
                    errorResponse = sr2.ReadToEnd();
                    sr2.Close();
                }
            }
            catch
            {
                errorResponse = "Unable to get response";
            }

            sendSMSErrorMessage = errorResponse;
        }
        catch (Exception ex)
        {
            sendSMSErrorMessage = ex.ToString();
        }
    }
コード例 #11
0
    /// <summary>
    /// This function validates the input fields and if they are valid send sms api is invoked
    /// </summary>
    private void SendSms()
    {
        try
        {
            string outBoundSmsJson = string.Empty;
            List<string> destinationNumbers = new List<string>();
            if (!string.IsNullOrEmpty(address.Value))
            {
                string addressInput = address.Value;
                string[] multipleAddresses = addressInput.Split(',');
                foreach (string addr in multipleAddresses)
                {
                    if (addr.StartsWith("tel:"))
                    {
                        destinationNumbers.Add(addr);
                    }
                    else
                    {
                        string phoneNumberWithTel = "tel:" + addr;
                        destinationNumbers.Add(phoneNumberWithTel);
                    }
                }
                if (multipleAddresses.Length == 1)
                {
                    SendSMSDataForSingle outBoundSms = new SendSMSDataForSingle();
                    outBoundSms.outboundSMSRequest = new OutboundSMSRequestForSingle();
                    outBoundSms.outboundSMSRequest.notifyDeliveryStatus = chkGetOnlineStatus.Checked;
                    outBoundSms.outboundSMSRequest.address = destinationNumbers[0];
                    outBoundSms.outboundSMSRequest.message = message.SelectedValue;
                    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                    outBoundSmsJson = javaScriptSerializer.Serialize(outBoundSms);
                }
                else
                {
                    SendSMSDataForMultiple outBoundSms = new SendSMSDataForMultiple();
                    outBoundSms.outboundSMSRequest = new OutboundSMSRequestForMultiple();
                    outBoundSms.outboundSMSRequest.notifyDeliveryStatus = chkGetOnlineStatus.Checked;
                    outBoundSms.outboundSMSRequest.address = destinationNumbers;
                    outBoundSms.outboundSMSRequest.message = message.SelectedValue;
                    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                    outBoundSmsJson = javaScriptSerializer.Serialize(outBoundSms);
                }
            }
            else
            {
                sendSMSErrorMessage = "No input provided for Address";
                return;
            }

            string sendSmsResponseData;
            HttpWebRequest sendSmsRequestObject = (HttpWebRequest)System.Net.WebRequest.Create(string.Empty + this.endPoint + this.sendSMSURL);
            sendSmsRequestObject.Method = "POST";
            sendSmsRequestObject.Headers.Add("Authorization", "Bearer " + this.accessToken);
            sendSmsRequestObject.ContentType = "application/json";
            sendSmsRequestObject.Accept = "application/json";

            UTF8Encoding encoding = new UTF8Encoding();
            byte[] postBytes = encoding.GetBytes(outBoundSmsJson);
            sendSmsRequestObject.ContentLength = postBytes.Length;

            Stream postStream = sendSmsRequestObject.GetRequestStream();
            postStream.Write(postBytes, 0, postBytes.Length);
            postStream.Close();

            HttpWebResponse sendSmsResponseObject = (HttpWebResponse)sendSmsRequestObject.GetResponse();
            using (StreamReader sendSmsResponseStream = new StreamReader(sendSmsResponseObject.GetResponseStream()))
            {
                sendSmsResponseData = sendSmsResponseStream.ReadToEnd();
                JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
                sendSMSResponseData = new SendSMSResponse();
                sendSMSResponseData.outBoundSMSResponse = new OutBoundSMSResponse();
                sendSMSResponseData = (SendSMSResponse)deserializeJsonObject.Deserialize(sendSmsResponseData, typeof(SendSMSResponse));
                if (!chkGetOnlineStatus.Checked)
                {
                    Session["lastSentSMSID"] = sendSMSResponseData.outBoundSMSResponse.messageId;
                    messageId.Value = Session["lastSentSMSID"].ToString();
                }
                sendSMSSuccessMessage = "Success";
                sendSmsResponseStream.Close();
            }

        }
        catch (WebException we)
        {
            string errorResponse = string.Empty;

            try
            {
                using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
                {
                    errorResponse = sr2.ReadToEnd();
                    sr2.Close();
                }
            }
            catch
            {
                errorResponse = "Unable to get response";
            }

            sendSMSErrorMessage= errorResponse;
        }
        catch (Exception ex)
        {
            sendSMSErrorMessage = ex.ToString();
        }
    }
コード例 #12
0
        /// <summary>
        /// Sends the SMS.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public async Task <SendSMSResponse> SendSMS(SendSMSRequest request, CancellationToken cancellationToken)
        {
            SendSMSResponse response = null;

            using (HttpClient client = new HttpClient())
            {
                // Create the Auth Request
                TheSmsWorksTokenRequest apiTokenRequest = new TheSmsWorksTokenRequest
                {
                    CustomerId = ConfigurationReader.GetValue("TheSMSWorksCustomerId"),
                    Key        = ConfigurationReader.GetValue("TheSMSWorksKey"),
                    Secret     = ConfigurationReader.GetValue("TheSMSWorksSecret")
                };

                String        apiTokenRequestSerialised = JsonConvert.SerializeObject(apiTokenRequest).ToLower();
                StringContent content = new StringContent(apiTokenRequestSerialised, Encoding.UTF8, "application/json");

                // First do the authentication
                var apiTokenHttpResponse = await client.PostAsync($"{ConfigurationReader.GetValue("TheSMSWorksBaseAddress")}auth/token", content, cancellationToken);

                if (apiTokenHttpResponse.IsSuccessStatusCode)
                {
                    TheSmsWorksTokenResponse apiTokenResponse =
                        JsonConvert.DeserializeObject <TheSmsWorksTokenResponse>(await apiTokenHttpResponse.Content
                                                                                 .ReadAsStringAsync());

                    // Now do the actual send
                    TheSmsWorksSendSMSRequest apiSendSmsRequest = new TheSmsWorksSendSMSRequest
                    {
                        Content     = request.Message,
                        Sender      = request.Sender,
                        Destination = request.Destination,
                        Schedule    = string.Empty,
                        Tag         = string.Empty,
                        Ttl         = 0
                    };

                    String apiSendSMSMessageRequestSerialised = JsonConvert.SerializeObject(apiSendSmsRequest).ToLower();
                    content = new StringContent(apiSendSMSMessageRequestSerialised, Encoding.UTF8, "application/json");

                    client.DefaultRequestHeaders.Add("Authorization", apiTokenResponse.Token);
                    var apiSendSMSMessageHttpResponse = await client.PostAsync($"{ConfigurationReader.GetValue("TheSMSWorksBaseAddress")}message/send", content, cancellationToken);

                    if (apiSendSMSMessageHttpResponse.IsSuccessStatusCode)
                    {
                        // Message has been sent
                        TheSmsWorksSendSMSResponse apiTheSmsWorksSendSmsResponse =
                            JsonConvert.DeserializeObject <TheSmsWorksSendSMSResponse>(await apiSendSMSMessageHttpResponse.Content
                                                                                       .ReadAsStringAsync());

                        response = new SendSMSResponse
                        {
                            ApiStatusCode = apiSendSMSMessageHttpResponse.StatusCode,
                            MessageId     = apiTheSmsWorksSendSmsResponse.MessageId,
                            Status        = apiTheSmsWorksSendSmsResponse.Status
                        };
                    }
                    else
                    {
                        response = await HandleAPIError(apiSendSMSMessageHttpResponse);
                    }
                }
                else
                {
                    response = await HandleAPIError(apiTokenHttpResponse);
                }
            }

            return(response);
        }
コード例 #13
0
        public async Task <IActionResult> SendMessage(SendSMSRequest Request)
        {
            SendSMSResponse Response = await _mediator.Send(Request);

            return(Ok(Response));
        }