Call Tracking with C# and ASP.NET MVC

January 10, 2017
Written by
Jose Oliveros
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by
Paul Kamp
Twilion
Kat King
Twilion

call-tracking-csharp

This ASP.NET MVC web application shows how you can use Twilio to track the effectiveness of different marketing channels.

This application has three main features:

  • It purchases phone numbers from Twilio to use in different marketing campaigns (like a billboard or a bus advertisement)
  • It forwards incoming calls for those phone numbers to a salesperson
  • It displays charts showing data about the phone numbers and the calls they receive

In this tutorial, we'll point out the key bits of code that make this application work. Check out the project README on GitHub to see how to run the code yourself.

Search for available phone numbers

Call tracking requires us to search for and buy phone numbers on demand, associating a specific phone number with a lead source. This class uses the Twilio C# Helper Library to search for phone numbers by area code and return a list of numbers that are available for purchase.

Editor: this is a migrated tutorial. Find the original at https://github.com/TwilioDevEd/call-tracking-csharp/

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Rest.Api.V2010.Account.AvailablePhoneNumberCountry;
using Twilio.Types;

namespace CallTracking.Web.Domain.Twilio
{
    public interface IRestClient
    {
        Task<IEnumerable<LocalResource>> SearchPhoneNumbersAsync(string areaCode);
        Task<IncomingPhoneNumberResource> PurchasePhoneNumberAsync(string phoneNumber, string applicationSid);
        Task<string> GetApplicationSidAsync();
    }

    public class RestClient : IRestClient
    {
        private readonly ITwilioRestClient _client;
        
        public RestClient()
        {
            _client = new TwilioRestClient(Credentials.TwilioAccountSid, Credentials.TwilioAuthToken);
        }

        public async Task<IEnumerable<LocalResource>> SearchPhoneNumbersAsync(string areaCode = "415")
        {
            var localNumbers = await LocalResource.ReadAsync(
                pathCountryCode: "US", areaCode: int.Parse(areaCode), client: _client);

            return localNumbers.ToList();
        }

        public async Task<IncomingPhoneNumberResource> PurchasePhoneNumberAsync(
            string phoneNumber, string applicationSid)
        {
            return await IncomingPhoneNumberResource.CreateAsync(
                voiceApplicationSid: applicationSid,
                phoneNumber: new PhoneNumber(phoneNumber),
                client: _client
            );
        }

        public async Task<string> GetApplicationSidAsync()
        {
            const string defaultApplicationName = "Call tracking app";
            var applications = await ApplicationResource.ReadAsync(defaultApplicationName, client: _client);

            var application = applications.FirstOrDefault() ?? 
                await ApplicationResource.CreateAsync(defaultApplicationName);

            return application.Sid;
        }
    }
}

Now let's see how we will display these numbers for the user to purchase them and enable their campaigns.

Display available phone numbers

We display a form to the user on the app's home page which allows them to search for a new phone number by area code. At the controller level we use the Twilio.RestClient we created earlier to actually search for numbers. This will render the view that contains a list of numbers they can choose to buy.

using System.Threading.Tasks;
using System.Web.Mvc;
using CallTracking.Web.Domain.Twilio;

namespace CallTracking.Web.Controllers
{
    public class AvailablePhoneNumbersController : Controller
    {
        private readonly IRestClient _restClient;

        public AvailablePhoneNumbersController()
            : this(new RestClient())
        {}

        public AvailablePhoneNumbersController(IRestClient restClient)
        {
            _restClient = restClient;
        }

        // GET: AvailablePhoneNumbers
        public async Task<ActionResult> Index(string areaCode)
        {
            var phoneNumbers = await _restClient.SearchPhoneNumbersAsync(areaCode);

            return View(phoneNumbers);
        }
    }
}

We've seen how we can display available phone numbers for purchase with the help of the Twilio C# helper library. Now let's look at how we can buy an available phone number.

Buy a phone number

Our PurchasePhoneNumber method takes two parameters, the first one is a phone number and the second one is the application SID. Now our Twilio API client can purchase the available phone number our user chooses.

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Rest.Api.V2010.Account.AvailablePhoneNumberCountry;
using Twilio.Types;

namespace CallTracking.Web.Domain.Twilio
{
    public interface IRestClient
    {
        Task<IEnumerable<LocalResource>> SearchPhoneNumbersAsync(string areaCode);
        Task<IncomingPhoneNumberResource> PurchasePhoneNumberAsync(string phoneNumber, string applicationSid);
        Task<string> GetApplicationSidAsync();
    }

    public class RestClient : IRestClient
    {
        private readonly ITwilioRestClient _client;
        
        public RestClient()
        {
            _client = new TwilioRestClient(Credentials.TwilioAccountSid, Credentials.TwilioAuthToken);
        }

