//Send and Receive SMS using c# and GSM Library
//GSM Library is created by Stefan Mayr
//ProcessConnection.cs and COMPortInfo.cs are used to detect connected GSM Phone during //Window_Loaded_1 events of frmCommSettings.xaml.cs.
classDeclaration.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GSMComm
{
class classDeclaration
{
public static string Port{get;set;}
public static int BaudRate{get;set;}
public static int Timeout{get;set;}
}
}
ProcessConnection.cs
//Add References to System.Management, System.Management.Instrumentation
//Goto Project->Add Reference->.NET Framework-> System.Management, //System.Management.Instrumentation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Management.Instrumentation;
namespace GSMComm
{
public class ProcessConnection
{
public static ConnectionOptions ProcessConnectionOptions()
{
ConnectionOptions options = new ConnectionOptions();
options.Impersonation = ImpersonationLevel.Impersonate;
options.Authentication = AuthenticationLevel.Default;
options.EnablePrivileges = true;
return options;
}
public static ManagementScope ConnectionScope(string machineName, ConnectionOptions options, string path)
{
ManagementScope connectScope = new ManagementScope();
connectScope.Path = new ManagementPath(@"\\" + machineName + path);
connectScope.Options = options;
connectScope.Connect();
return connectScope;
}
}
}
COMPortInfo.cs
//Add References to System.Management, System.Management.Instrumentation
//Goto Project->Add Reference->.NET Framework-> System.Management, //System.Management.Instrumentation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Management.Instrumentation;
namespace GSMComm
{
public class COMPortInfo
{
public string Name { get; set; }
public string Description { get; set; }
public COMPortInfo() { }
public static List GetCOMPortsInfo()
{
List comPortInfoList = new List();
ConnectionOptions options = ProcessConnection.ProcessConnectionOptions();
ManagementScope connectionScope = ProcessConnection.ConnectionScope(Environment.MachineName, options, @"\root\CIMV2");
ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
ManagementObjectSearcher comPortSearcher = new ManagementObjectSearcher(connectionScope, objectQuery);
using (comPortSearcher)
{
string caption = null;
foreach (ManagementObject obj in comPortSearcher.Get())
{
if (obj != null)
{
object captionObj = obj["Caption"];
if (captionObj != null)
{
caption = captionObj.ToString();
if (caption.Contains("(COM"))
{
COMPortInfo comPortInfo = new COMPortInfo();
comPortInfo.Name = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")", string.Empty);
comPortInfo.Description = caption;
comPortInfoList.Add(comPortInfo);
}
}
}
}
}
return comPortInfoList;
}
}
}
frmCommSettings.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using GsmComm.GsmCommunication;
namespace GSMComm
{
///
/// Interaction logic for frmCommSettings.xaml
///
public partial class frmCommSettings : Window
{
public frmCommSettings()
{
InitializeComponent();
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
btnRefresh_Click(this, null);
cboBaudRate.Items.Add("9600");
cboBaudRate.Items.Add("19200");
cboBaudRate.Items.Add("38400");
cboBaudRate.Items.Add("57600");
cboBaudRate.Items.Add("115200");
cboBaudRate.Text="9600";
cboTimeout.Items.Add("150");
cboTimeout.Items.Add("300");
cboTimeout.Items.Add("600");
cboTimeout.Items.Add("900");
cboTimeout.Items.Add("1200");
cboTimeout.Items.Add("1500");
cboTimeout.Items.Add("1800");
cboTimeout.Items.Add("2000");
cboTimeout.Text="300";
}
private void btnTest_Click(object sender, RoutedEventArgs e)
{
//Auto Detect Connected Port
GsmCommMain comm = new GsmCommMain(cboPort.SelectedItem.ToString().Substring(0, 5).Replace("-", ""), Convert.ToInt32(cboBaudRate.Text), Convert.ToInt32(cboTimeout.Text));
//Manual Connection Test
//GsmCommMain comm = new GsmCommMain(cboPort.Text,Convert.ToInt32(cboBaudRate.Text),Convert.ToInt32(cboTimeout.Text));
try
{
comm.Open();
while (!comm.IsConnected())
{
if (MessageBox.Show(this, "No phone connected.", "Connection setup",MessageBoxButton.OK,MessageBoxImage.Error,MessageBoxResult.OK)==MessageBoxResult.OK)
{
comm.Close();
return;
}
}
comm.Close();
}
catch(Exception ex)
{
MessageBox.Show("Connection error: " + ex.Message, "Connection setup", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
MessageBox.Show("Successfully connected to the phone.", "Connection setup", MessageBoxButton.OK, MessageBoxImage.Information);
//For Manual Test
//classDeclaration.Port=cboPort.Text;
//For Auto Detect
classDeclaration.Port = cboPort.SelectedItem.ToString().Substring(0, 5).Replace("-", "");
classDeclaration.BaudRate=Convert.ToInt32(cboBaudRate.Text);
classDeclaration.Timeout = Convert.ToInt32(cboTimeout.Text);
btnOK.IsEnabled = true;
btnOK.IsDefault = true;
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
MainWindow f = new MainWindow();
f.Show();
this.Close();
}
private void btnExit_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
private void btnRefresh_Click(object sender, RoutedEventArgs e)
{
cboPort.Items.Clear();
foreach (COMPortInfo comPort in COMPortInfo.GetCOMPortsInfo())
{
cboPort.Items.Add(string.Format("{0} – {1}", comPort.Name, comPort.Description));
}
}
}
}
MainWindow.xaml.cs
//Add References to using GsmComm.PduConverter;using GsmComm.PduConverter.SmartMessaging;
//using GsmComm.GsmCommunication;using GsmComm.Interfaces;using GsmComm.Server;
//Goto Project->Add Reference->Browse->add the following files from C:\Program //Files\GSMComm\DotNet40 (Available only after GSMLibrary Installation)
// GSMCommServer.dll, GSMCommShared.dll, GSMCommunication.dll, PDUConverter.dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using GsmComm.PduConverter;
using GsmComm.PduConverter.SmartMessaging;
using GsmComm.GsmCommunication;
using GsmComm.Interfaces;
using GsmComm.Server;
namespace GSMComm
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
private GsmCommMain comm;
private bool registerMessageReceived;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
comm = null;
registerMessageReceived = false;
comm = new GsmCommMain(classDeclaration.Port, classDeclaration.BaudRate, classDeclaration.Timeout);
comm.Open();
pb.IsIndeterminate = false;
try
{
// Enable notifications about new received messages
if (!registerMessageReceived)
{
comm.MessageReceived += new MessageReceivedEventHandler(comm_MessageReceived);
registerMessageReceived = true;
}
comm.EnableMessageNotifications();
//MessageBox.Show("Message notifications activated.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnClear_Click(object sender, RoutedEventArgs e)
{
txtmessage.Text = "";
}
private void btnSend_Click(object sender, RoutedEventArgs e)
{
pb.IsIndeterminate = true;
// Thread.Sleep(60000);
try
{
// Send an SMS message
SmsSubmitPdu pdu;
// Send message in the default format
pdu = new SmsSubmitPdu(txtmessage.Text, txtno.Text);
pdu.RequestStatusReport = true;
comm.SendMessage(pdu);
MessageBox.Show(ShowMessage(pdu));
}
catch (CommException ex)
{
MessageBox.Show(ex.Message.ToString());
}
// }
pb.IsIndeterminate = false;
}
private void comm_MessageReceived(object sender, MessageReceivedEventArgs e)
{
try
{
IMessageIndicationObject obj = e.IndicationObject;
if (obj is ShortMessage)
{
ShortMessage msg = (ShortMessage)obj;
SmsPdu pdu = comm.DecodeReceivedMessage(msg);
MessageBox.Show("New message received.");
txtmessage.Text = ShowMessage(pdu);
}
if (obj is MemoryLocation)
{
MemoryLocation loc = (MemoryLocation)obj;
MessageBox.Show(string.Format("New message received in storage \"{0}\", index {1}.", loc.Storage, loc.Index));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private string GetMessageStorage()
{
string storage = string.Empty;
//if (rbMessageSIM.Checked)
storage = PhoneStorageType.Sim;
//if (rbMessagePhone.Checked)
// storage = PhoneStorageType.Phone;
if (storage.Length == 0)
throw new ApplicationException("Unknown message storage.");
else
return storage;
}
private string ShowMessage(SmsPdu pdu)
{
string output;
if (pdu is SmsSubmitPdu)
{
// Stored (sent/unsent) message
SmsSubmitPdu data = (SmsSubmitPdu)pdu;
output ="SENT/UNSENT MESSAGE" + "\n";
output = output + "Recipient: " + data.DestinationAddress + "\n";
output = output + "Message text: " + data.UserDataText + "\n";
return output;
}
if (pdu is SmsDeliverPdu)
{
// Received message
SmsDeliverPdu data = (SmsDeliverPdu)pdu;
output = "RECEIVED MESSAGE" + "\n";
output = output + "Sender: " + data.OriginatingAddress + "\n";
output = output + "Sent: " + data.SCTimestamp.ToString() + "\n";
output = output + "Message text: " + data.UserDataText + "\n";
return output;
}
if (pdu is SmsStatusReportPdu)
{
// Status report
SmsStatusReportPdu data = (SmsStatusReportPdu)pdu;
output = "STATUS REPORT" + "\n";
output = output + "Recipient: " + data.RecipientAddress + "\n";
output = output + "Status: " + data.Status.ToString() + "\n";
output = output + "Timestamp: " + data.DischargeTime.ToString() + "\n";
output = output + "Message ref: " + data.MessageReference.ToString() + "\n";
return output;
}
MessageBox.Show("Unknown message type: " + pdu.GetType().ToString());
return null;
}
private void cmdPhoneInfo_Click(object sender, RoutedEventArgs e)
{
IdentificationInfo info = comm.IdentifyDevice();
txtmessage.Text = "";
txtmessage.Text = txtmessage.Text + "Manufacturer: " + info.Manufacturer + "\n";
txtmessage.Text = txtmessage.Text + "Model: " + info.Model + "\n";
txtmessage.Text = txtmessage.Text + "Revision: " + info.Revision + "\n";
txtmessage.Text = txtmessage.Text + "Serial number: " + info.SerialNumber + "\n";
}
private void cmdmsgstatus_Click(object sender, RoutedEventArgs e)
{
txtmessage.Text = "";
string storage = GetMessageStorage();
try
{
// Get memory status of the storage
MemoryStatus status = comm.GetMessageMemoryStatus(storage);
int percentUsed = (status.Total > 0) ? (int)((double)status.Used / (double)status.Total * 100) : 0;
txtmessage.Text = string.Format("Message memory status: {0} of {1} used ({2}% used, {3}% free)", status.Used, status.Total, percentUsed, 100 - percentUsed);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnRead_Click(object sender, RoutedEventArgs e)
{
pb.IsIndeterminate = true;
string storage = GetMessageStorage();
txtmessage.Text = "";
try
{
// Read all SMS messages from the storage
DecodedShortMessage[] messages = comm.ReadMessages(PhoneMessageStatus.ReceivedUnread, storage);
foreach (DecodedShortMessage message in messages)
{
txtmessage.Text = string.Format("Message status = {0} \nLocation = {1}/{2}", StatusToString(message.Status), message.Storage, message.Index);
txtmessage.Text = txtmessage.Text + "\n" + ShowMessage(message.Data);
}
MessageBox.Show(string.Format("{0,9} unread messages.", messages.Length.ToString()));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
pb.IsIndeterminate = false;
}
private void btnReadAllMessages_Click(object sender, RoutedEventArgs e)
{
pb.IsIndeterminate = true;
string storage = GetMessageStorage();
txtmessage.Text = "";
try
{
// Read all SMS messages from the storage
DecodedShortMessage[] messages = comm.ReadMessages(PhoneMessageStatus.All, storage);
foreach (DecodedShortMessage message in messages)
{
txtmessage.Text = txtmessage.Text + "\n" + string.Format("Message status = {0} \nLocation = {1}/{2}", StatusToString(message.Status), message.Storage, message.Index);
txtmessage.Text = txtmessage.Text + "\n" + ShowMessage(message.Data);
}
MessageBox.Show(string.Format("{0,9} messages read.", messages.Length.ToString()));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
pb.IsIndeterminate = false;
}
private string StatusToString(PhoneMessageStatus status)
{
// Map a message status to a string
string ret;
switch (status)
{
case PhoneMessageStatus.All:
ret = "All";
break;
case PhoneMessageStatus.ReceivedRead:
ret = "Read";
break;
case PhoneMessageStatus.ReceivedUnread:
ret = "Unread";
break;
case PhoneMessageStatus.StoredSent:
ret = "Sent";
break;
case PhoneMessageStatus.StoredUnsent:
ret = "Unsent";
break;
default:
ret = "Unknown (" + status.ToString() + ")";
break;
}
return ret;
}
private void btnownnumber_Click(object sender, RoutedEventArgs e)
{
try
{
// Get the subscriber numbers
SubscriberInfo[] info2 = comm.GetSubscriberNumbers();
foreach (SubscriberInfo info in info2)
{
txtmessage.Text=string.Format("{0,-20}Type {1}, Speed {2}, Service {3}, ITC {4}, Alpha {5}",info.Number, info.Type, info.Speed, info.Service, info.Itc, info.Alpha) + "\n";
}
txtmessage.Text= string.Format("{0,9} number(s) found.", info2.Length.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void DeleteAllMessages()
{
string storage = GetMessageStorage();
try
{
// Delete all messages from phone memory
comm.DeleteMessages(DeleteScope.All, storage);
MessageBox.Show("All Messages Deleted from SIM");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnoperator_Click(object sender, RoutedEventArgs e)
{
try
{
// List the operators detected by the phone
OperatorInfo2[] info2 = comm.ListOperators();
txtmessage.Text = "";
txtmessage.Text=txtmessage.Text + "Operator list:" + "\n";
txtmessage.Text = txtmessage.Text + "--------------------------------------------" + "\n";
foreach (OperatorInfo2 info in info2)
{
txtmessage.Text = txtmessage.Text + string.Format("Status: {0}\r\nComplete Name: {1}\r\nShorten Name: {2}\r\n Numeric: {3}\r\nAccess Technology: {4}", info.Status, info.LongAlphanumeric, info.ShortAlphanumeric, info.Numeric, info.AccessTechnology) + "\n";
}
txtmessage.Text = txtmessage.Text + "--------------------------------------------" + "\n";
txtmessage.Text = txtmessage.Text + string.Format("{0} operator(s) found.", info2.Length.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void Window_GotFocus_1(object sender, RoutedEventArgs e)
{
btnsignal_Click(sender,e);
}
private void btnsignal_Click(object sender, RoutedEventArgs e)
{
try
{
// Get signal quality
SignalQualityInfo info = comm.GetSignalQuality();
txtsignal.Text = "Signal Strength : " + info.SignalStrength.ToString() + "%";
}
catch (Exception)
{
txtsignal.Text="Signal Strength : 0%";
}
}
private void Window_Closing_1(object sender, System.ComponentModel.CancelEventArgs e)
{
if (MessageBox.Show("Are you sure you want to Exit?", "GSM Phone Project", MessageBoxButton.YesNo).Equals(MessageBoxResult.No))
{
e.Cancel = true;
}
else { comm.Close(); }
}
private void btnReadUnSent_Click(object sender, RoutedEventArgs e)
{
pb.IsIndeterminate = true;
string storage = GetMessageStorage();
txtmessage.Text = "";
try
{
// Read all SMS messages from the storage
DecodedShortMessage[] messages = comm.ReadMessages(PhoneMessageStatus.StoredUnsent, storage);
foreach (DecodedShortMessage message in messages)
{
txtmessage.Text = txtmessage.Text + "\n" + string.Format("Message status = {0} \nLocation = {1}/{2}", StatusToString(message.Status), message.Storage, message.Index);
txtmessage.Text = txtmessage.Text + "\n" + ShowMessage(message.Data);
}
MessageBox.Show(string.Format("{0,9} messages read.", messages.Length.ToString()));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
pb.IsIndeterminate = false;
}
private void btnReadSent_Click(object sender, RoutedEventArgs e)
{
pb.IsIndeterminate = true;
string storage = GetMessageStorage();
txtmessage.Text = "";
try
{
// Read all SMS messages from the storage
DecodedShortMessage[] messages = comm.ReadMessages(PhoneMessageStatus.StoredSent, storage);
foreach (DecodedShortMessage message in messages)
{
txtmessage.Text = txtmessage.Text + "\n" + string.Format("Message status = {0} \nLocation = {1}/{2}", StatusToString(message.Status), message.Storage, message.Index);
txtmessage.Text = txtmessage.Text + "\n" + ShowMessage(message.Data);
}
MessageBox.Show(string.Format("{0,9} messages read.", messages.Length.ToString()));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
pb.IsIndeterminate = false;
}
}
}
//GSM Library is created by Stefan Mayr
//ProcessConnection.cs and COMPortInfo.cs are used to detect connected GSM Phone during //Window_Loaded_1 events of frmCommSettings.xaml.cs.
classDeclaration.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GSMComm
{
class classDeclaration
{
public static string Port{get;set;}
public static int BaudRate{get;set;}
public static int Timeout{get;set;}
}
}
ProcessConnection.cs
//Add References to System.Management, System.Management.Instrumentation
//Goto Project->Add Reference->.NET Framework-> System.Management, //System.Management.Instrumentation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Management.Instrumentation;
namespace GSMComm
{
public class ProcessConnection
{
public static ConnectionOptions ProcessConnectionOptions()
{
ConnectionOptions options = new ConnectionOptions();
options.Impersonation = ImpersonationLevel.Impersonate;
options.Authentication = AuthenticationLevel.Default;
options.EnablePrivileges = true;
return options;
}
public static ManagementScope ConnectionScope(string machineName, ConnectionOptions options, string path)
{
ManagementScope connectScope = new ManagementScope();
connectScope.Path = new ManagementPath(@"\\" + machineName + path);
connectScope.Options = options;
connectScope.Connect();
return connectScope;
}
}
}
COMPortInfo.cs
//Add References to System.Management, System.Management.Instrumentation
//Goto Project->Add Reference->.NET Framework-> System.Management, //System.Management.Instrumentation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Management.Instrumentation;
namespace GSMComm
{
public class COMPortInfo
{
public string Name { get; set; }
public string Description { get; set; }
public COMPortInfo() { }
public static List
{
List
ConnectionOptions options = ProcessConnection.ProcessConnectionOptions();
ManagementScope connectionScope = ProcessConnection.ConnectionScope(Environment.MachineName, options, @"\root\CIMV2");
ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
ManagementObjectSearcher comPortSearcher = new ManagementObjectSearcher(connectionScope, objectQuery);
using (comPortSearcher)
{
string caption = null;
foreach (ManagementObject obj in comPortSearcher.Get())
{
if (obj != null)
{
object captionObj = obj["Caption"];
if (captionObj != null)
{
caption = captionObj.ToString();
if (caption.Contains("(COM"))
{
COMPortInfo comPortInfo = new COMPortInfo();
comPortInfo.Name = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")", string.Empty);
comPortInfo.Description = caption;
comPortInfoList.Add(comPortInfo);
}
}
}
}
}
return comPortInfoList;
}
}
}
frmCommSettings.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using GsmComm.GsmCommunication;
namespace GSMComm
{
///
/// Interaction logic for frmCommSettings.xaml
///
public partial class frmCommSettings : Window
{
public frmCommSettings()
{
InitializeComponent();
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
btnRefresh_Click(this, null);
cboBaudRate.Items.Add("9600");
cboBaudRate.Items.Add("19200");
cboBaudRate.Items.Add("38400");
cboBaudRate.Items.Add("57600");
cboBaudRate.Items.Add("115200");
cboBaudRate.Text="9600";
cboTimeout.Items.Add("150");
cboTimeout.Items.Add("300");
cboTimeout.Items.Add("600");
cboTimeout.Items.Add("900");
cboTimeout.Items.Add("1200");
cboTimeout.Items.Add("1500");
cboTimeout.Items.Add("1800");
cboTimeout.Items.Add("2000");
cboTimeout.Text="300";
}
private void btnTest_Click(object sender, RoutedEventArgs e)
{
//Auto Detect Connected Port
GsmCommMain comm = new GsmCommMain(cboPort.SelectedItem.ToString().Substring(0, 5).Replace("-", ""), Convert.ToInt32(cboBaudRate.Text), Convert.ToInt32(cboTimeout.Text));
//Manual Connection Test
//GsmCommMain comm = new GsmCommMain(cboPort.Text,Convert.ToInt32(cboBaudRate.Text),Convert.ToInt32(cboTimeout.Text));
try
{
comm.Open();
while (!comm.IsConnected())
{
if (MessageBox.Show(this, "No phone connected.", "Connection setup",MessageBoxButton.OK,MessageBoxImage.Error,MessageBoxResult.OK)==MessageBoxResult.OK)
{
comm.Close();
return;
}
}
comm.Close();
}
catch(Exception ex)
{
MessageBox.Show("Connection error: " + ex.Message, "Connection setup", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
MessageBox.Show("Successfully connected to the phone.", "Connection setup", MessageBoxButton.OK, MessageBoxImage.Information);
//For Manual Test
//classDeclaration.Port=cboPort.Text;
//For Auto Detect
classDeclaration.Port = cboPort.SelectedItem.ToString().Substring(0, 5).Replace("-", "");
classDeclaration.BaudRate=Convert.ToInt32(cboBaudRate.Text);
classDeclaration.Timeout = Convert.ToInt32(cboTimeout.Text);
btnOK.IsEnabled = true;
btnOK.IsDefault = true;
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
MainWindow f = new MainWindow();
f.Show();
this.Close();
}
private void btnExit_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
private void btnRefresh_Click(object sender, RoutedEventArgs e)
{
cboPort.Items.Clear();
foreach (COMPortInfo comPort in COMPortInfo.GetCOMPortsInfo())
{
cboPort.Items.Add(string.Format("{0} – {1}", comPort.Name, comPort.Description));
}
}
}
}
MainWindow.xaml.cs
//Add References to using GsmComm.PduConverter;using GsmComm.PduConverter.SmartMessaging;
//using GsmComm.GsmCommunication;using GsmComm.Interfaces;using GsmComm.Server;
//Goto Project->Add Reference->Browse->add the following files from C:\Program //Files\GSMComm\DotNet40 (Available only after GSMLibrary Installation)
// GSMCommServer.dll, GSMCommShared.dll, GSMCommunication.dll, PDUConverter.dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using GsmComm.PduConverter;
using GsmComm.PduConverter.SmartMessaging;
using GsmComm.GsmCommunication;
using GsmComm.Interfaces;
using GsmComm.Server;
namespace GSMComm
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
private GsmCommMain comm;
private bool registerMessageReceived;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
comm = null;
registerMessageReceived = false;
comm = new GsmCommMain(classDeclaration.Port, classDeclaration.BaudRate, classDeclaration.Timeout);
comm.Open();
pb.IsIndeterminate = false;
try
{
// Enable notifications about new received messages
if (!registerMessageReceived)
{
comm.MessageReceived += new MessageReceivedEventHandler(comm_MessageReceived);
registerMessageReceived = true;
}
comm.EnableMessageNotifications();
//MessageBox.Show("Message notifications activated.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnClear_Click(object sender, RoutedEventArgs e)
{
txtmessage.Text = "";
}
private void btnSend_Click(object sender, RoutedEventArgs e)
{
pb.IsIndeterminate = true;
// Thread.Sleep(60000);
try
{
// Send an SMS message
SmsSubmitPdu pdu;
// Send message in the default format
pdu = new SmsSubmitPdu(txtmessage.Text, txtno.Text);
pdu.RequestStatusReport = true;
comm.SendMessage(pdu);
MessageBox.Show(ShowMessage(pdu));
}
catch (CommException ex)
{
MessageBox.Show(ex.Message.ToString());
}
// }
pb.IsIndeterminate = false;
}
private void comm_MessageReceived(object sender, MessageReceivedEventArgs e)
{
try
{
IMessageIndicationObject obj = e.IndicationObject;
if (obj is ShortMessage)
{
ShortMessage msg = (ShortMessage)obj;
SmsPdu pdu = comm.DecodeReceivedMessage(msg);
MessageBox.Show("New message received.");
txtmessage.Text = ShowMessage(pdu);
}
if (obj is MemoryLocation)
{
MemoryLocation loc = (MemoryLocation)obj;
MessageBox.Show(string.Format("New message received in storage \"{0}\", index {1}.", loc.Storage, loc.Index));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private string GetMessageStorage()
{
string storage = string.Empty;
//if (rbMessageSIM.Checked)
storage = PhoneStorageType.Sim;
//if (rbMessagePhone.Checked)
// storage = PhoneStorageType.Phone;
if (storage.Length == 0)
throw new ApplicationException("Unknown message storage.");
else
return storage;
}
private string ShowMessage(SmsPdu pdu)
{
string output;
if (pdu is SmsSubmitPdu)
{
// Stored (sent/unsent) message
SmsSubmitPdu data = (SmsSubmitPdu)pdu;
output ="SENT/UNSENT MESSAGE" + "\n";
output = output + "Recipient: " + data.DestinationAddress + "\n";
output = output + "Message text: " + data.UserDataText + "\n";
return output;
}
if (pdu is SmsDeliverPdu)
{
// Received message
SmsDeliverPdu data = (SmsDeliverPdu)pdu;
output = "RECEIVED MESSAGE" + "\n";
output = output + "Sender: " + data.OriginatingAddress + "\n";
output = output + "Sent: " + data.SCTimestamp.ToString() + "\n";
output = output + "Message text: " + data.UserDataText + "\n";
return output;
}
if (pdu is SmsStatusReportPdu)
{
// Status report
SmsStatusReportPdu data = (SmsStatusReportPdu)pdu;
output = "STATUS REPORT" + "\n";
output = output + "Recipient: " + data.RecipientAddress + "\n";
output = output + "Status: " + data.Status.ToString() + "\n";
output = output + "Timestamp: " + data.DischargeTime.ToString() + "\n";
output = output + "Message ref: " + data.MessageReference.ToString() + "\n";
return output;
}
MessageBox.Show("Unknown message type: " + pdu.GetType().ToString());
return null;
}
private void cmdPhoneInfo_Click(object sender, RoutedEventArgs e)
{
IdentificationInfo info = comm.IdentifyDevice();
txtmessage.Text = "";
txtmessage.Text = txtmessage.Text + "Manufacturer: " + info.Manufacturer + "\n";
txtmessage.Text = txtmessage.Text + "Model: " + info.Model + "\n";
txtmessage.Text = txtmessage.Text + "Revision: " + info.Revision + "\n";
txtmessage.Text = txtmessage.Text + "Serial number: " + info.SerialNumber + "\n";
}
private void cmdmsgstatus_Click(object sender, RoutedEventArgs e)
{
txtmessage.Text = "";
string storage = GetMessageStorage();
try
{
// Get memory status of the storage
MemoryStatus status = comm.GetMessageMemoryStatus(storage);
int percentUsed = (status.Total > 0) ? (int)((double)status.Used / (double)status.Total * 100) : 0;
txtmessage.Text = string.Format("Message memory status: {0} of {1} used ({2}% used, {3}% free)", status.Used, status.Total, percentUsed, 100 - percentUsed);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnRead_Click(object sender, RoutedEventArgs e)
{
pb.IsIndeterminate = true;
string storage = GetMessageStorage();
txtmessage.Text = "";
try
{
// Read all SMS messages from the storage
DecodedShortMessage[] messages = comm.ReadMessages(PhoneMessageStatus.ReceivedUnread, storage);
foreach (DecodedShortMessage message in messages)
{
txtmessage.Text = string.Format("Message status = {0} \nLocation = {1}/{2}", StatusToString(message.Status), message.Storage, message.Index);
txtmessage.Text = txtmessage.Text + "\n" + ShowMessage(message.Data);
}
MessageBox.Show(string.Format("{0,9} unread messages.", messages.Length.ToString()));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
pb.IsIndeterminate = false;
}
private void btnReadAllMessages_Click(object sender, RoutedEventArgs e)
{
pb.IsIndeterminate = true;
string storage = GetMessageStorage();
txtmessage.Text = "";
try
{
// Read all SMS messages from the storage
DecodedShortMessage[] messages = comm.ReadMessages(PhoneMessageStatus.All, storage);
foreach (DecodedShortMessage message in messages)
{
txtmessage.Text = txtmessage.Text + "\n" + string.Format("Message status = {0} \nLocation = {1}/{2}", StatusToString(message.Status), message.Storage, message.Index);
txtmessage.Text = txtmessage.Text + "\n" + ShowMessage(message.Data);
}
MessageBox.Show(string.Format("{0,9} messages read.", messages.Length.ToString()));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
pb.IsIndeterminate = false;
}
private string StatusToString(PhoneMessageStatus status)
{
// Map a message status to a string
string ret;
switch (status)
{
case PhoneMessageStatus.All:
ret = "All";
break;
case PhoneMessageStatus.ReceivedRead:
ret = "Read";
break;
case PhoneMessageStatus.ReceivedUnread:
ret = "Unread";
break;
case PhoneMessageStatus.StoredSent:
ret = "Sent";
break;
case PhoneMessageStatus.StoredUnsent:
ret = "Unsent";
break;
default:
ret = "Unknown (" + status.ToString() + ")";
break;
}
return ret;
}
private void btnownnumber_Click(object sender, RoutedEventArgs e)
{
try
{
// Get the subscriber numbers
SubscriberInfo[] info2 = comm.GetSubscriberNumbers();
foreach (SubscriberInfo info in info2)
{
txtmessage.Text=string.Format("{0,-20}Type {1}, Speed {2}, Service {3}, ITC {4}, Alpha {5}",info.Number, info.Type, info.Speed, info.Service, info.Itc, info.Alpha) + "\n";
}
txtmessage.Text= string.Format("{0,9} number(s) found.", info2.Length.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void DeleteAllMessages()
{
string storage = GetMessageStorage();
try
{
// Delete all messages from phone memory
comm.DeleteMessages(DeleteScope.All, storage);
MessageBox.Show("All Messages Deleted from SIM");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnoperator_Click(object sender, RoutedEventArgs e)
{
try
{
// List the operators detected by the phone
OperatorInfo2[] info2 = comm.ListOperators();
txtmessage.Text = "";
txtmessage.Text=txtmessage.Text + "Operator list:" + "\n";
txtmessage.Text = txtmessage.Text + "--------------------------------------------" + "\n";
foreach (OperatorInfo2 info in info2)
{
txtmessage.Text = txtmessage.Text + string.Format("Status: {0}\r\nComplete Name: {1}\r\nShorten Name: {2}\r\n Numeric: {3}\r\nAccess Technology: {4}", info.Status, info.LongAlphanumeric, info.ShortAlphanumeric, info.Numeric, info.AccessTechnology) + "\n";
}
txtmessage.Text = txtmessage.Text + "--------------------------------------------" + "\n";
txtmessage.Text = txtmessage.Text + string.Format("{0} operator(s) found.", info2.Length.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void Window_GotFocus_1(object sender, RoutedEventArgs e)
{
btnsignal_Click(sender,e);
}
private void btnsignal_Click(object sender, RoutedEventArgs e)
{
try
{
// Get signal quality
SignalQualityInfo info = comm.GetSignalQuality();
txtsignal.Text = "Signal Strength : " + info.SignalStrength.ToString() + "%";
}
catch (Exception)
{
txtsignal.Text="Signal Strength : 0%";
}
}
private void Window_Closing_1(object sender, System.ComponentModel.CancelEventArgs e)
{
if (MessageBox.Show("Are you sure you want to Exit?", "GSM Phone Project", MessageBoxButton.YesNo).Equals(MessageBoxResult.No))
{
e.Cancel = true;
}
else { comm.Close(); }
}
private void btnReadUnSent_Click(object sender, RoutedEventArgs e)
{
pb.IsIndeterminate = true;
string storage = GetMessageStorage();
txtmessage.Text = "";
try
{
// Read all SMS messages from the storage
DecodedShortMessage[] messages = comm.ReadMessages(PhoneMessageStatus.StoredUnsent, storage);
foreach (DecodedShortMessage message in messages)
{
txtmessage.Text = txtmessage.Text + "\n" + string.Format("Message status = {0} \nLocation = {1}/{2}", StatusToString(message.Status), message.Storage, message.Index);
txtmessage.Text = txtmessage.Text + "\n" + ShowMessage(message.Data);
}
MessageBox.Show(string.Format("{0,9} messages read.", messages.Length.ToString()));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
pb.IsIndeterminate = false;
}
private void btnReadSent_Click(object sender, RoutedEventArgs e)
{
pb.IsIndeterminate = true;
string storage = GetMessageStorage();
txtmessage.Text = "";
try
{
// Read all SMS messages from the storage
DecodedShortMessage[] messages = comm.ReadMessages(PhoneMessageStatus.StoredSent, storage);
foreach (DecodedShortMessage message in messages)
{
txtmessage.Text = txtmessage.Text + "\n" + string.Format("Message status = {0} \nLocation = {1}/{2}", StatusToString(message.Status), message.Storage, message.Index);
txtmessage.Text = txtmessage.Text + "\n" + ShowMessage(message.Data);
}
MessageBox.Show(string.Format("{0,9} messages read.", messages.Length.ToString()));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
pb.IsIndeterminate = false;
}
}
}