Click here to Skip to main content
Click here to Skip to main content

How to Send SMS Messages from C# using an SQL Database

By , 16 Aug 2007
 

Screenshot - sms-gateway-form.gif

Introduction

In this article, I give you an example of how you can send SMS messages to wireless devices from C# .NET. I assume, that you are familiar with Visual Studio 2003 or 2005 and the basics of databases and the SQL language. The solution described here is an in-house solution. To use it, you need a GSM Modem for sending SMS messages.

Background

The system architecture used for SMS messaging consists of a GSM Modem, that is attached to the PC with a phone-to-PC datacable, an SQL-SMS Gateway software installed onto your PC, an SQL database server, such as SQL Express or Microsoft SQL and your SMS application (Figure 1). As you can see in the figure, your SMS application will create an SQL record in the database. The SMS gateway will poll this record using an SQL SELECT statement and will send it using a GSM modem.

Screenshot - sms-gateway-architecture.gif

Figure 1: In house SMS messaging / system architecture.

Preparing your Database Server

To get this architecture running, first you should prepare your database. This means that you should create two database tables. One will be used for sending SMS messages (ozekimessageout) and the other will be used for receiving SMS messages (ozekimessagein). The database table you create should contain a field for sender number, recipient number and message text. For sending messages, you also need a status field, that will indicate whether the message has been sent.

The recommended database table layout can be seen on Figure 2. Please note that you can add extra columns to this layout freely. After creating the database table layout, you should also create a username and a password that can be used to log into database.

create database ozeki
GO

use database ozeki
GO

CREATE TABLE ozekimessagein (
id int IDENTITY (1,1),
sender varchar(30),
receiver varchar(30),
msg varchar(160),
senttime varchar(100),
receivedtime varchar(100),
operator varchar(30),
msgtype varchar(30),
reference varchar(30),
);

CREATE TABLE ozekimessageout (
id int IDENTITY (1,1),
sender varchar(30),
receiver varchar(30),
msg varchar(160),
senttime varchar(100),
receivedtime varchar(100),
operator varchar(100),
msgtype varchar(30),
reference varchar(30),
status varchar(30),
errormsg varchar(250)
);
GO

sp_addLogin 'ozekiuser', 'ozekipass'
GO

sp_addsrvrolemember 'ozekiuser', 'sysadmin'
GO
Figure 2: Database table layout.

Configuring the SMS Gateway

Once the database has been setup, you should install and configure the SMS Gateway. The SMS Gateway we use in this article is the Ozeki NG - SMS Gateway. It can be downloaded from www.ozekisms.com. There are other similar SMS gateways available. We chose this SMS Gateway, because it is very reliable, easy to configure and it is based on .NET which means it integrates well into our architecture. In the SMS gateway, first you should configure the GSM modem attached to your PC. This can be done by adding a GSM Modem service provider connection. Detailed steps:

Step 1. Open http://127.0.0.1:9501 in Internet Explorer, login with admin/abc123.

Step 2. In the "Serviceprovider connections" menu, click on "Add service provider connection", then select "GSM Modem Connection" and click "Install".

Step 3. On the GSM modem configuration form, select the com port (usually COM1) and click on autodetect to configure your modem.

Step 4. In the "Users and applications" menu, click on "Add user", the select "Database user" and click on "install".

Step 5. For username, provide "sql1".

Step 6. For connection string, type select "OleDb" and for connection string enter:

Provider=SQLNCLI;Server=.\SQLEXPRESS;User ID=ozekiuser;password=ozekipass;
Database=ozeki;Persist Security Info=True

Step 7. In the configuration form, I suggest you to turn on SQL logging. You can do this by enabling the checkboxes:

"Log SQL SELECT statements" and "Log SQL UPDATE statements"

Screenshot - sms-gateway-config.gif

Figure 3: SMS Gateway configured.

After these steps, you have configured the SMS Gateway to forward your messages from the database to the mobile devices.

Using the Code

Once the database has been prepared and the SMS Gateway has been setup, you can use Visual Studio .NET to create your SMS application. In Visual Studio, create a new project of "Windows Application" type (Figure 4). This application will provide a GUI for sending the SMS message. It will connect to the database server and will insert a new record when a message is sent to a mobile phone.

Screenshot - sms-gateway-application-create.gif

Figure 4: Application type: Windows Application.

In this application, you should have a form that can be used by the user of your app to compose the message (Figure 5). This form should contain a field for the recipient number and another field for the message text. The form will have a button, that will initiate the sending process.

Screenshot - sms-gateway-form.gif

Figure 5: SMS Message form.

