We want to split messages into multiple (sms)text messages if the characters exceed 136.
But we also want to make sure that the second message arrives after the first, and before third.
So far, from the few tests We've done, it seems to work like this, but to make sure we still want to add a delay of maybe 3 seconds or so.
is Thread.Sleep
the correct way to do it, or is there another solution than adding a delay?
This is the code :
// Split message to send them as individual text messages
string[] messages = splitMessage(request["message"], 132);
for (int i = 0; i < messages.Length; i++)
{
HttpWebRequest _wr = (HttpWebRequest)WebRequest.Create(url);
// Use the CredentialCache so you can attach the authentication to the request
CredentialCache mycache = new CredentialCache { { new Uri(url), "Basic", new NetworkCredential(_username, _password) } };
// use Basic Authentication
_wr.Credentials = mycache;
_wr.Method = "POST";
_wr.ContentType = "application/json";
_wr.Timeout = -1; // not sure if necessary but it's not harmful
// _data variable holds the data to be pushed to the server in the request.
// this piece of data holds the request to send a text message from the application
string _data = "{\"outboundSMSMessageRequest\":" +
"{\"address\": \"" + formatedAddress + "\",\"requestId\": \"" + request["requestId"] + "\"" +
",\"outboundSMSTextMessage\": \"" + messages[i] + "\",\"senderAddress\": \"" + request["sender"] + "\"" +
_optional + "}}";
//get a reference to the request-stream, and write the POST data (_data) to it
using (var s = new StreamWriter(_wr.GetRequestStream()))
{
s.Write(_data);
}
//get response-stream, and use a streamReader to read the content
try
{
HttpWebResponse _response = (HttpWebResponse)_wr.GetResponse();
}
catch (WebException ex)
{
using (StreamWriter file = new StreamWriter(@"D:\WEB\SMS\jsonResponse.txt", true))
{
file.WriteLine("No good");
}
// Log exception and throw as for GET example above
Trace.WriteLine("No good");
Trace.WriteLine(ex);
}
using (Stream s = _wr.GetResponse().GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
var jsonData = sr.ReadToEnd();
Trace.WriteLine("Server response: " + jsonData);
//decode jsonData with javascript serializer
using (StreamWriter file = new StreamWriter(@"D:\WEB\SMS\jsonResponse.txt", true))
{
file.WriteLine("Server response: " + jsonData);
}
}
}
}