Sending SMS Using TheTexting SMS Gateway With C#

Introduction

In this article, I will walk you through a quick and interesting way to send SMS using a simple C# application. I wanted to make it as easy as possible for you, so I have created both, the Windows and web version in order to demonstrate the instructions that I will explain in this article. So, just follow these easy steps as I walk you through the whole process and in no time, sending SMS will be a piece of cake for you.

As mobile phones have become part and parcel of our everyday lives and none of us can do without them anymore, it is no wonder that statistics have shown that SMS is the most effective way to communicate, especially when it comes to any type of business communication. With this in mind I set out to show you an easy way to send SMS.

I am going to use TheTexting SMS API to send SMS. Since there are many other SMS gateways, you can try out some of them using their free trial version. Personally, TheTexting SMS API is my cup of tea since it provides larger number of free test sms and good technical documentations as well so I will use thetexting as sms gateway in this article.

Different ways of sending text messages?

  1. Using GSM Modem
    This would be the best choice if you want to implement offline applications and if you want to send a small number of SMS for every minute then using GSM modem is the best choice.

  2. Using endpoints
    It is best choice when the number of SMS needed to be sent exceeds a hundred per minute.

  3. Using web service
    This would be a best choice for an online application and a very few number of SMS go every minute.

Sending SMS via web service

Let’s start without going deeper into the unnecessary details about competitors in the market. Going in depth at this stage will only make it more confusing and it is not my intention to give you a headache. I will go through the process step by step so that you can fallow effortlessly.

Get Started

The first thing you need to do is create an account on http://www.thetexting.com , so what you need to do is click on this link while holding the CTRL key on your keyboard. You can also copy and paste the link into your browser window and hit enter key of your keyboard.


Fig 1.0

Then, click on the sign up link as shown above. When you click on this link, you will be redirected to the following page.

Fig 1.1

Just fill out this form with the required information and then submit the form. You will receive a verification SMS on the contact number that you have provided here while signing up and you will also receive a verification email on the email address that you have specified. In order to get your account activated with thetexting.com, you need to verify both, your number and your email address. You can see in the figure below how it should look.


Fig 1.2

After verification of number and email, you will be redirected to the following page.


Fig 1.3

Here, you can see your balance, Dashboard, products, API settings, profile, and developer reference. API settings are crucial for us now. Just click on API settings to check your Key and Secret values, as shown below.


Fig 1.4

Here, you can see your API_KEY and SECRET values for your account but you can also generate a new API Key by clicking on the button Generate API Key.

Service URL

https://www.thetexting.com/rest/sms/json/message/send?api_key=wwpiub1oipk49a1&api_secret=j5h suac8877mdzdd&to=923218829981&text=Hello"

This is the API service URL which our Web client will be comsuming. You can just change the api-key,api_secret and to parameters and paste it into your browser window and hit enter. At this point you will be able to send SMS without creating any applications. Isn’t that great?

Now, let’s start with our demo application. At this point we will be creating a WPF application. Again, I do not want to spin my article out, so here I will not teach you about WPF if those who are really new to WPF can follow one of the best links which is given below secondly this code would work for windows form application as well, so it’s your preference either you love WPF or windows Form.

https://msdn.microsoft.com/en-us/library/aa970268(v=vs.100).aspx

After you create a simple WPFform, it will look something like the image below,


Here, you can see four parameter values. API_KEY,API_SECREAT are the Keys which you have given after signing up to thetexting.com which you can see in fig 1.4 and you can get these values by login to http://www.thetexting.com . Then go to API Setting link. To is the number which you want to send SMS to, but don’t forget to write the country code with the number as well, just like I did (1 is for United states). Send message is the message which you want to send. Since we have subscribed to test account we cannot provide the from parameters and custom message here, so the from and Message body would have the default values.

