Ahoy! We now recommend you build your appointment reminders with Twilio's built-in Message Scheduling functionality. Head on over to the Message Scheduling documentation to learn more about scheduling messages.
Ready to implement appointment reminders in your application? Here's how it works:
Check out how Yelp uses SMS to confirm restaurant reservations for diners.
Here are the technologies we'll use to get this done:
In this tutorial, we'll point out key snippets of code that make this application work. Check out the project README on GitHub to see how to run the code yourself.
To implement appointment reminders, we will be working through a series of user stories that describe how to fully implement appointment reminders in a web application. We'll walk through the code required to satisfy each story, and explore what we needed to add on each step.
All this can be done with the help of Twilio in under half an hour.
As a user, I want to create an appointment with a name, guest phone numbers, and a time in the future.
In order to build an automated appointment reminder application, we probably should start with an appointment. This story requires that we create a bit of UI and a model object to create and save a new Appointment
in our system. At a high level, here's what we will need to add:
POST
requestAppointment
model object to store information about the userAlright, so we know what we need to create a new appointment. Now let's start by looking at the model, where we decide what information we want to store with the appointment.
The appointment model is fairly straightforward, but since humans will be interacting with it let's make sure we add some data validation.
Our application relies on ASP.NET Data Annotations. In our case, we only want to validate that some fields are required. To accomplish this we'll use [Required]
data annotation.
By default, ASP.NET MVC displays the property name when rendering a control. In our example those property names can be Name
or PhoneNumber
. For rendering Name
there shouldn't be any problem. But for PhoneNumber
we might want to display something nicer, like "Phone Number". For this kind of scenario we can use another data annotation: [Display(Name = "Phone Number")]
.
For validating the contents of the PhoneNumber
field, we're using [Phone]
data annotation, which confirms user-entered phone numbers conform loosely to E.164 formatting standards.
AppointmentReminders.Web/Models/Appointment.cs
1using System;2using System.ComponentModel.DataAnnotations;3using Microsoft.Ajax.Utilities;45namespace AppointmentReminders.Web.Models6{7public class Appointment8{9public static int ReminderTime = 30;10public int Id { get; set; }1112[Required]13public string Name { get; set; }1415[Required, Phone, Display(Name = "Phone number")]16public string PhoneNumber { get; set; }1718[Required]19public DateTime Time { get; set; }2021[Required]22public string Timezone { get; set; }2324[Display(Name = "Created at")]25public DateTime CreatedAt { get; set; }26}27}
Our appointment model is now defined. It's time to take a look at the form that allows an administrator to create new appointments.
When we create a new appointment, we need a guest name, a phone number and a time. By using HTML Helper classes we can bind the form to the model object. Those helpers will generate the necessary HTML markup that will create a new appointment on submit.
AppointmentReminders.Web/Views/Appointments/_Form.cshtml
1@using AppointmentReminders.Web.Extensions2@model AppointmentReminders.Web.Models.Appointment34<div class="form-group">5@Html.LabelFor(x => x.Name, new { @class = "control-label col-lg-2" })6<div class="col-lg-10">7@Html.TextBoxFor(x => x.Name, new { @class = "form-control", @required = "required" })8</div>9</div>10<div class="form-group">11@Html.LabelFor(x => x.PhoneNumber, new { @class = "control-label col-lg-2" })12<div class="col-lg-10">13@Html.TextBoxFor(x => x.PhoneNumber, new { @class = "form-control", @required = "required" })14</div>15</div>16<div class="form-group">17<label class="control-label col-lg-2">Time and Date</label>18<div class="col-lg-10">19<div class="row">20<div class="col-lg-6">21<div class='input-group date' id="datetimepicker">22@Html.TextBox("Time", Model.Time.ToCustomDateString(), new { @class = "form-control"})23<span class="input-group-addon">24<span class="glyphicon glyphicon-calendar"></span>25</span>26</div>27</div>28<div class="col-lg-6 pull-right">29@Html.DropDownListFor(x => x.Timezone, (IEnumerable<SelectListItem>)ViewBag.Timezones, new { @class = "form-control" })30</div>31</div>32</div>33</div>
Now that we have a model and an UI, we will see how we can interact with Appointments
.
As a user, I want to view a list of all future appointments, and be able to delete those appointments.
If you're an organization that handles a lot of appointments, you probably want to be able to view and manage them in a single interface. That's what we'll tackle in this user story. We'll create a UI to:
We know what interactions we want to implement, so let's look first at how to list all upcoming Appointments.
At the controller level, we'll get a list of all the appointments in the database and render them with a view. We also add a prompt if there aren't any appointments, so the admin user can create one.
AppointmentReminders.Web/Controllers/AppointmentsController.cs
1using System;2using System.Linq;3using System.Net;4using System.Web.Mvc;5using AppointmentReminders.Web.Models;6using AppointmentReminders.Web.Models.Repository;78namespace AppointmentReminders.Web.Controllers9{10public class AppointmentsController : Controller11{12private readonly IAppointmentRepository _repository;1314public AppointmentsController() : this(new AppointmentRepository()) { }1516public AppointmentsController(IAppointmentRepository repository)17{18_repository = repository;19}2021public SelectListItem[] Timezones22{23get24{25var systemTimeZones = TimeZoneInfo.GetSystemTimeZones();26return systemTimeZones.Select(systemTimeZone => new SelectListItem27{28Text = systemTimeZone.DisplayName,29Value = systemTimeZone.Id30}).ToArray();31}32}3334// GET: Appointments35public ActionResult Index()36{37var appointments = _repository.FindAll();38return View(appointments);39}4041// GET: Appointments/Details/542public ActionResult Details(int? id)43{44if (id == null)45{46return new HttpStatusCodeResult(HttpStatusCode.BadRequest);47}4849var appointment = _repository.FindById(id.Value);50if (appointment == null)51{52return HttpNotFound();53}5455return View(appointment);56}5758// GET: Appointments/Create59public ActionResult Create()60{61ViewBag.Timezones = Timezones;62// Use an empty appointment to setup the default63// values.64var appointment = new Appointment65{66Timezone = "Pacific Standard Time",67Time = DateTime.Now68};6970return View(appointment);71}7273[HttpPost]74public ActionResult Create([Bind(Include="ID,Name,PhoneNumber,Time,Timezone")]Appointment appointment)75{76appointment.CreatedAt = DateTime.Now;7778if (ModelState.IsValid)79{80_repository.Create(appointment);8182return RedirectToAction("Details", new {id = appointment.Id});83}8485return View("Create", appointment);86}8788// GET: Appointments/Edit/589[HttpGet]90public ActionResult Edit(int? id)91{92if (id == null)93{94return new HttpStatusCodeResult(HttpStatusCode.BadRequest);95}9697var appointment = _repository.FindById(id.Value);98if (appointment == null)99{100return HttpNotFound();101}102103ViewBag.Timezones = Timezones;104return View(appointment);105}106107// POST: /Appointments/Edit/5108[HttpPost]109public ActionResult Edit([Bind(Include = "ID,Name,PhoneNumber,Time,Timezone")] Appointment appointment)110{111if (ModelState.IsValid)112{113_repository.Update(appointment);114return RedirectToAction("Details", new { id = appointment.Id });115}116return View(appointment);117}118119// DELETE: Appointments/Delete/5120[HttpDelete]121public ActionResult Delete(int id)122{123_repository.Delete(id);124return RedirectToAction("Index");125}126}127}
That's how we return the list of appointments, now we need to render them. Let's look at the Appointments template for that.
The index view lists all appointments which are sorted by Id. The only thing we need to add to fulfil our user story is a delete button. We'll add the edit button just for kicks.
You may notice that instead of hard-coding the urls for Edit and Delete we are using an ASP.NET MVC HTML Helpers. If you view the rendered markup you will see these paths.
/Appointments/Edit/
id
for edit/Appointments/Delete/
id
for deleteAppointmentsController.cs
contains methods which handle both the edit and delete operations.
1@using AppointmentReminders.Web.Extensions2@model IEnumerable<AppointmentReminders.Web.Models.Appointment>34<div class="page-header">5<h1>Appointments</h1>6</div>78<table class="table table-striped">9<tr>10<th>11@Html.DisplayNameFor(model => model.Id)12</th>13<th>14@Html.DisplayNameFor(model => model.Name)15</th>16<th>17@Html.DisplayNameFor(model => model.PhoneNumber)18</th>19<th>20@Html.DisplayNameFor(model => model.Time)21</th>22<th>23@Html.DisplayNameFor(model => model.CreatedAt)24</th>25<th>26Actions27</th>28</tr>2930@foreach (var item in Model) {31<tr>32<td>33@Html.ActionLink(item.Id.ToString(), "Details", new {Controller = "Appointments", id = item.Id})34</td>35<td>36@Html.DisplayFor(modelItem => item.Name)37</td>38<td>39@Html.DisplayFor(modelItem => item.PhoneNumber)40</td>41<td>42@Html.DisplayFor(modelItem => item.Time)43</td>44<td>45@Html.DisplayFor(modelItem => item.CreatedAt)46</td>47<td>48@Html.ActionLink("Edit", "Edit", new { Controller = "Appointments", id = item.Id }, new { @class = "btn btn-default btn-xs" })4950@Html.DeleteLink("Delete", "Appointments",51new { id = item.Id },52new { @class = "btn btn-danger btn-xs", onclick = "return confirm('Are you sure?');" })53</td>54</tr>55}5657</table>5859@Html.ActionLink("New", "Create", new { Controller = "Appointments" }, new { @class = "btn btn-primary" })
Now that we have the ability to create, view, edit, and delete appointments, we can dig into the fun part: scheduling a recurring job that will send out reminders via SMS when an appointment is coming up!
As an appointment system, I want to notify a user via SMS an arbitrary interval before a future appointment.
There are a lot of ways to build this part of our application, but no matter how you implement it there should be two moving parts:
Let's take a look at how we decided to implement the latter with Hangfire.
If you've never used a job scheduler before, you may want to check out this post by Scott Hanselman that shows a few ways to run background tasks in ASP.NET MVC. We decided to use Hangfire because of its simplicity. If you have a better way to schedule jobs in ASP.NET MVC please let us know.
Hangfire needs a backend of some kind to queue the upcoming jobs. In this implementation, we're using SQL Server Database, but it's possible to use a different data store. You can check their documentation for further details.
1<?xml version="1.0" encoding="utf-8"?>2<packages>3<package id="Antlr" version="3.5.0.2" targetFramework="net472" />4<package id="EntityFramework" version="6.4.4" targetFramework="net472" />5<package id="Hangfire" version="1.7.19" targetFramework="net472" />6<package id="Hangfire.Core" version="1.7.18" targetFramework="net472" />7<package id="Hangfire.SqlServer" version="1.7.18" targetFramework="net472" />8<package id="JWT" version="7.3.1" targetFramework="net472" />9<package id="Microsoft.AspNet.Mvc" version="5.2.7" targetFramework="net472" />10<package id="Microsoft.AspNet.Razor" version="3.2.7" targetFramework="net472" />11<package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net472" />12<package id="Microsoft.AspNet.WebPages" version="3.2.7" targetFramework="net472" />13<package id="Microsoft.IdentityModel.JsonWebTokens" version="6.8.0" targetFramework="net472" />14<package id="Microsoft.IdentityModel.Logging" version="6.8.0" targetFramework="net472" />15<package id="Microsoft.IdentityModel.Tokens" version="6.8.0" targetFramework="net472" />16<package id="Microsoft.Owin" version="4.1.1" targetFramework="net472" />17<package id="Microsoft.Owin.Host.SystemWeb" version="4.1.1" targetFramework="net472" />18<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net472" />19<package id="Newtonsoft.Json" version="12.0.3" targetFramework="net472" />20<package id="Owin" version="1.0" targetFramework="net472" />21<package id="Portable.BouncyCastle" version="1.8.9" targetFramework="net472" />22<package id="Portable.JWT" version="1.0.5" targetFramework="net472" />23<package id="RestSharp" version="106.11.7" targetFramework="net472" />24<package id="System.IdentityModel.Tokens.Jwt" version="6.8.0" targetFramework="net472" />25<package id="Twilio" version="5.53.0" targetFramework="net472" />26<package id="WebGrease" version="1.6.0" targetFramework="net472" />27</packages>
Now that we have included Hangfire dependencies into the project, let's take a look at how to configure it to use it in our appointment reminders application.
We created a class named Hangfire
to configure our job scheduler. This class defines two static methods:
ConfigureHangfire
to set initialization parameters for the job scheduler.InitialzeJobs
to specify which recurring jobs should be run, and how often they should run.AppointmentReminders.Web/App_Start/Hangfire.cs
1using Hangfire;2using Owin;34namespace AppointmentReminders.Web5{6public class Hangfire7{8public static void ConfigureHangfire(IAppBuilder app)9{10GlobalConfiguration.Configuration11.UseSqlServerStorage("DefaultConnection");1213app.UseHangfireDashboard("/jobs");14app.UseHangfireServer();15}1617public static void InitializeJobs()18{19RecurringJob.AddOrUpdate<Workers.SendNotificationsJob>(job => job.Execute(), Cron.Minutely);20}21}22}
That's it for the configuration. Let's take a quick look next at how we start up the job scheduler.
This ASP.NET MVC project is an OWIN-based application, which allows us to create a startup class to run any custom initialization logic required in our application. This is the preferred location to start Hangfire - check out their configuration docs for more information.
AppointmentReminders.Web/Startup.c
1using Microsoft.Owin;2using Owin;34[assembly: OwinStartup(typeof(AppointmentReminders.Web.Startup))]5namespace AppointmentReminders.Web6{7public class Startup8{9public void Configuration(IAppBuilder app)10{11Hangfire.ConfigureHangfire(app);12Hangfire.InitializeJobs();13}14}15}
Now that we've started the job scheduler, let's take a look at the logic that gets executed when our job runs.
In this class, we define a method called Execute
which is called every minute by Hangfire. Every time the job runs, we need to:
The AppointmentsFinder
class queries our SQL Server database to find all the appointments whose date and time are coming up soon. For each of those appointments, we'll use the Twilio REST API to send out a formatted message.
AppointmentReminders.Web/Workers/SendNotificationsJob.cs
1using System;2using System.Collections.Generic;3using AppointmentReminders.Web.Domain;4using AppointmentReminders.Web.Models;5using AppointmentReminders.Web.Models.Repository;6using WebGrease.Css.Extensions;78namespace AppointmentReminders.Web.Workers9{10public class SendNotificationsJob11{12private const string MessageTemplate =13"Hi {0}. Just a reminder that you have an appointment coming up at {1}.";1415public void Execute()16{17var twilioRestClient = new Domain.Twilio.RestClient();1819AvailableAppointments().ForEach(appointment =>20twilioRestClient.SendSmsMessage(21appointment.PhoneNumber,22string.Format(MessageTemplate, appointment.Name, appointment.Time.ToString("t"))));23}2425private static IEnumerable<Appointment> AvailableAppointments()26{27return new AppointmentsFinder(new AppointmentRepository(), new TimeConverter())28.FindAvailableAppointments(DateTime.Now);29}30}31}
Now that we are retrieving a list of upcoming Appointments, let's take a look next at how we use Twilio to send SMS notifications.
This class is responsible for reading our Twilio account credentials from Web.config
, and using the Twilio REST API to actually send out a notification to our users. We also need a Twilio number to use as the sender for the text message. Actually sending the message is a single line of code!
AppointmentReminders.Web/Domain/Twilio/RestClient.cs
1using System.Web.Configuration;2using Twilio.Clients;3using Twilio.Rest.Api.V2010.Account;4using Twilio.Types;56namespace AppointmentReminders.Web.Domain.Twilio7{8public class RestClient9{10private readonly ITwilioRestClient _client;11private readonly string _accountSid = WebConfigurationManager.AppSettings["AccountSid"];12private readonly string _authToken = WebConfigurationManager.AppSettings["AuthToken"];13private readonly string _twilioNumber = WebConfigurationManager.AppSettings["TwilioNumber"];1415public RestClient()16{17_client = new TwilioRestClient(_accountSid, _authToken);18}1920public RestClient(ITwilioRestClient client)21{22_client = client;23}2425public void SendSmsMessage(string phoneNumber, string message)26{27var to = new PhoneNumber(phoneNumber);28MessageResource.Create(29to,30from: new PhoneNumber(_twilioNumber),31body: message,32client: _client);33}34}35}
Fun tutorial, right? Where can we take it from here?
And with a little code and a dash of configuration, we're ready to get automated appointment reminders firing in our application. Good work!
If you are a C# developer working with Twilio, you might want to check out other tutorials:
Put a button on your web page that connects visitors to live support or sales people via telephone.
Improve the security of your Flask app's login functionality by adding two-factor authentication via text message.