show-notice
hide-notice

Tuesday, 3 September 2013

Send SMS using Modem(GSM Dongle) in C#


Introduction:

Here i will explain Send SMS using Modem(GSM Dongle) in C#.

Description:

today we will discuss a very important topic, sending SMS alerts to a mobile phone that is a common demand of most clients. So we developed a small application that runs on the server and sends a SMS whenever a new record is inserted into the database from any client.


In this application we will use the following:

  • GSM Modem (I have used Vodafone; you can use any)
  • SIM Card.
 Create the table in SQL Server.


CREATE TABLE [dbo].[Donor_Profile](

      [Don_Date] [datetime] NULL,

      [Don_Donor_ID] [varchar](20) NOT NULL,

      [Don_Donor_Name] [varchar](50) NULL,

[Don_Mobile_Phone] [varchar](50) NULL,

      [Don_Member] [varchar](10) NULL,

      [Don_SMS1] [varchar](10) NULL,

      [Don_SMS2] [varchar](10) NULL,

      [Don_Logo] [image] NULL,

      [Don_Donor_Type] [int] NULL,

 CONSTRAINT [PK_Donor_Profile] PRIMARY KEY CLUSTERED

(

      [Don_Donor_ID] ASC

)
WITH (PAD_INDEX  = OFF,
STATISTICS_NORECOMPUTE  = OFF,
IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

)
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Now you can insert any record in the table but please make sure to insert: [Don_Donor_ID]= CF-00001-12 and leave the [Don_SMS1], [Don_SMS2] field NULL, [Don_Mobile_Phone] please enter valid phone number where you want to recive the sms. Create the new Desktop application. Design the form as shown in the picture. 



Step 5

Dear Reader, please read this carefully in thais step we need to include the following DLL files in the bin\ Debug folder:

  • GSMCommServer.dll
  • GSMCommShared.dll
  • GSMCommunication.dll
  • PDUConverter.dll


Step 6

Now we need to add the reference to the project as shown in the picture.













Now we have added one more reference.



Now we need to move to the code behind window and use these references in the code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using GsmComm.PduConverter;
using GsmComm.PduConverter.SmartMessaging;
using GsmComm.GsmCommunication;
using GsmComm.Interfaces;
using GsmComm.Server;
using System.Globalization;

namespace GSMModem
{
    public partial class Form1 : Form
    {
        private GsmCommMain comm;
        private delegate void SetTextCallback(string text);
        private SmsServer smsServer;
        public Form1()
        {
            InitializeComponent();
        }
Now we need to add few textboxes and private variables that we will use in our code.
namespace GSMModem
{
    public partial class Form1 : Form
    {
        private GsmCommMain comm;
        private delegate void SetTextCallback(string text);
        private SmsServer smsServer;
        public Form1()
        {
            InitializeComponent();
        }
        TextBox txtMessage = new TextBox();
        TextBox txtDonorName = new TextBox();
        TextBox txtNumber = new TextBox();
        TextBox txtDonorId = new TextBox();

Now we will add the two classes Operation and Main as in the following and add two methods in it GetDBConnection, ipconfig and Execute.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace GSMModem
{
    class Operation
    {
        public string ipconfig(string filePath)
        {
            StreamReader streamReader = new StreamReader(filePath);
            string text = streamReader.ReadToEnd();
            streamReader.Close();
            return text;
        }

        public void Execute(string SQL)
        {
                SqlConnection con = Main.GetDBConnection();
                con.Open(); 
                SqlCommand cmd = new SqlCommand(SQL, con);
                cmd.ExecuteNonQuery();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;

namespace GSMModem
{
    class Main
    {
        public static SqlConnection GetDBConnection()
        {
            Operation ipconf = new Operation();
            string path = Directory.GetCurrentDirectory();
            string path1 = ipconf.ipconfig(path + "\\" + "IPCONfG.txt");
            string strerverIP = path1;

            // Define the Access Database driver and the filename of the database
            SqlConnection conn = new SqlConnection(
        "Data Source=" + strerverIP + @"\CRMIS;Initial Catalog=PSH;User ID=sa;Password=sa12345");
            return conn;
        }
    }
}

Now add the following code in the form load event.
private void Form1_Load(object sender, EventArgs e)
        {
            cmbCOM.Items.Add("COM1");
            cmbCOM.Items.Add("COM2");
            cmbCOM.Items.Add("COM3");
            cmbCOM.Items.Add("COM4");
            cmbCOM.Items.Add("COM5");
            cmbCOM.Items.Add("COM6");
        }

Now add the following code in the connect button click event.
 
private void btnConnect_Click(object sender, EventArgs e)
        {
            if (cmbCOM.Text == "")
            {
                MessageBox.Show("Invalid Port Name");
                return;
            }
             comm = new GsmCommMain(cmbCOM.Text , 9600, 150);
            Cursor.Current = Cursors.Default;
            bool retry;
            do
            {   retry = false;
                try
                {   Cursor.Current = Cursors.WaitCursor;
                    comm.Open();
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("Modem Connected Sucessfully");
                }
                catch (Exception)
                {   Cursor.Current = Cursors.Default;
                    if (MessageBox.Show(this, "GSM Modem is not available", "Check",
                        MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning) == DialogResult.Retry)
                        retry = true;
                    else
                   { return;}
               }
            }
            while (retry);

        }

Now add the following code in the send button click event.
private void btnSend_Click(object sender, EventArgs e)
        {
            Operation code = new Operation();
            try
            {
                SqlConnection con = Main.GetDBConnection();
                DataTable consultanttable = new DataTable();
                string sqlConsultant = @"SELECT  Don_Donor_ID,Don_Donor_Name,left(Don_Mobile_Phone,4)+ right(Don_Mobile_Phone,7) 
                FROM  psh.dbo.Donor_Profile WHERE (Don_SMS1 IS NULL) or (Don_SMS1='notsend') and Don_Donor_ID ='CF-00001-12'";
                SqlDataAdapter Consultantdataadapter = new SqlDataAdapter(sqlConsultant, con);
                Consultantdataadapter.Fill(consultanttable);
                foreach (DataRow myrow in consultanttable.Rows)
                {
                    txtDonorId.Text = Convert.ToString(myrow[0]);
                    txtDonorName.Text = Convert.ToString(myrow[1]);
                    txtNumber.Text = Convert.ToString(myrow[2]);
                    Cursor.Current = Cursors.WaitCursor;
                    txtMessage.Text = "Respected " + txtDonorName.Text + ", Welcome to Clapp Trust. Your donor ID is " + txtDonorId.Text + ". Our online system will send you SMS whenever your donation is received.";
                    try
                    {
                        SmsSubmitPdu pdu;
                        byte dcs = (byte)DataCodingScheme.GeneralCoding.Alpha7BitDefault;
                        pdu = new SmsSubmitPdu(txtMessage.Text, Convert.ToString(txtNumber.Text), dcs);
                        int times = 1;
                        for (int i = 0; i < times; i++)
                        {
                            comm.SendMessage(pdu);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Modem is not available");
                        code.Execute("update psh.dbo.donor_profile set don_sms2='notsend' where don_donor_id ='" + txtDonorId.Text + "'");
                    }
                }
            }
            catch
            {
                MessageBox.Show("SMS not send");
            }

        }

Now we need to attach the modem to the system. It will install its own application but keep this point in your mind, you need to close the application after the installation is complete because that software captures the port that we will use in our code. let this application to be installed and close it when it is finished Now run the application; press F5. First we need to select the port name from the drop down menu then press the connect button; if port is not valid then it will show the error message.


Now I will select port COM4; it will connect successfully. Dear reader, you need to check your port one by one; Windows XP normally uses port COM3 or COM4.

Now press the "Send SMS button"; you will then get a SMS on your mobile phone


Download

SHARE THIS POST   

10 comments :

  1. No phone connected error. :/

    ReplyDelete
  2. the GsmCommMain(int,int,int) not GsmCommMain(text,int,int) error
    comm = new GsmCommMain(cmbCOM.Text , 9600, 150); text as argument in invalid

    ReplyDelete
  3. You are a life saver broo... Many thanks

    ReplyDelete
  4. Hello.. Can you please help me show the messages in a listview?

    ReplyDelete
  5. modem not connected .
    can you help me ..

    ReplyDelete
  6. Thanks for sharing this blog. We have now started providing bulk SMS API C# India that is very powerful and easy to integrate into your own software/application/website. As it saves your lot of valuable time in logging our interface again and again.

    ReplyDelete

Design by Gohilinfotech | www.gohilinfotech.blogspot.com