How to make phone calls and send SMS with C#

C# and how to send phone calls and messaging using C#

Bandwidth has a full suite of messaging API and voice API solutions to power your business’ needs.

Whether you want to send messages from toll-free numbers, local numbers, or short codes, it’s easy to enable messaging via API in your software or platform, while Bandwidth’s relationships with the carriers give you reliable message delivery and insights. 

In this article, you will see a quick overview of what sending your first message and creating your first call looks like when using Bandwidth’s Voice and Messaging APIs along with Bandwidth’s C# SDK and .NET Core. First you will see some code examples and then at the end of this article is an explanation of the variables you would need to insert into the code to make the SDK work with your Bandwidth account.

Additional resources:

Packages and Client Initialization

First you need to install the SDK package needed for this example like this where directory_name is where you want to save the package and then add to your project dependencies as needed by your project.

nuget install Bandwidth.Sdk -OutputDirectory {directory_name}
nuget install Microsoft.AspNetCore.App -OutputDirectory {directory_name}

You then need to initialize the configuration for the SDK client and the API controllers for Voice and Messaging.

using Bandwidth.Standard

namespace BandwidthFirstApp
{

    public class StartWithBandwidth
    {

        private static BandwidthClient client = new BandwidthClient.Builder()
                .MessagingBasicAuthCredentials( "{username}", "{password}" )
                .VoiceBasicAuthCredentials( "{username}", "{password}" )
                .Build();

        }

        public static Bandwidth.Standard.Messaging.Controllers.APIController messagingController = client.Messaging.APIController;

        public static Bandwidth.Standard.Voice.Controllers.APIController voiceController = client.Voice.APIController;
        
    }

}

How to send a text message with C#

Sending a SMS Message with C# from a Bandwidth number looks like this. This must be in the StartWithBandwidth class or the client must be imported.

using Bandwidth.Standard.Messaging.Models;
using System.Collections.Generic;

MessageRequest messageRequest = new MessageRequest();
messageRequest.ApplicationId = "{app_id}";
messageRequest.To = new List<string> { "{to}" };
messageRequest.From = "{from}";
messageRequest.Text = "Hello, I am sending a message! How fun!";

//this line is needed only for .NET Core
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

var response = messagingController.CreateMessage("{account_id}", messageRequest);

You will need to set up a server that can receive a callback/webhooks with a JSON body that will tell you if the message was successfully delivered or not. Some simple C# server code using ASP.NET Core that can process Bandwidth messaging callbacks could look like this.

First the Program class.

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace BandwidthFirstApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

Then the Startup class.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace BandwidthFirstApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseHsts();
            app.UseMvc();
        }
    }
}

And then, the controller for our endpoint that can receive callbacks.

using Bandwidth.Standard;
using Bandwidth.Standard.Messaging.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace BandwidthFirstApp.Controllers
{
    public class Message
    {
        public string Id { get; set; }
        public string Time { get; set; }
        public string[] To { get; set; }
        public string From { get; set; }
        public string Text { get; set; }
        public string ApplicationId { get; set; }
        public string Owner { get; set; }
        public string Direction { get; set; }
        public int SegmentCount { get; set; }
    }

    public class MessagingCallbackData
    {
        public string Type { get; set; }
        public string Time { get; set; }
        public string Description { get; set; }
        public string To { get; set; }
        public Message Message { get; set; }
    }

    [Route("messaging")]
    [ApiController]
    public class ValuesController : Controller
    {

        private static BandwidthClient client = new BandwidthClient.Builder()
            .VoiceBasicAuthCredentials("{user}", "{password}")
            .MessagingBasicAuthCredentials("{token}", "{secret}")
            .Build();

        public static Bandwidth.Standard.Messaging.Controllers.APIController messagingController = client.Messaging.APIController;

        public static Bandwidth.Standard.Voice.Controllers.APIController voiceController = client.Voice.APIController;


        [HttpPost]
        public StatusCodeResult Post([FromBody] MessagingCallbackData[] messagingCallbackData)
        {
            if (messagingCallbackData[0].Type == "message-delivered")
            {
                //successful delivery action
                return StatusCode(200);
            }

            if (messagingCallbackData[0].Type == "message-failed")
            {
                string failureReason = messagingCallbackData[0].Description;
                //failed delivery action
                return StatusCode(200);

            }

            return StatusCode(200);
        }
    }
}

How to make a phone call using C#

Making a phone call using C# from a Bandwidth number looks like this. This must be in the StartWithBandwidth class or the client must be imported.

Voice.Models.ApiCreateCallRequest apiCreateCallRequest = new ApiCreateCallRequest();
apiCreateCallRequest.To = "{to}";
apiCreateCallRequest.From = "{from}";
apiCreateCallRequest.AnswerUrl = "{url}";
apiCreateCallRequest.ApplicationId = "{app_id}";

//this line is needed only for .NET Core
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

voiceClient.CreateCall("{account_id}", apiCreateCallRequest);

When the call is answered by whoever you sent the call to, Bandwidth will send a callback/webhook with a JSON body to the URL you specified when you created the call. You can send BXML verbs back to Bandwidth in response to the callback/webhook in order to create new actions on the call. Some simple server code that would make the call play some text-to-speech audio and then hang up could look like this (please reference the Messaging section for examples of the Program and Startup classes).

using Bandwidth.Standard.Voice.Bxml;
using Microsoft.AspNetCore.Mvc;

namespace StartWithBandwidth.Controllers
{   

    public class VoiceCallbackData
    {
        public string EventType { get; set; }
        public string AccountId { get; set; }
        public string ApplicationId { get; set; }
        public string From { get; set; }
        public string To { get; set; }
        public string Direction { get; set; }
        public string CallId { get; set; }
        public string CallUrl { get; set; }
        public string StartTime { get; set; }
        public string AnswerTime { get; set; }
        //depending on your use case, you will need to add more strings here to accommodate the data in other Voice callbacks besides Answer
    }

    [Route("/voice")]
    [ApiController]
    public class ValuesController : Controller
    {

        [HttpPost]
        public void Post([FromBody] VoiceCallbackData callback)
        {
            if (callback.EventType == "answer")
            {
                Response response = new Response();

                SpeakSentence speakSentence = new SpeakSentence();
                speakSentence.Sentence = "I am saying something and now will hang  up.";
                speakSentence.Voice = "julie";

                Hangup hangup = new Hangup();

                response.Add(speakSentence);
                response.Add(hangup);
                
                return response.ToBXML();
            }

            return "";
         }
    }

}

And that’s it! That’s how simple it is to create your first message and call with a Bandwidth phone number, Bandwidth’s API, and Bandwidth’s C# SDK.

Variable Reference

Here is an explanation of the variables used in the above code that will be unique to your account and use case.

Variable Name Explanation
username your username for the Bandwidth Dashboard
password your password for the Bandwidth Dashboard
app_id the ID of your messaging or voice application; applications are set within the Bandwidth Dashboard and are used associate your Bandwidth phone numbers with URLs for callback/webhooks
from_number when creating outgoing messages or calls, the number you are sending to; this can be your cell phone number for testing or the number of one of your customers
to_number when creating outgoing messages or calls, this is a number you have been assigned by Bandwidth that lives on your Bandwidth Dashboard account
account_id your Bandwidth Dashboard account ID
url a URL you own that to which Bandwidth will send callbacks/webhooks related to call and messaging events; note that for messaging, this URL is not set at the time of message creation and is instead defined by the Bandwidth Dashboard application used to send the message

Developing with Bandwidth – C#

Looking for additional information on developing with C#? The webinar below goes into greater detail on the topics presented in this post.