Appointment Alerter In C# Using Speech Synthesis

Introduction

In C#, we have the ability to use speech synthesis. For saving the appointment, we will create a table in SQL Server database. And for speech synthesis, we will use this.

  1. using System.Speech.Synthesis; namespace.  

Creating the Application

So let’s start. First, we will create a Windows Forms application in Visual Studio.

  • Click on File->New Project and select Windows Forms Project from the Window.
  • Let’s give it a name. I named it “AppointmentAlerter”.
  • Now, let’s add three labels. The Text of the first label will be “Choose Date of Appointment”. The text of the second label will be “Choose Time of Appointment” and the text of the third label will be “Enter Appointment Details”.
  • Now, let’s add two DateTime pickers to the form from the toolbox. The first one will be used to set the date of appointment and the second one will be for the time of appointment.
  • Add a textbox and set its Multiline property to True. Add a button and set its text “Save Appointment”. The form would look like below.
 
Appointment Alerter In C# Using Speech Synthesis

Let’s rename our first DateTime Picker for showing the date as “dtp_AppDt” from the properties window.

Appointment Alerter In C# Using Speech Synthesis

Similarly, let’s rename our second DateTime Picker for showing time to “dtp_AppTm”. Similarly, rename our textbox as “txtAppDetails”.

Now, let’s go to the code behind and add the following code in the Forms Constructor,

  1. public Form1()  
  2. {  
  3.     InitializeComponent();  
  4.     dtp_AppTm.Format = DateTimePickerFormat.Time;  
  5.     dtp_AppTm.ShowUpDown = true;  
  6. }  

The first line of the highlighted code sets the second DateTime Picker to show time and the second line tells to show up-down to true so that you can choose time by pressing up or down.

Now, let’s create a table in our database.