        public async Task<IEnumerable<LocalResource>> SearchPhoneNumbersAsync(string areaCode = "415")
        {
            var localNumbers = await LocalResource.ReadAsync(
                pathCountryCode: "US", areaCode: int.Parse(areaCode), client: _client);

            return localNumbers.ToList();
        }

        public async Task<IncomingPhoneNumberResource> PurchasePhoneNumberAsync(
            string phoneNumber, string applicationSid)
        {
            return await IncomingPhoneNumberResource.CreateAsync(
                voiceApplicationSid: applicationSid,
                phoneNumber: new PhoneNumber(phoneNumber),
                client: _client
            );
        }

        public async Task<string> GetApplicationSidAsync()
        {
            const string defaultApplicationName = "Call tracking app";
            var applications = await ApplicationResource.ReadAsync(defaultApplicationName, client: _client);

            var application = applications.FirstOrDefault() ?? 
                await ApplicationResource.CreateAsync(defaultApplicationName);

            return application.Sid;
        }
    }
}

If you don't know where you can get this application SID, don't panic, the next step will show you how.

Set webhook URLs in a TwiML Application

When we purchase a phone number, we specify a voice application SID. This is an identifier for a TwiML application, which you can create through the REST API or your Twilio Console.

Create TwiML App

Associate a phone number with a lead source

Once we search for and buy a Twilio number, we need to associate it with a lead source in our database. This is the core of a call tracking application. Any phone calls to our new Twilio number will be attributed to this source.

using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
using CallTracking.Web.Domain.Twilio;
using CallTracking.Web.Models;
using CallTracking.Web.Models.Repository;
using HttpStatusCodeResult = System.Web.Mvc.HttpStatusCodeResult;

namespace CallTracking.Web.Controllers
{
    public class LeadSourcesController : Controller
    {
        private readonly IRepository<LeadSource> _repository;
        private readonly IRestClient _restClient;

        public LeadSourcesController()
            : this(new LeadSourcesRepository(), new RestClient()) { }

        public LeadSourcesController(IRepository<LeadSource> repository, IRestClient restClient)
        {
            _repository = repository;
            _restClient = restClient;
        }

        // POST: LeadSources/Create
        [HttpPost]
        public async Task<ActionResult> Create(string phoneNumber)
        {
            var twiMLApplicationSid = Credentials.TwiMLApplicationSid ?? await _restClient.GetApplicationSidAsync();
            var twilioNumber = await _restClient.PurchasePhoneNumberAsync(phoneNumber, twiMLApplicationSid);

            var leadSource = new LeadSource
            {
                IncomingNumberNational = twilioNumber.FriendlyName,
                IncomingNumberInternational = twilioNumber.PhoneNumber?.ToString()
            };

            _repository.Create(leadSource);

            return RedirectToAction("Edit", new {id = leadSource.Id});
        }

        // GET: LeadSources/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var leadSource = _repository.Find(id.Value);
            if (leadSource == null)
            {
                return HttpNotFound();
            }

            return View(leadSource);
        }

        // POST: LeadSources/Edit/
        [HttpPost]
        public ActionResult Edit(
            [Bind(Include = "Id,Name,IncomingNumberNational,IncomingNumberInternational,ForwardingNumber")]
            LeadSource leadSource)
        {
            if (ModelState.IsValid)
            {
                _repository.Update(leadSource);
                return RedirectToAction("Index", new { Controller = "Dashboard" });
            }

            return View(leadSource);
        }
    }
}

So far our method for creating a Lead Source and associating a Twilio phone number with it is pretty straightforward. Now let's have a closer look at our Lead Source model which will store this information.

Define the LeadSource model

The LeadSource model associates a Twilio number to a named lead source (like "Wall Street Journal Ad" or "Dancing guy with sign"). It also tracks a phone number to which we'd like all the calls redirected, like your sales or support helpline.

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace CallTracking.Web.Models
{
    public class LeadSource
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string IncomingNumberNational { get; set; }
        public string IncomingNumberInternational { get; set; }
        [Display(Name = "Forwarding Number")]
        public string ForwardingNumber { get; set; }
        public virtual IList<Lead> Leads { get; set; }
    }
}

As the application will be collecting leads and associating them to each LeadSource or campaign, it is necessary to have a Lead model as well to keep track of each Lead as it comes in and associate it to the LeadSource.

Define the Lead model

A Lead represents a phone call generated by a LeadSource. Each time somebody calls a phone number associated with a LeadSource, we'll use the Lead model to record some of the data Twilio gives us about their call.

