Send SMS through USB Modem in MS CRM Plugin.

Hello Everyone,

Sending SMS messages from CRM is a common and a critical requirement for many customers. Once you know it, it is really simple to send SMSs from Microsoft Dynamics CRM with the help of a USB Dongle and C#(Plugin/Custom Workflow).


I will now illustrate the whole process step by step:

  • Step 1: One needs to learn about AT Commands (which are used to interact with the Modem[USB Dongle] connected to a Port on Server). After learning about AT Commands, we will be testing the commands through a terminal.
  • Step 2: Create a C# class library to access the Port to which your USB Dongle is attached to, send commands to the port to send SMS and close the port.Integrate the code to a CRM Plugin/Workflow.

AT(Attention) Commands

AT commands (or Attention Commands) are used to control modems to do their specified functions. Most of the AT Commands start with “AT”, but the exact usage of the term AT command set slightly varies from manufacturer to manufacturer.

The most common set of AT Commands are:

  • AT (Command to check if the modem is connected)

         Usage:  Type “AT”. Press Enter.

         Response:   If response is “OK”, modem is connected. Else, response will be “ERROR”.

  • ATE1 (Command to enable echo of requests to Modem)(Initially all commands sent by you will not be visible on terminal)

         Usage:  Type “ATE1”. Press Enter.

         Response:   “OK” will be returned and now the Commands sent by you can be seen on the terminal.

  • AT+CMGF (Command to check/set the message mode[PDU Mode/SMS Mode])

         Check:

         Usage:  Type “AT+CMGF=?”. Press Enter.

         Response:   “+CMGF: (0-1)” will be returned, which signifies that the command accepts 2 values: 0(PDU Mode) and 1(SMS Mode).

         Set:

         Usage:  Type “AT+CMGF=1”. Press Enter.

         Response:   “OK” will be returned if the modem is set to SMS Mode.

  • AT+CMGS (Command to send SMS to a specific number)

         Usage:  Type AT+CMGS=”RECIPIENT_NUMBER”    Press Enter.

         Response:   “>” will be returned and the console will wait for a message to be typed. Once the message is typed “CTRL + Z” can be pressed to send the SMS or “Esc” to cancel the command. After pressing CTRL + Z, the message will be delivered with a response “+CMGS: 23 OK” (23 indicates the SMS number) or “ERROR”.

         Example:

AT+CMGS=”+918867125456″  [Press Enter]

> Hi there! This is a message from Kautuk.   [Ctrl + Z]

+CMGS: 23

OK

Now, as we have a fair idea of AT Commands lets try it out on Hyper Terminal. (Hyper Terminal is a interface/tool to connect and interact with Modems using AT Commands. You can download a free trial of 30 days.)

You need to create a New Connection to the USB Modem’s Port in order to interact with it. Follow the below steps for it:

  1. Open Hyper terminal.
  2. Create a new connection.HyperNewConnection
  3. Select the Port to which the USB Device is connected. (In my case it is COM1)HyperterminalNew1
  4. Click Configure and set the Port properties.(Normally it is the same as shown in the screenshot below)HyperConfig
  5. After this try out the set of commands above to send SMS from the Terminal.

Here is a screenshot of the interface with Commands and responses.(Notice in the screenshot below, the first two commands are invisible and only the response “OK” can be seen. Only after typing the command “ATE1”, the commands are visible.)

Hyperterminal


Finally the C# CRM Plugin to send SMS 

In the above section, we tested the connection of the USB Device and sending SMSs using the Hyperterminal. Now we are ready to code it into a C# code.

Below is the sample plugin code to send SMS from CRM. Register the plugin assembly on any event and test it out.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel;

namespace SMSIntegrationModule
{

public class SMSIntegration: IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
#region SMS Integration Module
try
{
var port = new SerialPort();
port.NewLine = “\r\n”;
port.PortName = “COM1”;
port.BaudRate = 9600;
port.Parity = Parity.None;
port.DataBits = 8;
port.StopBits = StopBits.One;

port.Handshake = Handshake.RequestToSend;
port.Encoding = Encoding.GetEncoding(“iso-8859-1”);
port.WriteBufferSize = 500;
port.DtrEnable = true;
port.RtsEnable = true;

port.ReadTimeout = 1000;
port.WriteTimeout = 1000;

if (port.IsOpen)
port.Close();
port.Open();

IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService _service = serviceFactory.CreateOrganizationService(context.UserId);
if (context.InputParameters.Contains(“Target”) && context.InputParameters[“Target”] is Entity)
{
Entity entity = context.InputParameters[“Target”] as Entity;

port.WriteLine(“AT+CMGF=1”);
port.WriteLine(“AT+CSCS=” + ‘”‘ + “GSM” + ‘”‘);
port.WriteLine(“AT+CMGS=” + ‘”‘ + “+918867125456” + ‘”‘);
string msg = “Hi ” + entity[“new_customername”].ToString() + “, \n\nAccount Number:” + entity[“new_salesid”].ToString() + “.\nBill Number:” + entity[“new_itemid”].ToString() + “.\nCurrent Reading:” + entity[“new_currentreading”].ToString() + “.\nAmount:” + entity[“new_lineamount”].ToString() + “.\n\nThanks,\nElectricity Board.”;

port.Write(msg);
port.Write(Convert.ToChar(26).ToString());
port.Close();

#endregion
}
}
catch (Exception e)
{
var str = e.Message;
throw new InvalidPluginExecutionException(str);
}
}
}

}

Let me know your thoughts on it in the comments.

Have a great day! 🙂