Skip to contentSkip to navigationSkip to topbar
On this page

Send Appointment Reminders with C# and ASP.NET MVC


(information)

Info

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:

  1. An administrator creates an appointment for a future date and time, and stores a customer's phone number in the database for that appointment
  2. A background process checks the database on a regular interval, looking for appointments that require a reminder to be sent out
  3. At a configured time in advance of the appointment, an SMS reminder is sent out to the customer to remind them of their appointment

Check out how Yelp uses SMS to confirm restaurant reservations for diners.(link takes you to an external page)


Building Blocks

building-blocks page anchor

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(link takes you to an external page) to see how to run the code yourself.


How To Read This Tutorial

how-to-read-this-tutorial page anchor

To implement appointment reminders, we will be working through a series of user stories(link takes you to an external page) 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:

  • A form to enter details about the appointment
  • A route and controller function on the server to render the form
  • A route and controller function on the server to handle the form POST request
  • A persistent Appointment model object to store information about the user

Alright, 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(link takes you to an external page). 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(link takes you to an external page).

The Appointment Model

the-appointment-model page anchor

AppointmentReminders.Web/Models/Appointment.cs

1
using System;
2
using System.ComponentModel.DataAnnotations;
3
using Microsoft.Ajax.Utilities;
4
5
namespace AppointmentReminders.Web.Models
6
{
7
public class Appointment
8
{
9
public static int ReminderTime = 30;
10
public int Id { get; set; }
11
12
[Required]
13
public string Name { get; set; }
14
15
[Required, Phone, Display(Name = "Phone number")]
16
public string PhoneNumber { get; set; }
17
18
[Required]
19
public DateTime Time { get; set; }
20
21
[Required]
22
public string Timezone { get; set; }
23
24
[Display(Name = "Created at")]
25
public 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(link takes you to an external page) 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.Extensions
2
@model AppointmentReminders.Web.Models.Appointment
3
4
<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.


Interacting with Appointments

interacting-with-appointments page anchor

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:

  • Show all appointments
  • Delete individual appointments

We know what interactions we want to implement, so let's look first at how to list all upcoming Appointments.


Getting a List of Appointments

getting-a-list-of-appointments page anchor

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

1
using System;
2
using System.Linq;
3
using System.Net;
4
using System.Web.Mvc;
5
using AppointmentReminders.Web.Models;
6
using AppointmentReminders.Web.Models.Repository;
7
8
namespace AppointmentReminders.Web.Controllers
9
{
10
public class AppointmentsController : Controller
11
{
12
private readonly IAppointmentRepository _repository;
13
14
public AppointmentsController() : this(new AppointmentRepository()) { }
15
16
public AppointmentsController(IAppointmentRepository repository)
17
{
18
_repository = repository;
19
}
20
21
public SelectListItem[] Timezones
22
{
23
get
24
{
25
var systemTimeZones = TimeZoneInfo.GetSystemTimeZones();
26
return systemTimeZones.Select(systemTimeZone => new SelectListItem
27
{
28
Text = systemTimeZone.DisplayName,
29
Value = systemTimeZone.Id
30
}).ToArray();
31
}
32
}
33
34
// GET: Appointments
35
public ActionResult Index()
36
{
37
var appointments = _repository.FindAll();
38
return View(appointments);
39
}
40
41
// GET: Appointments/Details/5
42
public ActionResult Details(int? id)
43
{
44
if (id == null)
45
{
46
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
47
}
48
49
var appointment = _repository.FindById(id.Value);
50
if (appointment == null)
51
{
52
return HttpNotFound();
53
}
54
55
return View(appointment);
56
}
57
58
// GET: Appointments/Create
59
public ActionResult Create()
60
{
61
ViewBag.Timezones = Timezones;
62
// Use an empty appointment to setup the default
63
// values.
64
var appointment = new Appointment
65
{
66
Timezone = "Pacific Standard Time",
67
Time = DateTime.Now
68
};
69
70
return View(appointment);
71
}
72
73
[HttpPost]
74
public ActionResult Create([Bind(Include="ID,Name,PhoneNumber,Time,Timezone")]Appointment appointment)
75
{
76
appointment.CreatedAt = DateTime.Now;
77
78
if (ModelState.IsValid)
79
{
80
_repository.Create(appointment);
81
82
return RedirectToAction("Details", new {id = appointment.Id});
83
}
84
85
return View("Create", appointment);
86
}
87
88
// GET: Appointments/Edit/5
89
[HttpGet]
90
public ActionResult Edit(int? id)
91
{
92
if (id == null)
93
{
94
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
95
}
96
97
var appointment = _repository.FindById(id.Value);
98
if (appointment == null)
99
{
100
return HttpNotFound();
101
}
102
103
ViewBag.Timezones = Timezones;
104
return View(appointment);
105
}
106
107
// POST: /Appointments/Edit/5
108
[HttpPost]
109
public ActionResult Edit([Bind(Include = "ID,Name,PhoneNumber,Time,Timezone")] Appointment appointment)
110
{
111
if (ModelState.IsValid)
112
{
113
_repository.Update(appointment);
114
return RedirectToAction("Details", new { id = appointment.Id });
115
}
116
return View(appointment);
117
}
118
119
// DELETE: Appointments/Delete/5
120
[HttpDelete]
121
public ActionResult Delete(int id)
122
{
123
_repository.Delete(id);
124
return 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.


Displaying All Appointments

displaying-all-appointments page anchor

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.

HTML Helpers

html-helpers page anchor

You may notice that instead of hard-coding the urls for Edit and Delete we are using an ASP.NET MVC HTML Helpers(link takes you to an external page). If you view the rendered markup you will see these paths.

  • /Appointments/Edit/id for edit
  • /Appointments/Delete/id for delete

AppointmentsController.cs contains methods which handle both the edit and delete operations.

Display all Appointments

display-all-appointments page anchor
1
@using AppointmentReminders.Web.Extensions
2
@model IEnumerable<AppointmentReminders.Web.Models.Appointment>
3
4
<div class="page-header">
5
<h1>Appointments</h1>
6
</div>
7
8
<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>
26
Actions
27
</th>
28
</tr>
29
30
@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" })
49
50
@Html.DeleteLink("Delete", "Appointments",
51
new { id = item.Id },
52
new { @class = "btn btn-danger btn-xs", onclick = "return confirm('Are you sure?');" })
53
</td>
54
</tr>
55
}
56
57
</table>
58
59
@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:

  • A script that checks the database for any appointment that is upcoming, and then sends a SMS.
  • A worker that runs that script continuously.

Let's take a look at how we decided to implement the latter with Hangfire(link takes you to an external page).


If you've never used a job scheduler before, you may want to check out this post by Scott Hanselman(link takes you to an external page) 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(link takes you to an external page).

Hangfire needs a backend of some kind to queue the upcoming jobs. In this implementation, we're using SQL Server Database(link takes you to an external page), but it's possible to use a different data store. You can check their documentation(link takes you to an external page) 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.


Hangfire Configuration Class

hangfire-configuration-class page anchor

We created a class named Hangfire to configure our job scheduler. This class defines two static methods:

  1. ConfigureHangfire to set initialization parameters for the job scheduler.
  2. InitialzeJobs to specify which recurring jobs should be run, and how often they should run.

AppointmentReminders.Web/App_Start/Hangfire.cs

1
using Hangfire;
2
using Owin;
3
4
namespace AppointmentReminders.Web
5
{
6
public class Hangfire
7
{
8
public static void ConfigureHangfire(IAppBuilder app)
9
{
10
GlobalConfiguration.Configuration
11
.UseSqlServerStorage("DefaultConnection");
12
13
app.UseHangfireDashboard("/jobs");
14
app.UseHangfireServer();
15
}
16
17
public static void InitializeJobs()
18
{
19
RecurringJob.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.


Starting the Job Scheduler

starting-the-job-scheduler page anchor

This ASP.NET MVC project is an OWIN-based application(link takes you to an external page), 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(link takes you to an external page).

AppointmentReminders.Web/Startup.c

1
using Microsoft.Owin;
2
using Owin;
3
4
[assembly: OwinStartup(typeof(AppointmentReminders.Web.Startup))]
5
namespace AppointmentReminders.Web
6
{
7
public class Startup
8
{
9
public void Configuration(IAppBuilder app)
10
{
11
Hangfire.ConfigureHangfire(app);
12
Hangfire.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.


Notification Background Job

notification-background-job page anchor

In this class, we define a method called Execute which is called every minute by Hangfire. Every time the job runs, we need to:

  1. Get a list of upcoming appointments that require notifications to be sent out
  2. Use Twilio to send appointment reminders via SMS

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.

Notifications Background Job

notifications-background-job page anchor

AppointmentReminders.Web/Workers/SendNotificationsJob.cs

1
using System;
2
using System.Collections.Generic;
3
using AppointmentReminders.Web.Domain;
4
using AppointmentReminders.Web.Models;
5
using AppointmentReminders.Web.Models.Repository;
6
using WebGrease.Css.Extensions;
7
8
namespace AppointmentReminders.Web.Workers
9
{
10
public class SendNotificationsJob
11
{
12
private const string MessageTemplate =
13
"Hi {0}. Just a reminder that you have an appointment coming up at {1}.";
14
15
public void Execute()
16
{
17
var twilioRestClient = new Domain.Twilio.RestClient();
18
19
AvailableAppointments().ForEach(appointment =>
20
twilioRestClient.SendSmsMessage(
21
appointment.PhoneNumber,
22
string.Format(MessageTemplate, appointment.Name, appointment.Time.ToString("t"))));
23
}
24
25
private static IEnumerable<Appointment> AvailableAppointments()
26
{
27
return 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

1
using System.Web.Configuration;
2
using Twilio.Clients;
3
using Twilio.Rest.Api.V2010.Account;
4
using Twilio.Types;
5
6
namespace AppointmentReminders.Web.Domain.Twilio
7
{
8
public class RestClient
9
{
10
private readonly ITwilioRestClient _client;
11
private readonly string _accountSid = WebConfigurationManager.AppSettings["AccountSid"];
12
private readonly string _authToken = WebConfigurationManager.AppSettings["AuthToken"];
13
private readonly string _twilioNumber = WebConfigurationManager.AppSettings["TwilioNumber"];
14
15
public RestClient()
16
{
17
_client = new TwilioRestClient(_accountSid, _authToken);
18
}
19
20
public RestClient(ITwilioRestClient client)
21
{
22
_client = client;
23
}
24
25
public void SendSmsMessage(string phoneNumber, string message)
26
{
27
var to = new PhoneNumber(phoneNumber);
28
MessageResource.Create(
29
to,
30
from: new PhoneNumber(_twilioNumber),
31
body: message,
32
client: _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:

Click to Call

Put a button on your web page that connects visitors to live support or sales people via telephone.

Two-Factor Authentication

Improve the security of your Flask app's login functionality by adding two-factor authentication via text message.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.