To be able to connect to your database server, you should include the "using System.Data.OleDb;" directive in the using section for your code. The code for sending the SMS message is written into the event handler of the button. In this code, first we connect to the database using an OleDbConnection object. For the connection, we use a standard connection string. If the connection is successful (the
state equals ConnectionState.Open), we execute our SQL INSERT statement to insert the SMS message. To achieve this, we compose the SQL statement and we use an OleDbCommand object to execute it (Figure 6):

private void button1_Click(object sender, EventArgs e)
{
    try
    {
    //Connect to the database
    OleDbConnection conn = new OleDbConnection();

    conn.ConnectionString = "Provider=SQLNCLI;Server=.\\;"+
"User ID=ozekiuser;password=ozekipass;Database=ozeki;Persist Security Info=True";
    conn.Open();
    if (conn.State == ConnectionState.Open)
    {
        //Send the message
        OleDbCommand cmd = new OleDbCommand();
        cmd.Connection = conn;
        string SQLInsert = 
        "INSERT INTO "+
        "ozekimessageout (receiver,msg,status) "+
        "VALUES "+
        "('"+tbSender.Text+"','"+tbMsg.Text+"','send')";
        cmd.CommandText = SQLInsert;
        cmd.ExecuteNonQuery();
        MessageBox.Show("Message sent");
    }

    //Disconnect from the database
    conn.Close();
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }

}

Verifying Your SMS Application

After executing the application, you can send your first SMS message. To track the message, you can use a SQL console to see what is inserted into your SQL table and you should examine the event log of the SMS gateway to see the SQL events. The eventlog of the Ozeki NG SMS gateway is located at the following location:

C:\Program Files\Ozeki\OzekiNG - SMS Gateway\Logs 

References

Good luck!

History

  • 17th August, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Toth Elemer
Web Developer
United Kingdom United Kingdom
Member
I am a Web developer in the U.K.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionIts working same i wanted to workmembersndpj19 Mar '13 - 23:15 
Thanks for sharing a wonderful experience Smile | :) thanks a lot Smile | :) Smile | :)
Sandeep Kr. Jaiswal
Scientific Programmer
NIC UP

QuestionError in connection string [modified]memberMember 964140618 Feb '13 - 3:16 
i have use this code and apply it microsoft visual studio 2012 which has its inbuilt sql server....in in this case how can i connect to the databas?
 
conn.ConnectionString = "Provider=SQLNCLI;Data Source=(LocalDB)\v11.0;AttachDbFilename=ozeki.mdf;Integrated Security=SSPI";
 
this the connection string which i have used...
 
and it appear an error message
 
start with (login time out , an error has occured while establishing aconnection to the server,...)

modified 18 Feb '13 - 10:05.

QuestionHellomemberShambhoo kumar13 Dec '12 - 6:51 
nice work sir...
Thank alot Smile | :)
Questionpak soft sms gatewaymemberjimisd_axily8 Dec '12 - 17:24 
Pak Soft SMS Gateway is a .NET C# messaging Gateway that can be used to send and receive messages using any ETSI 07.05 compliant GSM modem or phone handset connected to the PC serial port through serial cable, infrared or bluetooth.
Some of the features of the Pak Soft SMS Gateway
Fully Supported Multipart Or Long SMS
Send SMS
Read incoming SMS
Send MMS
Read MMS
Send WAP Push message
Send vCalendar,
vCard Send Flash SMS
Send Picture SMS
Ability to define group of destination numbers so that messages can be sent in bulk easily.
Easily Integtrate With Any Database Like (Access,Oracle SQL Server etc) Complete sending and receving sms history
 
U can download from
http://www.mediafire.com/?hadyonq2vhhanw3
 
if u need any help please email me zahid.mahmood2013@gmail.com
AnswerC# smsmemberdharwishnasar11 Jul '12 - 21:01 
checkout this link. it is easy to learn and easy to understand
http://codehues.in/?p=34[^]
BugSQL Injectionmembersuper-e-8 May '12 - 4:10 
This code is awfully prone to SQL injection attacks [^].
You should consider using SQL Command parameters[^] to avoid such problems.
GeneralMy vote of 5memberpaulolove10 Apr '12 - 2:10 
It is very explicit
QuestionHow can i Configure Ozaki Sql Servermembermcaguna16 Sep '11 - 21:10 
Dear Friends.
Good Afternoon.i have installed ozaki server manager.but not config ozaki sql.please anyone help me.please very urgent...
GeneralMy vote of 1memberSercanOzdemir19 May '11 - 12:37 
Does not WORKING!
GeneralMy vote of 5memberTell Will Mosh8 Apr '11 - 20:03 
It works well for me

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 17 Aug 2007
Article Copyright 2007 by Toth Elemer
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid