Creating an appointment reminder app with .NET SDK

Creating the application

To function, your code needs to have the ability to validate input data and send texts. It also needs to display different pages depending on whether a user is inputting an appointment or has already submitted the appointment details. The controller contains the business logic of your application.

In the Controllers folder, create a file called AppointmentController.cs. Then, copy the code displayed on the right panel of this page and paste the contents into the file. We'll step through each section of code below.

Importing the SDK

This code imports the SDK functionality your app needs to update a group and send a reply. It also specifies the namespace the Controller is in:

Copy
Copied
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using sinch_appointment_reminder.Models;
using Sinch;
using System.Text.Json;

namespace sinch_appointment_reminder.Controllers;

public class AppointmentController : Controller
{
}

The AppointmentController class

Now let's review the class members and constructor. Take a look at the following code, which defines the AppointmentController class:
Copy
Copied
public AppointmentController(ISinchClient sinchClient, ILogger<AppointmentController> logger, IConfiguration configuration)
{
    _logger = logger;
    _sinchClient = sinchClient;
    Configuration = configuration;
}
The constructor's job is to set up your controller by initializing the AppointmentController members. This includes the SDK client object, which will be used to send SMS messages. There is also a configuration object for reading config values and logger object for debugging.

The RemindPatient method

Now we'll review the RemindPatient method:
Copy
Copied
public async void RemindPatient(string to, string message, DateTime reminder_datetime)
{
    var response = await _sinchClient.Sms.Batches.Send(new Sinch.SMS.Batches.Send.SendTextBatchRequest
    {
        Body = message,
        From = Configuration["Sinch:from_number"],
        To = new List<string> { to },
        SendAt = reminder_datetime,
        DeliveryReport = Sinch.SMS.DeliveryReport.None
    });

    Console.WriteLine(JsonSerializer.Serialize(response, new JsonSerializerOptions()
    {
        WriteIndented = true
    }));
}
This method is the keystone of your application because its job is to send the SMS. It uses the SinchClient instance you just created to call the SDK send method. What makes this method powerful is the SendAt parameter. Because the Sinch SMS REST API has message scheduling built in, it's a one-stop shop for any application that requires sending SMS messages at particular times. This reduces the amount of dependencies you need. Even better, it means you don't need your app to be running all the time!
In addition to SendAt, the send method has a number of other parameters, including message expiry and delivery reports. These are available on the REST API reference.

General controller methods

We're now going to review the methods for our controller:

Copy
Copied
public async Task<IActionResult> Index()
{
    return RedirectToAction(nameof(Submit));
}

public async Task<IActionResult> Submit()
{
    return View();
}

These methods implement the application's functionality and shunt users to the correct page at each point on their journey.

  • The first method redirects from the root URL. This means that users can simply type http://localhost:<port>/appointment and they will be taken to the appointment scheduling form at http://localhost:<port>/appointment/submit.
  • The second method displays the appointment scheduling form.

The Submit post method

Now let's review the Submit post method:
Copy
Copied
[HttpPost]
public IActionResult Submit(string patient, string doctor, string phone, DateTime appointment_date, DateTime appointment_time)
    {
        DateTime appointment_datetime = new DateTime(appointment_date.Year, appointment_date.Month, appointment_date.Day, appointment_time.Hour, appointment_time.Minute, appointment_time.Second);
        TempData["appointment_datetime"] = appointment_datetime;
        TempData["patient"] = patient;
        TempData["doctor"] = doctor;
        TempData["phone"] = phone;
        var now = DateTime.Now;
        DateTime reminder_datetime = appointment_datetime.AddHours(-2).ToUniversalTime();

        if (now.AddHours(2.08333) > appointment_datetime)
        {
            return RedirectToAction(nameof(Index));
        }

        string country_code = "+1";
        if (Configuration["Sinch:sms_region"] == "eu")
        {
            country_code = Configuration["Sinch:country_code_eu"];
        }

        string to = country_code + phone;

        string message = "Hi " + patient + ", you have a Sinch Hospital appointment with Dr " + doctor + " scheduled for " + appointment_datetime;
        RemindPatient(to, message, reminder_datetime);
        return RedirectToAction(nameof(Success));

    }
This contains the meat of your application's business logic. It is a post method that receives form data from the front end and sends an SMS message by calling remindPatient. Once a confirmation message is sent, the user is redirected to the success page.

This method also contains validation to make sure any appointment is booked at least a couple of hours into the future. This also stops users from accidently booking an appointment in the past.

The Sinch SDK requires phone numbers to have a country code, so the code checks the SMS region and adds a US/EU country code to the phone number.

Rendering the success page

The final route path renders the success page:

Copy
Copied
public IActionResult Success()
{

    return View();
}

Congratulations! That's the core of your application completed.



We'd love to hear from you!
Rate this content:
Still have a question?
 
Ask the community.