C # code for sending SMS 

  1. public class Response  
  2.         {  
  3.             public string message_id { get; set; }  
  4.             public int message_count { get; set; }  
  5.             public double price { get; set; }  
  6.         }  
  7.   
  8.         public class RootObject  
  9.         {  
  10.             public Response Response { get; set; }  
  11.             public string ErrorMessage { get; set; }  
  12.             public int Status { get; set; }  
  13.         }  
  14.       
  15.         private void button1_Click(object sender, RoutedEventArgs e)  
  16.         {  
  17.             string key = txtKey.Text;  
  18.             string secret = txtSecret.Text;  
  19.             string to = txtTo.Text;  
  20.             string messages = txtMessage.Text;  
  21.             
  22.             string sURL;  
  23.            
  24.              
  25.             sURL = "https://www.thetexting.com/rest/sms/json/message/send?api_key=" + key + "&api_secret=" + secret + "&to=" + to + "&text=" + messages;  
  26.               
  27.             try  
  28.             {  
  29.                   
  30.                     using (WebClient client = new WebClient())  
  31.                    {  
  32.   
  33.                        string s = client.DownloadString(sURL);  
  34.                           
  35.                 var responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(s);  
  36.                 int n=responseObject.Status;  
  37.                 if (n == 3)  
  38.                 {  
  39.                     MessageBox.Show("Something went wrong with your credentials""My Demo App");  
  40.   
  41.                 }  
  42.                 else  
  43.                 {  
  44.                    MessageBox.Show("Message Send Successfully""My Demo App");  
  45.                 }  
  46.   
  47.                    }  
  48.                     
  49.   
  50.             }  
  51.             catch (Exception ex)  
  52.             {  
  53.                 MessageBox.Show("Something went wrong with your information""My Demo App");  
  54.                 ex.ToString();  
  55.             }  
  56.         }  
  57.   
  58.          
  59.     }   

Here we have a very simple code. We have created four variables and we are assigning the four text boxes values to these four variables . Next we are creating a string variable of URL and giving it our service URL and embedding our parameters values with it.with this URL{this URL is basically the address of our REST service}, then we are using webclient to download the data , as our service return data in json so now we want to read this json result using c# , again here we have two methods to do that, one is to pull this whole data into the datatable and then read from datatable but the best approach is to deserialize json data , so we have created two class Response and RootObject and they have their own properties message id , count,price,status etc then we are using Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(s) to convert the json data to c# and then we are reading the status value to show the specified message to you user i.e. if the status code is 3 then it means that authentication failed and show this message to the user.

If you need details about how to Deserialize Json Data then visit

http://stackoverflow.com/questions/7895105/deserialize-json-with-c-sharp

Just replace these values of API_KEY, API_SECRET , TO with your own API_KEY , API_ SECRET, TO, then click the send button and your message will be sent to the desired number.

Namespaces Required 

  1. using System.Text;    
  2. using System.Windows;    
  3. using System.Windows.Controls;    
  4. using System.Windows.Data;    
  5. using System.Windows.Documents;    
  6. using System.Windows.Input;    
  7. using System.Windows.Media;    
  8. using System.Windows.Media.Imaging;    
  9. using System.Windows.Navigation;    
  10. using System.Windows.Shapes;    
  11. using System.IO;    
  12. using System.Net;    
  13. using System.Data;    
  14. using System.Xml;    
  15. using Newtonsoft.Json;   
Note

You must include Newtonsoft.Json.dll into your references, the demo application having already included Newtonsoft.Json.dll but for double check if you are going to create your own wpf application I have also copied this dll into the demo example attachment’s.

I have already defined the TheTexting API and its key parameters in the previous section. In addition to that I have also attached a demo for web application. Keep in mind that before you can use their gateway to send SMS, you need to sign up for an account with thetexting.com.

Software Requirements to run the demo for MVC

  1. You should have installed Visual studio 2015
  2. You should have MVC5 installed as well
  3. Json.dll reference need to be added

Here are the steps to open the demo project,

  • Download the project and extract it to your desired folder.
  • Open up visual studio.
  • Click on File Menu then select open project from the menu a window will pop up find the location where you unzipped the project and select TheTextingDemo.sln and click open.
  • This is a pre templated MVC project I just have added a simple class in the models folder with name cs to set the configuration like API KYE,SECRET,TO,MESSAGE etc.
  • Then I have just modified the index.cshtml view and home Controller.

Our class definition is like below 

  1. using System.Linq;  
  2. using System.Web;  
  3. namespace TheTextingDemo.Models  
  4. {  
  5.     public class ConfigurationSettings  
  6.     {  
  7.         [Key]  
  8.         [ScaffoldColumn(false)]  
  9.         public int RecordID { getset; }  
  10.   
  11.         [Required(ErrorMessage = "API_KEY is required")]  
  12.         [Display(Name = "Enter API_KEY Name")]  
  13.         public string API_KEY { getset; }  
  14.         [Required(ErrorMessage = "API_SECRET is required")]  
  15.         public string API_SECRET { getset; }  
  16.         [Required(ErrorMessage = "To_Number  is required")]  
  17.         [Display(Name = "To_Number")]  
  18.         public double To_Number { getset; }  
  19.         //[DataType(DataType.PhoneNumber)]    
  20.         [Required(ErrorMessage = "Message  is required")]  
  21.         public string TextMessage { getset; }  
  22.     }  
  23. }  
For the sake of clarity, I will not drag the article out by defining each and everything related to MVC and c#. If you are not best friends with MVC you can find all about it on https://www.asp.net/mvc/overview .

Index.cshtml 

  1. @model  TheTextingDemo.Models.ConfigurationSettings  
  2.   
  3.   
  4. <h2>TheTexting SMS GateWay Demo</h2>  
  5. <style type="text/css">  
  6.     .required:after {  
  7.         padding-left: 10px;  
  8.         content: "*";  
  9.         font-weight: bold;  
  10.         color: red;  
  11.     }  
  12. </style>  
  13. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>  
  14. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>  
  15. @Html.ValidationSummary(true"Correct The Errors first.")  
  16. @using (Html.BeginForm("SendSMS""Home", FormMethod.Post))  
  17. {  
  18.   
  19.     <div>  
  20.         <fieldset>  
  21.             <legend>Account Information</legend>  
  22.             <div>  
  23.                 <h3>Note: all the fields with (*) are required fields.</h3>  
  24.   
  25.   
  26.             </div>  
  27.             <div>  
  28.                 @Html.LabelFor(model => model.API_KEY, new { @class = "required" })  
  29.             </div>  
  30.             <div>  
  31.   
  32.                 @Html.TextBoxFor(model => model.API_KEY)  
  33.                 @Html.ValidationMessageFor(model => model.API_KEY)  
  34.             </div>  
  35.             <div>  
  36.                 @Html.LabelFor(model => model.API_SECRET, new { @class = "required" })  
  37.             </div>  
  38.             <div>  
  39.                 @Html.TextBoxFor(model => model.API_SECRET)  
  40.                 @Html.ValidationMessageFor(model => model.API_SECRET)  
  41.             </div>  
  42.             <div>  
  43.   
  44.                 @Html.LabelFor(a => a.To_Number, new { @class = "required" })  
  45.   
  46.   
  47.             </div>  
  48.             <div>  
  49.   
  50.                 @Html.TextBoxFor(a => a.To_Number)  
  51.   
  52.   
  53.                 @Html.ValidationMessageFor(a => a.To_Number)  
  54.             </div>  
  55.             <div>  
  56.                 @Html.LabelFor(a => a.TextMessage, new { @class = "required" })  
  57.   
  58.   
  59.             </div>  
  60.             <div>  
  61.                 @Html.TextAreaFor(a => a.TextMessage, new { @Value = "test" })  
  62.   
  63.                 @Html.ValidationMessageFor(a => a.TextMessage)  
  64.             </div>  
  65.   
  66.             <br />  
  67.   
  68.   
  69.             <input id="Submit" type="submit" value="SendSMS" />  
  70.             <br /><br />  
  71.             <h4 style="display:inline; color:red;">  
  72.                 Note:  
  73.                 <p style="display:inline;">Number must contain the country code like for us we have 1-3306807200</p>  
  74.             </h4>  
  75.   
  76.   
  77.         </fieldset>  
  78.   
  79.   
  80.     </div>  
  81.   
  82. }   