My database name is “[TestDatabase]”. The following is the code for creating the table.

  1. CREATE TABLE [dbo].[Tbl_Appointment](  
  2.     [AppID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [AppDate] [dateNOT NULL,  
  4.     [AppTime] [timeNOT NULL,  
  5.     [AppDetails] [varchar](550)NOT NULL)  

This will create a table named “Tbl_Appointment” in our database. The column types are obvious. The first column is the identity column. The second column is for the date of appointment. The third column is for the time of appointment. The last column is for saving the details of your appointment. Please mark that this table has been created in SQL Server 2016. “Time” data type may not be available in earlier versions of SQL Server. Please check your SQL Server version.

Now let’s code the ADO.NET part in our code behind. Let’s add the following XML markup in our “app.config” file in our project,

  1. <connectionStrings>  
  2.     <add connectionString="Data Source=DESKTOP-NPH7QFU;Initial Catalog=TestDatabase;User ID=sa;Password=rwd@123" name="AppConString" />  
  3.   </connectionStrings>  

Remember, your connection string can be different , depending on your database, sql server login and password.

Now let’s go to our form in design view and double click on the “Save Appointment” Button. I have named it “btnSaveApp”. In the code behind let’s add the following namespaces,

  1. using System.Data.SqlClient;  
  2. using System.Configuration;  

The first one is for ado.net and the second for accessing our connection string.

Let’s add the reference to the assembly System.Configuration.dll. For this right click on your project and click on “Add” then “Reference” and from the pop-up box select “System.Configuration” and click “OK”.

Appointment Alerter In C# Using Speech Synthesis

Let’s write the following code inside the button click code,

  1. private void btnSaveApp_Click(object sender, EventArgs e)  
  2. {  
  3.     string constring = ConfigurationManager.ConnectionStrings["AppConString"].ConnectionString;  
  4.     using (SqlConnection sqlcon = new SqlConnection(constring))  
  5.     {  
  6.         SqlCommand cmd = new SqlCommand();  
  7.         cmd.Connection = sqlcon;  
  8.         cmd.CommandText = "INSERT INTO Tbl_Appointment(AppDate, AppTime, AppDetails)   VALUES(@param1,@param2,@param3)";  
  9.         cmd.Parameters.AddWithValue("@param1", dtp_AppDt.Value.ToShortDateString());  
  10.         cmd.Parameters.AddWithValue("@param2", dtp_AppTm.Value.ToShortTimeString());  
  11.         cmd.Parameters.AddWithValue("@param3", txtAppDetails.Text);  
  12.         sqlcon.Open();  
  13.         int result = cmd.ExecuteNonQuery();  
  14.         sqlcon.Close();  
  15.         if (result >0)  
  16.         {
  17.             MessageBox.Show("Appointment Saved successfully!");  
  18.         }  
  19.         else  
  20.         {
  21.             MessageBox.Show("Error in saving Appointment!");  
  22.         }  
  23.     }  
  24. }  

The first line is for accessing the connection string from our app.config file. The second line is a using statement with SqlConnection. This internally converts to a try catch and finally block and the connection is closed automatically at the end of it. The rest of the code is the SQL command code for inserting data into our database table which we created earlier. I assume you are familiar with ado.net and know how to save data into the table.

Now let’s add the speech synthesizer. For it let’s write the following using statement,

  1. using System.Speech.Synthesis  

You will see a red line under speech by IntelliSense, meaning it is not supported. You are probably thinking we have to add assembly for it. So let’s right-click on the project and click Add->Reference. In the reference window, click on “Assemblies”->”Framework” and then scroll down to “System.Speech”. Select (Check it) it and click on ok.

Appointment Alerter In C# Using Speech Synthesis

The assembly will be added to your form. Now you will see the red underline disappear from speech namespace.

Now let’s add a timer to our project. For this, with form in design view, let’s go to Toolbox->Components and double click on “timer” or you can also drag and drop it into the form.

Now double click on your form. This will create a stub code for Form load in code behind. Let’s add the following code,

  1. private void Form1_Load(object sender, EventArgs e)  
  2.         {              
  3.             timer1.Interval = 60 * 60 * 100;  
  4.             timer1.Start();              
  5.         }  

This sets the timer interval to 1 hour . We will read the database every hour to fetch the appointments. In the next line we start the timer.

Now let’s go the design view and double click on “timer.” This will create a stub code for the timer_tick event in the code behind. Now, let’s write the following code for reading today’s appointment from the database and read it out.

  1. private void timer1_Tick(object sender, EventArgs e)  
  2. {  
  3.     string constring = ConfigurationManager.ConnectionStrings["AppConString"].ConnectionString;  
  4.     using (SqlConnection sqlcon = new SqlConnection(constring))  
  5.     {  
  6.         SqlCommand sqlcom = new SqlCommand("Select AppDate, AppTime, AppDetails from Tbl_Appointment where AppDate='"+DateTime.Today.ToString("dd MMM yyyy")+"'", sqlcon);  
  7.         SqlDataAdapter sqlda = new SqlDataAdapter(sqlcom);  
  8.         DataTable dt = new DataTable();  
  9.         sqlcon.Open();  
  10.         sqlda.Fill(dt);  
  11.         sqlcon.Close();  
  12.                   
  13.         if(dt.Rows.Count >0)  
  14.         {  
  15.             using (SpeechSynthesizer synth = new SpeechSynthesizer())  
  16.             {
  17.                 for (int i = 0; i < dt.Rows.Count; i++)  
  18.                 {  
  19.                     synth.Speak("Today at " + DateTime.Today.ToLongDateString() + "  you have the following appointment at time " + dt.Rows[i]["AppTime"].ToString() + " you have  " + dt.Rows[i]["AppDetails"].ToString());  
  20.                 }  
  21.                 return;  
  22.             }  
  23.         }  
  24.         else  
  25.         {
  26.             using (SpeechSynthesizer synth = new SpeechSynthesizer())  
  27.             {  
  28.                 synth.Speak("Today you have no appointments");  
  29.                 return;  
  30.             }         
  31.         }  
  32.                   
  33.     }  
  34. }  

For those who are familiar with ADO.NET, most of the code is obvious. We read today’s appointments from the database and save it into a table. The highlighted code is where we read from the use of speech synthesizer to read out today’s appointments. It first checks if there are any appointments for today and then with “synth.Speak “, it reads out the appointment. Here you can code whatever you want to be read out.

Now let’s save the form to the system tray. For that let’s drag and drop a “NotifyIcon” from the toolbox to your windows form. Now let’s set the following property to Notifyicon from property box.

Appointment Alerter In C# Using Speech Synthesis

Now, let’s go to the form events in the properties window and double click on “Resize” event. In the code behind let’s write the following code,

  1. private void Form1_Resize(object sender, EventArgs e)  
  2. {  
  3.     //if the form is minimized    
  4.     //hide it from the task bar    
  5.     //and show the system tray icon (represented by the NotifyIcon control)    
  6.     if (this.WindowState == FormWindowState.Minimized)  
  7.     {
  8.         Hide();  
  9.         notifyIcon1.Visible = true;  
  10.     }    
  11. }  

If the Window state is minimized the window will be hidden and the notifyicon will be visible in system tray.

Now let’s go to notify icon and from the property window double click on “MouseDoubleClick” event. Then write the following code in the code behind,

  1. private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)  
  2. {  
  3.     Show();  
  4.     this.WindowState = FormWindowState.Normal;  
  5.     notifyIcon1.Visible = false;   
  6. }   

On Mouse double-click, the window will show up while the notify icon will be invisible.

Now, let’s test the application.

Conclusion

The Appointment Alerter is a quick application for making an appointment and reading it out using speech synthesis. Today we learned a lot of technologies like speech synthesis, minimizing to system tray and saving and reading from the database. This is a useful application for creating and being notified about your appointments.

That’s all folks! Thank you.


Similar Articles