• Anthony Stevens

Twilio Demo #3: Appointment Reminder using the REST API

Software, Web

My last Twilio demo showed how you could call Twilio and retrieve information from a web application you’ve built.  This demo shows the reverse scenario: you use a web application that calls out to Twilio, which in turn calls out to a given phone number.

This will be a pretty straightforward translation of Twilio’s existing Appointment Reminder demo, which is written in Ruby.

WARNING: Use this power only for good.  For example, you wouldn’t dream of rickrolling anyone, would you? :)

Let’s get started.  Our web app will be written in ASP.NET/C#, and, unlike the previous example, has no database backend, for simplicity’s sake.  In a real-life application, you would pull these reminders from a database on a schedule; but here we’ll bypass that part.

Before you get started, you’ll need to download the C# REST helper library from the Twilio website. This contains some code that wraps the messy network communications.

Add the file twiliorest.cs to your web application project.

You’ll need two ASPX pages: a page that captures the phone number you want Twilio to call, and a page that Twilio uses to decide what to do based on the callee’s responses.

Here’s the web form to capture input. Put this in your <form> tag in a new web form page called default.aspx:

Twilio phone reminder demo

Enter your phone number to receive an automated reminder

Here’s the code-behind in default.aspx.cs:

using System;
using System.Collections;
using TwilioRest;

namespace Twilio.Web.appointment
{
    public partial class _default : System.Web.UI.Page
    {
	protected const string ACCOUNT_SID = "SSSSSSSSSSSSSSSSSSSSSSSSSSSSS";
        protected const string AUTH_TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        protected const string API_VERSION = "2008-08-01";
        protected const string CALLER_ID = "NNN-NNN-NNNN";

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            string phoneNumber = Server.HtmlEncode(this.PhoneNumberText.Text);
            this.MakeTwilioCall(phoneNumber);
        }

        protected virtual void MakeTwilioCall(string phoneNumber)
        {
            TwilioRest.Account account = new Account(ACCOUNT_SID, AUTH_TOKEN);

            // create the URL at Twilio to post to
            string postUrl = "/{0}/Accounts/{1}/Calls";
            postUrl = string.Format(postUrl, API_VERSION, ACCOUNT_SID);

            // create the variables to pass in to the POST
            string reminderUrl = Page.Request.Url.GetLeftPart(UriPartial.Authority) + "/appointment/reminder.aspx";
            Hashtable vars = new Hashtable(3);
            vars.Add("Caller", CALLER_ID);
            vars.Add("Called", phoneNumber);
            vars.Add("Url", reminderUrl);
            try
            {
                string response = account.request(postUrl, "POST", vars);
            }
            catch (Exception exc)
            {
                this.MessageElement.InnerText = exc.Message;
            }
        }
    }
}

What we’re doing here is simply handling the button click event and then using the Twilio helper library to make the RESTful call to the Twilio servers. Of course you need to put your own values in for ACCOUNT_SID, AUTH_TOKEN, and CALLER_ID, which you can get from your Account page on the Twilio website.

Twilio will call the phone number you enter in the text box, and use a new page /appointment/reminder.aspx (which you have to create) as the “controller” for the outbound call.

Your reminder.aspx page should be blank (since you will be writing XML output, not HTML). Here’s the code-behind for reminder.aspx:

using System;
using System.Collections;
using System.Xml;

namespace Twilio.Web.appointment
{
    public partial class reminder : System.Web.UI.Page
    {
        protected string Url = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Response.ContentType = "text/xml";
            this.Url = Page.Request.Url.GetLeftPart(UriPartial.Authority) + "/appointment/reminder.aspx";

            if (Request["Digits"] != null)
            {
                DoAction(int.Parse(Request["Digits"].ToString()));
            }
            else
            {
                this.WriteReminder();
            }
        }

        protected virtual void DoAction(int digit)
        {
            switch (digit)
            {
                case 3:
                    {
                        WriteGoodbye();
                        break;
                    }
                case 2:
                    {
                        WriteDirections();
                        break;
                    }
                default:
                    {
                        WriteReminder();
                        break;
                    }
            }
        }

        protected virtual void WriteGoodbye()
        {
            this.WriteXmlToResponse("goodbye.xml", null);
        }

        protected virtual void WriteDirections()
        {
            this.WriteXmlToResponse("directions.xml", new string[1] { this.Url });
        }

        protected virtual void WriteReminder()
        {
            this.WriteXmlToResponse("reminder.xml", new string[1] { this.Url });

        }

        ///
        /// XML helper method
        ///
        protected virtual void WriteXmlToResponse(string fileName, string[] values)
        {
            System.Xml.XmlDocument doc = new XmlDocument();
            string path = Server.MapPath(Page.Request.ApplicationPath) + @"\appointment\" + fileName;
            doc.Load(path);
            string xml = doc.OuterXml;
            xml = string.Format(xml, values);
            Response.Write(xml);
        }
    }
}

We’re using the same WriteXmlToResponse() helper method we created in our last demo. There are three output functions: WriteReminder(), WriteDirections(), and WriteGoodbye(), which correspond to the three choices the user can make when they receive the phone call.

Also note that we set the MIME content-type to “text/xml” in the first line of Page_Load().

Not much to it, is there?

To make this demo work, you’ll also need three XML files that contain the content to read to the user:

reminder.xml


			Hello this is a call from Crowdify.  You have an appointment tomorrow at 9 AM.

			Please press 1 to repeat this menu. Press 2 for directions.	Or press 3 if you are done.

directions.xml


	Your appointment is located on the top of Mount Everest.
	{0}

goodbye.xml


	Good bye.

Note that in the first two XML files we are using the same String.Format() placeholders as in our previous demo.

That’s it – an end-to-end demo of using the Twilio REST API. The helper library that Twilio provides makes it really easy to get going in no time at all.

UPDATE: I’ve zipped the source (which includes code for all three recent Twilio demos) and saved it at http://thepursuitofalife.com/wp-content/uploads/2009/01/twilio-demo.zip.

Technorati Tags: ,,

8 Comments

6 Comments

  1. SK  •  Jan 20, 2009 @6:59 pm

    Unable to build the project using the directions above. Could you please post the entire project solution in a zip file that we could download.

  2. anthonyrstevens  •  Jan 21, 2009 @12:44 pm
  3. Niral Patel  •  Jul 26, 2010 @9:20 pm

    hey u have done so good
    and you helps us lot doing this application

    Thanks a lot and god bless you

  4. Niral Patel  •  Jul 28, 2010 @3:37 am

    hi can u please let me know the Code for recording a Sound by the caller

  5. Niral Patel  •  Jul 28, 2010 @3:38 am

    and also save that record to databse too, Please let me know if u can help me out for this..

    Thanks a Lot for All u have done for me.

  6. sandeep  •  Jan 21, 2011 @4:59 am

    i’m using twilio acc in c#.net for appointment reminder but while i’m debug the the code i’m getting the voice message like thanks for using twilio account bla blaa and its says that application error 11220 ? can any one help?

2 Trackbacks