As I want to get access of these textboxes into my controller action so I make this view as strongly typed view as @model TheTextingDemo.Models.ConfigurationSettings

  • Next I create an action method in the home controller with [httppost] attribute because from our view we want to get the values of all textboxes which the user typed in, so our controller method looks like this.

C# code for Send SMS {home Controller} 

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5. using System.Web.Mvc;    
  6. using System.IO;    
  7. using System.Net;    
  8. using System.Web.UI.WebControls;    
  9. using TheTextingDemo.Models;    
  10. namespace TheTextingDemo.Controllers    
  11. {    
  12.     public class HomeController : Controller    
  13.     {    
  14.     
  15.         public class Response    
  16.         {    
  17.             public string message_id { getset; }    
  18.             public int message_count { getset; }    
  19.             public double price { getset; }    
  20.         }    
  21.     
  22.         public class RootObject    
  23.         {    
  24.             public Response Response { getset; }    
  25.             public string ErrorMessage { getset; }    
  26.             public int Status { getset; }    
  27.         }    
  28.         public ActionResult Index()    
  29.         {    
  30.             return View();    
  31.         }    
  32.         [HttpPost]    
  33.         public ActionResult SendSMS(ConfigurationSettings sm)    
  34.         {  
  35.             string API_KEY = sm.API_KEY;    
  36.             string API_SECRET = sm.API_SECRET;    
  37.             double TO = Convert.ToDouble(sm.To_Number);    
  38.             string Message = sm.TextMessage;    
  39.             string sURL;  
  40.             sURL = "https://www.thetexting.com/rest/sms/json/message/send?api_key=" + API_KEY + "&api_secret=" + API_SECRET + "&to=" + TO + "&text=" + Message;  
  41.             if (ModelState.IsValid)    
  42.             {  
  43.                 try  
  44.                 {  
  45.                     using (WebClient client = new WebClient())    
  46.                     {    
  47.     
  48.                         string s = client.DownloadString(sURL);    
  49.     
  50.                         var responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(s);    
  51.                         int n = responseObject.Status;    
  52.                         if (n == 3)    
  53.                         {    
  54.                             return Content("<script>alert('Message does not Send Successfully due to invalid credentials !');location.href='/';</script>");  
  55.                         }    
  56.                         else    
  57.                         {    
  58.                             return Content("<script>alert('Message Send Successfully !');location.href='/';</script>");    
  59.                         }  
  60.                     }   
  61.                 }   
  62.                 catch (Exception ex)    
  63.                 {  
  64.                     ModelState.AddModelError("""Error in sending Message");    
  65.                     ex.ToString();    
  66.                 }  
  67.                 return View("Index");  
  68.             }    
  69.             else    
  70.             {  
  71.                 ModelState.AddModelError("""Error in sending Message");  
  72.                 return View("Index");    
  73.             }  
  74.         }  
  75.     }    
  76. }     
All the c # code is similar just the semantics and structure of windows application vs web applications are different and I promise that I have defined all these details above so when you run the project the following screen will appear .

You should just replace the API_KEY and API_SECRET Values with the ones you have given after creation of your account and click the sendSMS button.

Source Code Files

I have attached source code files for both windows and web:

  1. For windows - TheTextingDemoAppWindows.zip
  2. For web - TheTextingDemo MVC.zip
Conclusion

Now, you can pause and catch your breath. I hope you didn’t get lost in my explanations. If you have followed the steps closely, you should be able to send SMS using C# application with thetexting.com without much difficulty. I did my very best to make it simple and to walk you through all the details as painlessly as possible. I hope this article will be helpful to all the readers and especially to beginners.

References

Note

If you face any problem while restoring the TheTextingDemo MVC.zip into Visual Studio 2015, you can download the project from Dropbox as well. Given below is the link of dropbox folder containing all files and packages.

https://www.dropbox.com/sh/ezlxh722srf8zgl/AAA-sB4nBb29i_x9ZexkE8FGa?dl=0


Similar Articles