namespace CallTracking.Web.Models
{
    public class Lead
    {
        public int Id { get; set; }
        public string PhoneNumber { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public int LeadSourceId { get; set; }
        public virtual LeadSource LeadSource { get; set; }
    }
}

The backend part of the code which creates a LeadSource as well as a Twilio Number is complete. The next part of the application will be the webhooks that will handle incoming calls and forward them to the appropriate sales team member. Let's us see the way these webhooks are built.

Forward calls and create leads

Whenever a customer calls one of our Twilio numbers, Twilio will send a POST request to the URL associated with this action (should be /CallTracking/ForwardCall).

We use the incoming call data to create a new Lead for a LeadSource, then return TwiML that connects our caller with the ForwardingNumber of our LeadSource.

using System.Web.Mvc;
using CallTracking.Web.Models;
using CallTracking.Web.Models.Repository;
using Twilio.AspNet.Mvc;
using Twilio.TwiML;

namespace CallTracking.Web.Controllers
{
    public class CallTrackingController : TwilioController
    {
        private readonly IRepository<LeadSource> _leadSourcesRepository;
        private readonly IRepository<Lead> _leadsRepository;

        public CallTrackingController()
            : this(new LeadSourcesRepository(), new LeadsRepository()) { }

        public CallTrackingController(IRepository<LeadSource> leadSourcesRepository, IRepository<Lead> leadsRepository)
        {
            _leadSourcesRepository = leadSourcesRepository;
            _leadsRepository = leadsRepository;
        }

        // POST: CallTracking/ForwardCall
        [HttpPost]
        public ActionResult ForwardCall(string called, string caller, string fromCity, string fromState)
        {
            var leadSource = _leadSourcesRepository.FirstOrDefault(x => x.IncomingNumberInternational == called);
            _leadsRepository.Create(new Lead
            {
                LeadSourceId = leadSource.Id,
                City = fromCity,
                State = fromState,
                PhoneNumber = caller
            });

            var response = new VoiceResponse();
            var dial = new Dial();
            dial.Number(leadSource.ForwardingNumber);

            response.Dial(dial);

            return TwiML(response);
        }
    }
}

Once we have forwarded calls and created leads, we will have a lot of incoming calls that will create leads, and that will be data for us but we need to transform that data into information in order to get benefits from it. So, let's see how we get statistics from these sources on the next step.

Getting statistics about our lead sources

One useful statistic we can get from our data is how many calls each LeadSource has received. We use LINQ to make a list containing each LeadSource and a count of its Lead models.

using System.Linq;
using System.Web.Mvc;
using CallTracking.Web.Models;
using CallTracking.Web.Models.Repository;

namespace CallTracking.Web.Controllers
{
    public class StatisticsController : Controller
    {
        private readonly IRepository<Lead> _leadsRepository;

        public StatisticsController()
            : this(new LeadsRepository()) { }

        public StatisticsController(IRepository<Lead> leadsRepository)
        {
            _leadsRepository = leadsRepository;
        }

        // GET: Statistics/LeadsBySource
        public ActionResult LeadsBySource()
        {
            var leads = _leadsRepository.All().Select(x => new {x.LeadSource.Name});
            var response = leads.GroupBy(x => x.Name).Select(group => new {label = group.Key, value = group.Count()}).ToList();

            return Json(response, JsonRequestBehavior.AllowGet);
        }

        // GET: Statistics/LeadsByCity
        public ActionResult LeadsByCity()
        {
            var response = _leadsRepository.All().GroupBy(x => x.City).Select(group => new { label = group.Key, value = group.Count() });
            return Json(response, JsonRequestBehavior.AllowGet);
        }
    }
}

Up until this point, we have been focusing on the backend code to our application. Which is ready to start handling incoming calls or leads. Next, let's turn our attention to the client side. Which, in this case, is a simple Javascript application, along with Chart.js which will render these stats in an appropriate way.

Visualizing the statistics with Chart.js

On the client side, we fetch call tracking statistics in JSON from the server using jQuery. We display the stats in colorful pie charts we create with Chart.js.

$(document).ready(function () {
    $.get("/statistics/leadsbysource/", function (data) {
        CallTrackingGraph("#leads-by-source", data).draw();
    });

    $.get("/statistics/leadsbycity/", function (data) {
        CallTrackingGraph("#leads-by-city", data).draw();
    });
});

CallTrackingGraph = function (selector, data) {
    function getContext() {
        return $(selector).get(0).getContext("2d");
    }

    return {
        draw: function () {
            var context = getContext(selector);
            new Chart(context).Pie(data);
        }
    }
}

That's it! Our ASP.NET MVC application is now ready to purchase new phone numbers, forward incoming calls, and record some statistics for our business.

Where to next?

If you're a C# developer working with Twilio, you might also enjoy these tutorials:

Automated Survey (C#)

Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages.

Appointment Reminders (C#)

Learn to implement appointment reminders in your web app with Twilio. Appointment reminders allow you to automate the process of reaching out to your customers in advance of an upcoming appointment.

Did this help?

Thanks for checking this tutorial out! If you have any feedback to share with us please contact us on Twitter, we'd love to hear it.