Skip to content

Instantly share code, notes, and snippets.

@t2-support-gists
Created July 16, 2012 23:05
Show Gist options
  • Save t2-support-gists/3125649 to your computer and use it in GitHub Desktop.
Save t2-support-gists/3125649 to your computer and use it in GitHub Desktop.
SMS Csharp RESTFul App 1
******************************************************************************************
* Licensed by AT&T under 'Software Development Kit Tools Agreement.' 2013
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION: http://developer.att.com/sdk_agreement/
* Copyright 2013 AT&T Intellectual Property. All rights reserved. http://developer.att.com
* For more information contact developer.support@att.com<mailto:developer.support@att.com>
******************************************************************************************
AT&T API Platform Samples - SMS app 1
------------------------------
Application with a web interface that allows a user to send an SMS message, check
the delivery status of that SMS message, and check for received SMS messages.
This file describes how to set up, configure and run the C# Applications of the
AT&T API Platform sample applications. It covers all steps required to register the
application on DevConnect and, based on the generated API keys and secrets,
create and run one's own full-fledged sample applications.
1. Configuration
2. Installation
3. Parameters
4. Running the application
1. Configuration
Configuration consists of a few steps necessary to get an application registered
on DevConnect with the proper services and endpoints, depending on the type of
client-side application (autonomous/non-autonomous).
To register an application, go to https://devconnect-api.att.com/ and login with
your valid username and password. Next, choose "My Apps" from the bar at the top
of the page and click the "Setup a New Application" button.
Fill in the form, in particular all fields marked as "required".
Be careful while filling in the "OAuth Redirect URL" field. It should contain the
URL that the oAuth provider will redirect users to when he/she successfully
authenticates and authorizes your application.
NOTE: You MUST select SMS in the list of services under field 'Services' in order to
use this sample application code.
Having your application registered, you will get back an important pair of data:
an API key and Secret key. They are necessary to get your applications working with
the AT&T Platform APIs.
Initially your newly registered application is restricted to the "Sandbox"
environment only. To move it to production, you may promote it by clicking the
"Promote to production" button. Notice that you will get a different API key and
secret, so these values in your application should be adjusted accordingly.
Depending on the kind of authentication used, an application may be based on either
the Autonomous Client or the Web-Server Client OAuth flow (see
https://devconnect-api.att.com/docs/oauth20/autonomous-client-application-oauth-flow or
https://devconnect-api.att.com/docs/oauth20/web-server-client-application-oauth-flow
respectively).
2. Installation
** Requirements
To run the this sample application you need an IIS Server.
Download the application files from the download link published in AT&T portal
into webdomain of your IIS server.
3. Parameters
Each sample application contains an web.config file. This file
is located in the 'app' folder. This file holds configurable
parameters described in an easy-to-read format. Please modify the
web.config file using the comments specified within the file.
Note: If your application is promoted from Sandbox environment to Production
environment and you decide to use production application settings, you must
update parameters as per production application details.
4. Running the application
Suppose you copied the sample app files in your IIS server webroot/sms/app1/ folder.
In order to run the sample application, type in'http://IIS_HOSTNAME/sms/app1/Default.aspx'.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SMS_App1" %>
<!DOCTYPE html>
<!--
Licensed by AT&T under 'Software Development Kit Tools Agreement.' 2013
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION: http://developer.att.com/sdk_agreement/
Copyright 2013 AT&T Intellectual Property. All rights reserved. http://developer.att.com
For more information contact developer.support@att.com
-->
<!--[if lt IE 7]> <html class="ie6" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="ie7" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="ie8" lang="en"> <![endif]-->
<!--[if gt IE 8]><!-->
<html lang="en">
<head>
<title>AT&amp;T Sample Application - Basic SMS Service Application</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<meta id="viewport" name="viewport" content="width=device-width,minimum-scale=1,maximum-scale=1" />
<meta http-equiv="refresh" content="300" />
<link rel="stylesheet" type="text/css" href="style/common.css" />
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-33466541-1']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl'
: 'http://www')
+ '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
<script type="text/javascript" src="scripts/utils.js"></script>
</head>
<body onload="setup()">
<form id="form1" runat="server">
<div id="pageContainer">
<div id="header">
<div class="logo">
</div>
<div id="menuButton" class="hide">
<a id="jump" href="#nav">Main Navigation</a></div>
<ul class="links" id="nav">
<li><a href="#" target="_blank">Full Page<img alt="fullpage" src="images/max.png" /></a>
<span class="divider">|&nbsp;</span> </li>
<li><a runat="server" target="_blank" id="SourceLink">Source<img alt="source" src="images/opensource.png" /></a>
<span class="divider">|&nbsp;</span> </li>
<li><a runat="server" target="_blank" id="DownloadLink">Download<img alt="download"
src="images/download.png" /></a> <span class="divider">|&nbsp;</span> </li>
<li><a runat="server" target="_blank" id="HelpLink">Help</a> </li>
<li id="back"><a href="#top">Back to top</a></li>
</ul>
<!-- end of links -->
</div>
<!-- end of header -->
<div id="content">
<div id="contentHeading">
<h1>
AT&amp;T Sample Application - Basic SMS Service Application</h1>
<div class="border">
</div>
<div id="introtext">
<div>
<b>Server Time:&nbsp;</b><%= String.Format("{0:ddd, MMMM dd, yyyy HH:mm:ss}", DateTime.UtcNow) + " UTC" %></div>
<div>
<b>Client Time:</b>
<script language="JavaScript" type="text/javascript">
var myDate = new Date();
document.write(myDate);
</script>
</div>
<div>
<b>User Agent:</b>
<script language="JavaScript" type="text/javascript">
document.write("" + navigator.userAgent);
</script>
</div>
</div>
<!-- end of introtext -->
</div>
<!-- end of contentHeading -->
<div class="formBox" id="formBox">
<div id="formContainer" class="formContainer">
<div class="inputFields">
<div id="sendSMSdiv">
<h2>
Feature 1: Send SMS</h2>
<input placeholder="Address" name="address" id="address" type="text" runat="server" />
<label>
Message
<asp:DropDownList ID="message" runat="server" name="message">
</asp:DropDownList>
</label>
<label>
<asp:CheckBox ID="chkGetOnlineStatus" runat="server" ToolTip="If Checked, Delivery status is sent to the listener, use feature 3 to view the status" />
Receive Delivery Status Notification<br />
</label>
<button type="submit" class="submit" name="sendSMS" id="sendSMS" runat="server" onserverclick="BtnSubmit_Click">
Send SMS</button>
<% if (!string.IsNullOrEmpty(sendSMSSuccessMessage))
{ %>
<div class="successWide">
<strong>SUCCESS:</strong><br />
<strong>messageId: </strong>
<%= sendSMSResponseData.outBoundSMSResponse.messageId%>
<% if (sendSMSResponseData.outBoundSMSResponse.resourceReference != null)
{%>
<br />
<strong>resourceURL: </strong>
<%= sendSMSResponseData.outBoundSMSResponse.resourceReference.resourceURL%>
<%} %>
</div>
<% } %>
<% if (!string.IsNullOrEmpty(sendSMSErrorMessage))
{ %>
<div class="errorWide">
<strong>ERROR:</strong><br />
<%=sendSMSErrorMessage.ToString()%>
</div>
<% } %>
</div>
<!-- end of sendSMS -->
<div class="lightBorder">
</div>
<div id="getStatusdiv">
<h2>
Feature 2: Get Delivery Status</h2>
<input placeholder="Message ID" name="messageId" id="messageId" type="text" runat="server" />
<button type="submit" class="submit" name="getStatus" id="getStatus" runat="server"
onserverclick="GetDeliveryStatusButton_Click">
Get Status</button>
<% if (!string.IsNullOrEmpty(getSMSDeliveryStatusSuccessMessagae))
{ %>
<div class="successWide">
<strong>SUCCESS: </strong>
<br />
<strong>ResourceURL </strong>
<%=getSMSDeliveryStatusResponseData.DeliveryInfoList.ResourceURL%><br />
</div>
<table>
<thead>
<tr>
<th>
Id
</th>
<th>
Address
</th>
<th>
DeliveryStatus
</th>
</tr>
</thead>
<tbody>
<% foreach (DeliveryInfo delinfo in getSMSDeliveryStatusResponseData.DeliveryInfoList.DeliveryInfo)
{%>
<tr>
<td data-value="Id">
<%=delinfo.Id %>
</td>
<td data-value="Address">
<%= delinfo.Address %>
</td>
<td data-value="DeliveryStatus">
<%= delinfo.Deliverystatus %>
</td>
</tr>
<% }%>
</tbody>
</table>
<% } %>
<% if (!string.IsNullOrEmpty(getSMSDeliveryStatusErrorMessage))
{ %>
<div class="errorWide">
<strong>ERROR:</strong><br />
<%=getSMSDeliveryStatusErrorMessage.ToString()%>
</div>
<% } %>
</div>
<!-- end of getStatus -->
<div class="lightBorder">
</div>
<div id="receiveStatusdiv">
<h2>
Feature 3: Receive Delivery Status</h2>
<button type="submit" class="submit" name="receiveStatusBtn" id="receiveStatusBtn"
runat="server" onserverclick="receiveStatusBtn_Click">
Refresh Notifications</button>
<table>
<thead>
<tr>
<th>
messageId
</th>
<th>
address
</th>
<th>
deliveryStatus
</th>
</tr>
</thead>
<% if (receiveSMSDeliveryStatusResponseData != null && receiveSMSDeliveryStatusResponseData.Count > 0)
{ %>
<tbody>
<% foreach (deliveryInfoNotification deinfo in receiveSMSDeliveryStatusResponseData)
{ %>
<tr>
<td data-value="messageId">
<%=deinfo.messageId%>
</td>
<td data-value="address">
<%=deinfo.deliveryInfo.address%>
</td>
<td data-value="deliveryStatus">
<%=deinfo.deliveryInfo.deliveryStatus%>
</td>
</tr>
<%} %>
</tbody>
<% } %>
</table>
<br />
<% if (!string.IsNullOrEmpty(receiveSMSDeliveryStatusErrorMessage))
{ %>
<div class="errorWide">
<strong>ERROR:</strong><br />
<%=receiveSMSDeliveryStatusErrorMessage.ToString()%>
</div>
<% } %>
</div>
<!-- end of receiveStatus -->
<div class="lightBorder">
</div>
<div id="getMessagesDiv">
<h2>
Feature 4: Get Messages (<%= offlineShortCode%>)</h2>
<%if (!string.IsNullOrEmpty(offlineShortCode))
{%>
<button type="submit" runat="server" class="submit" name="getMessages" id="getMessages" onserverclick="GetMessagesButton_Click">
Get Messages</button>
<%} %>
<% if (getSMSResponseData != null)
{ %>
<div class="successWide">
<strong>SUCCESS:</strong><br />
<strong>Messages in this batch: </strong>
<%=getSMSResponseData.InboundSMSMessageList.NumberOfMessagesInThisBatch.ToString()%><br />
<strong>Messages pending: </strong>
<%= getSMSResponseData.InboundSMSMessageList.TotalNumberOfPendingMessages.ToString()%>
</div>
<br />
<table>
<thead>
<tr>
<th>
Message Index
</th>
<th>
Message Text
</th>
<th>
Sender Address
</th>
</tr>
</thead>
<tbody>
<% foreach (InboundSMSMessage msg in getSMSResponseData.InboundSMSMessageList.InboundSMSMessage)
{%>
<tr>
<td data-value="Message Index">
<%=msg.MessageId.ToString() %>
</td>
<td data-value="Message Text">
<%=msg.Message.ToString() %>
</td>
<td data-value="Sender Address">
<%=msg.SenderAddress.ToString() %>
</td>
</tr>
<%} %>
</tbody>
</table>
</div>
<% } %>
<% if (!string.IsNullOrEmpty(getSMSErrorMessage))
{ %>
<div class="errorWide">
<strong>ERROR:</strong><br />
<%=getSMSErrorMessage.ToString()%>
</div>
<% } %>
<!-- end of getMessages -->
<div class="lightBorder">
</div>
<div id="votes">
<h2>
Feature 5: Receive Messages (<%= onlineShortCode.ToString() %>)
</h2>
<button type="submit" class="submit" name="receiveMessages" id="receiveMessages"
runat="server" onserverclick="receiveMessagesBtn_Click">
Refresh Received Messages</button>
<table>
<thead>
<tr>
<th>
DateTime
</th>
<th>
SenderAddress
</th>
<th>
Message
</th>
<th>
DestinationAddress
</th>
<th>
MessageId
</th>
</tr>
</thead>
<% if (receivedSMSList != null && receivedSMSList.Count > 0)
{%>
<tbody>
<% foreach (ReceiveSMS msg in receivedSMSList)
{ %>
<tr>
<td data-value="DateTime">
<%=msg.DateTime.ToString() %>
</td>
<td data-value="SenderAddress">
<%=msg.SenderAddress.ToString() %>
</td>
<td data-value="Message">
<%=msg.Message.ToString() %>
</td>
<td data-value="DestinationAddress">
<%=msg.DestinationAddress.ToString() %>
</td>
<td data-value="MessageId">
<% var mid = "-"; if (!string.IsNullOrEmpty(msg.MessageId))
{
mid = msg.MessageId.ToString();
}%>
<%= mid.ToString() %>
</td>
</tr>
<%} %>
</tbody>
<% } %>
</table>
<% if (!string.IsNullOrEmpty(receiveSMSErrorMesssage))
{ %>
<div class="errorWide">
<strong>ERROR:</strong><br />
<%=receiveSMSErrorMesssage.ToString()%>
</div>
<% } %>
</div>
<!-- end of votes -->
</div>
<!-- end of inputFields -->
</div>
<!-- end of formContainer -->
</div>
<!-- end of formBox -->
</div>
<!-- end of content -->
<div class="border">
</div>
<div id="footer">
<div id="powered_by">
Powered by AT&amp;T Cloud Architecture</div>
<p>
The Application hosted on this site are working examples intended to be used for
reference in creating products to consume AT&amp;T Services and not meant to be
used as part of your product. The data in these pages is for test purposes only
and intended only for use as a reference in how the services perform.
<br />
<br />
For download of tools and documentation, please go to <a href="https://devconnect-api.att.com/"
target="_blank">https://devconnect-api.att.com</a>
<br />
For more information contact <a href="mailto:developer.support@att.com">developer.support@att.com</a>
<br />
<br />
&copy; 2013 AT&amp;T Intellectual Property. All rights reserved. <a href="http://developer.att.com/"
target="_blank">http://developer.att.com</a>
</p>
</div>
<!-- end of footer -->
</div>
<!-- end of page_container -->
</form>
<script type="text/javascript"> setup();</script>
</body>
</html>
// <copyright file="Default.aspx.cs" company="AT&amp;T">
// Licensed by AT&amp;T under 'Software Development Kit Tools Agreement.' 2013
// TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION: http://developer.att.com/sdk_agreement/
// Copyright 2013 AT&amp;T Intellectual Property. All rights reserved. http://developer.att.com
// For more information contact developer.support@att.com
// </copyright>
#region References
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Web.UI;
#endregion
/// <summary>
/// Default class
/// </summary>
public partial class SMS_App1 : System.Web.UI.Page
{
#region Variable Declaration
/// <summary>
/// Global Variables related to application
/// </summary>
private string endPoint, apiKey, secretKey, scope;
///<summary>
///API URL's
///</summary>
private string sendSMSURL = "/sms/v3/messaging/outbox";
private string getDeliveryStatusURL = "/sms/v3/messaging/outbox/";
private string getSMSURL = "/sms/v3/messaging/inbox";
/// <summary>
/// Global Variables related to access token
/// </summary>
private string accessTokenFilePath, accessToken, accessTokenExpiryTime,
refreshToken, refreshTokenExpiryTime;
private int refreshTokenExpiresIn;
/// <summary>
/// Variables related to Send SMS
/// </summary>
public string sendSMSErrorMessage = string.Empty;
public string sendSMSSuccessMessage = string.Empty;
public SendSMSResponse sendSMSResponseData = null;
/// <summary>
/// Variables related to Get Delivery Status
/// </summary>
public string getSMSDeliveryStatusErrorMessage = string.Empty;
public string getSMSDeliveryStatusSuccessMessagae = string.Empty;
public GetDeliveryStatus getSMSDeliveryStatusResponseData = null;
/// <summary>
/// Variables related to Get SMS
/// </summary>
public string getSMSSuccessMessage = string.Empty;
public string offlineShortCode = string.Empty;
public string getSMSErrorMessage = string.Empty;
public GetSmsResponse getSMSResponseData = null;
/// <summary>
/// Variables related to Receive SMS
/// </summary>
public string onlineShortCode = string.Empty;
public string receiveSMSSuccessMessage = string.Empty;
public string receiveSMSErrorMesssage = string.Empty;
public List<ReceiveSMS> receivedSMSList = new List<ReceiveSMS>();
public string receiveSMSFilePath = "\\Messages.txt";
/// <summary>
/// Variables related to Get Delivery Status
/// </summary>
public string receiveSMSDeliveryStatusErrorMessage = string.Empty;
public string receiveSMSDeliveryStatusSuccessMessagae = string.Empty;
public List<deliveryInfoNotification> receiveSMSDeliveryStatusResponseData = new List<deliveryInfoNotification>();
public string receiveSMSDeliveryStatusFilePath = "\\DeliveryStatus.txt";
/// <summary>
/// Access Token Types
/// </summary>
private enum AccessType
{
/// <summary>
/// Access Token Type is based on Client Credential Mode
/// </summary>
ClientCredential,
/// <summary>
/// Access Token Type is based on Refresh Token
/// </summary>
RefreshToken
}
#endregion
#region SMS Application Events
/// <summary>
/// This function is called when the applicaiton page is loaded into the browser.
/// This fucntion reads the web.config and gets the values of the attributes
/// </summary>
/// <param name="sender">Sender Details</param>
/// <param name="e">List of Arguments</param>
protected void Page_Load(object sender, EventArgs e)
{
try
{
BypassCertificateError();
bool ableToRead = this.ReadConfigFile();
if (ableToRead == false)
{
return;
}
if (Session["lastSentSMSID"] != null)
{
messageId.Value = Session["lastSentSMSID"].ToString();
}
//if (!IsPostBack)
//{
readOnlineMessages();
readOnlineDeliveryStatus();
//}
}
catch (Exception ex)
{
sendSMSErrorMessage = ex.ToString();
}
}
/// <summary>
/// Reads from config file
/// </summary>
/// <returns>true/false; true if able to read else false</returns>
private bool ReadConfigFile()
{
this.accessTokenFilePath = ConfigurationManager.AppSettings["AccessTokenFilePath"];
if (string.IsNullOrEmpty(this.accessTokenFilePath))
{
this.accessTokenFilePath = "~\\SMSApp1AccessToken.txt";
}
this.endPoint = ConfigurationManager.AppSettings["endPoint"];
if (string.IsNullOrEmpty(this.endPoint))
{
sendSMSErrorMessage= "endPoint is not defined in configuration file";
return false;
}
this.offlineShortCode = ConfigurationManager.AppSettings["OfflineShortCode"];
if (string.IsNullOrEmpty(this.offlineShortCode))
{
sendSMSErrorMessage= "short_code is not defined in configuration file";
return false;
}
this.apiKey = ConfigurationManager.AppSettings["api_key"];
if (string.IsNullOrEmpty(this.apiKey))
{
sendSMSErrorMessage= "api_key is not defined in configuration file";
return false;
}
this.secretKey = ConfigurationManager.AppSettings["secret_key"];
if (string.IsNullOrEmpty(this.secretKey))
{
sendSMSErrorMessage= "secret_key is not defined in configuration file";
return false;
}
this.scope = ConfigurationManager.AppSettings["scope"];
if (string.IsNullOrEmpty(this.scope))
{
this.scope = "SMS";
}
string refreshTokenExpires = ConfigurationManager.AppSettings["refreshTokenExpiresIn"];
if (!string.IsNullOrEmpty(refreshTokenExpires))
{
this.refreshTokenExpiresIn = Convert.ToInt32(refreshTokenExpires);
}
else
{
this.refreshTokenExpiresIn = 24; // Default value
}
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["SourceLink"]))
{
SourceLink.HRef = ConfigurationManager.AppSettings["SourceLink"];
}
else
{
SourceLink.HRef = "#"; // Default value
}
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["DownloadLink"]))
{
DownloadLink.HRef = ConfigurationManager.AppSettings["DownloadLink"];
}
else
{
DownloadLink.HRef = "#"; // Default value
}
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["HelpLink"]))
{
HelpLink.HRef = ConfigurationManager.AppSettings["HelpLink"];
}
else
{
HelpLink.HRef = "#"; // Default value
}
this.onlineShortCode = ConfigurationManager.AppSettings["OnlineShortCode"];
if (string.IsNullOrEmpty(this.onlineShortCode))
{
sendSMSErrorMessage = "Online ShortCode is not defined in configuration file";
return false;
}
this.sendSMSURL = ConfigurationManager.AppSettings["SendSMSURL"];
this.getDeliveryStatusURL = ConfigurationManager.AppSettings["GetDeliveryStatusURL"];
this.getSMSURL = ConfigurationManager.AppSettings["GetSMSURL"];
this.receiveSMSDeliveryStatusFilePath = ConfigurationManager.AppSettings["ReceivedDeliveryStatusFilePath"];
this.receiveSMSFilePath = ConfigurationManager.AppSettings["ReceivedMessagesFilePath"];
if (!IsPostBack)
{
string sampleMessages = ConfigurationManager.AppSettings["SMSSampleMessage"];
if (!string.IsNullOrEmpty(sampleMessages))
{
string[] sample = Regex.Split(sampleMessages, "_-_-");
foreach (string sm in sample)
{
message.Items.Add(sm);
}
}
else
{
message.Items.Add("ATT SMS sample Message");
}
}
return true;
}
/// <summary>
/// This function is called with user clicks on send SMS
/// This validates the access token and then calls sendSMS method to invoke send SMS API.
/// </summary>
/// <param name="sender">Sender Information</param>
/// <param name="e">List of Arguments</param>
protected void BtnSubmit_Click(object sender, EventArgs e)
{
try
{
if (this.ReadAndGetAccessToken(ref sendSMSErrorMessage) == true)
{
this.SendSms();
}
else
{
sendSMSErrorMessage = "Unable to get access token.";
}
}
catch (Exception ex)
{
sendSMSErrorMessage = ex.ToString();
}
}
/// <summary>
/// This method is called when user clicks on get message button
/// </summary>
/// <param name="sender">Sender Details</param>
/// <param name="e">List of Arguments</param>
protected void GetMessagesButton_Click(object sender, EventArgs e)
{
try
{
if (this.ReadAndGetAccessToken(ref getSMSErrorMessage) == true)
{
this.GetSms();
}
else
{
getSMSErrorMessage = "Unable to get access token.";
}
}
catch (Exception ex)
{
getSMSErrorMessage = ex.ToString();
}
}
#endregion
/// <summary>
/// This function is used to neglect the ssl handshake error with authentication server
/// </summary>
private static void BypassCertificateError()
{
ServicePointManager.ServerCertificateValidationCallback +=
delegate(object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
};
}
/// <summary>
/// This function calls receive sms api to fetch the sms's
/// </summary>
private void GetSms()
{
try
{
string receiveSmsResponseData;
if (string.IsNullOrEmpty(this.offlineShortCode))
{
getSMSErrorMessage = "Short code is null or empty";
return;
}
HttpWebRequest objRequest = (HttpWebRequest)System.Net.WebRequest.Create(string.Empty + this.endPoint + this.getSMSURL +"/" + this.offlineShortCode.ToString());
objRequest.Method = "GET";
objRequest.Headers.Add("Authorization", "BEARER " + this.accessToken);
HttpWebResponse receiveSmsResponseObject = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader receiveSmsResponseStream = new StreamReader(receiveSmsResponseObject.GetResponseStream()))
{
receiveSmsResponseData = receiveSmsResponseStream.ReadToEnd();
JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
getSMSResponseData = new GetSmsResponse();
getSMSResponseData = (GetSmsResponse)deserializeJsonObject.Deserialize(receiveSmsResponseData, typeof(GetSmsResponse));
receiveSmsResponseStream.Close();
}
}
catch (WebException we)
{
string errorResponse = string.Empty;
try
{
using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
{
errorResponse = sr2.ReadToEnd();
sr2.Close();
}
}
catch
{
errorResponse = "Unable to get response";
}
getSMSErrorMessage = errorResponse + Environment.NewLine + we.ToString();
}
catch (Exception ex)
{
getSMSErrorMessage = ex.ToString();
}
}
/// <summary>
/// Method will be called when the user clicks on Update Votes Total button
/// </summary>
/// <param name="sender">object, that invoked this method</param>
/// <param name="e">EventArgs, specific to this method</param>
protected void receiveStatusBtn_Click(object sender, EventArgs e)
{
try
{
//this.readOnlineDeliveryStatus();
}
catch (Exception ex)
{
receiveSMSErrorMesssage = ex.ToString();
}
}
/// <summary>
/// Method will be called when the user clicks on Update Votes Total button
/// </summary>
/// <param name="sender">object, that invoked this method</param>
/// <param name="e">EventArgs, specific to this method</param>
protected void receiveMessagesBtn_Click(object sender, EventArgs e)
{
try
{
//this.readOnlineMessages();
}
catch (Exception ex)
{
receiveSMSErrorMesssage = ex.ToString();
}
}
/// <summary>
/// This method reads the messages file and draw the table.
/// </summary>
private void readOnlineDeliveryStatus()
{
string receivedMessagesFile = ConfigurationManager.AppSettings["ReceivedDeliveryStatusFilePath"];
if (!string.IsNullOrEmpty(receivedMessagesFile))
receivedMessagesFile = Request.MapPath(receivedMessagesFile);
else
receivedMessagesFile = Request.MapPath("~\\DeliveryStatus.txt");
string messagesLine = String.Empty;
if (File.Exists(receivedMessagesFile))
{
using (StreamReader sr = new StreamReader(receivedMessagesFile))
{
while (sr.Peek() >= 0)
{
deliveryInfoNotification dNot = new deliveryInfoNotification();
dNot.deliveryInfo = new ReceiveDeliveryInfo();
messagesLine = sr.ReadLine();
string[] messageValues = Regex.Split(messagesLine, "_-_-");
dNot.messageId = messageValues[0];
dNot.deliveryInfo.address = messageValues[1];
dNot.deliveryInfo.deliveryStatus = messageValues[2];
receiveSMSDeliveryStatusResponseData.Add(dNot);
}
sr.Close();
receiveSMSDeliveryStatusResponseData.Reverse();
}
}
}
/// <summary>
/// This method reads the messages file and draw the table.
/// </summary>
private void readOnlineMessages()
{
string receivedMessagesFile = ConfigurationManager.AppSettings["ReceivedMessagesFilePath"];
if (!string.IsNullOrEmpty(receivedMessagesFile))
receivedMessagesFile = Request.MapPath(receivedMessagesFile);
else
receivedMessagesFile = Request.MapPath("~\\Messages.txt");
string messagesLine = String.Empty;
if (File.Exists(receivedMessagesFile))
{
using (StreamReader sr = new StreamReader(receivedMessagesFile))
{
while (sr.Peek() >= 0)
{
ReceiveSMS inboundMsg = new ReceiveSMS();
messagesLine = sr.ReadLine();
string[] messageValues = Regex.Split(messagesLine, "_-_-");
inboundMsg.DateTime = messageValues[0];
inboundMsg.MessageId = messageValues[1];
inboundMsg.Message = messageValues[2];
inboundMsg.SenderAddress = messageValues[3];
inboundMsg.DestinationAddress = messageValues[4];
receivedSMSList.Add(inboundMsg);
}
sr.Close();
receivedSMSList.Reverse();
}
}
}
/// <summary>
/// This function reads the Access Token File and stores the values of access token, expiry seconds
/// refresh token, last access token time and refresh token expiry time
/// This funciton returns true, if access token file and all others attributes read successfully otherwise returns false
/// </summary>
/// <param name="panelParam">Panel Details</param>
/// <returns>Returns boolean</returns>
private bool ReadAccessTokenFile(ref string message)
{
FileStream fileStream = null;
StreamReader streamReader = null;
try
{
fileStream = new FileStream(Request.MapPath(this.accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Read);
streamReader = new StreamReader(fileStream);
this.accessToken = streamReader.ReadLine();
this.accessTokenExpiryTime = streamReader.ReadLine();
this.refreshToken = streamReader.ReadLine();
this.refreshTokenExpiryTime = streamReader.ReadLine();
}
catch (Exception ex)
{
message= ex.Message;
return false;
}
finally
{
if (null != streamReader)
{
streamReader.Close();
}
if (null != fileStream)
{
fileStream.Close();
}
}
if ((this.accessToken == null) || (this.accessTokenExpiryTime == null) || (this.refreshToken == null) || (this.refreshTokenExpiryTime == null))
{
return false;
}
return true;
}
/// <summary>
/// This function validates the expiry of the access token and refresh token,
/// function compares the current time with the refresh token taken time, if current time is greater then
/// returns INVALID_REFRESH_TOKEN
/// function compares the difference of last access token taken time and the current time with the expiry seconds, if its more,
/// funciton returns INVALID_ACCESS_TOKEN
/// otherwise returns VALID_ACCESS_TOKEN
/// </summary>
/// <returns>Return String</returns>
private string IsTokenValid()
{
try
{
DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();
if (currentServerTime >= DateTime.Parse(this.accessTokenExpiryTime))
{
if (currentServerTime >= DateTime.Parse(this.refreshTokenExpiryTime))
{
return "INVALID_ACCESS_TOKEN";
}
else
{
return "REFRESH_TOKEN";
}
}
else
{
return "VALID_ACCESS_TOKEN";
}
}
catch
{
return "INVALID_ACCESS_TOKEN";
}
}
/// <summary>
/// This function is used to read access token file and validate the access token
/// this function returns true if access token is valid, or else false is returned
/// </summary>
/// <param name="panelParam">Panel Details</param>
/// <returns>Returns Boolean</returns>
private bool ReadAndGetAccessToken(ref string responseString)
{
bool result = true;
if (this.ReadAccessTokenFile(ref responseString) == false)
{
result = this.GetAccessToken(AccessType.ClientCredential, ref responseString);
}
else
{
string tokenValidity = this.IsTokenValid();
if (tokenValidity == "REFRESH_TOKEN")
{
result = this.GetAccessToken(AccessType.RefreshToken, ref responseString);
}
else if (string.Compare(tokenValidity, "INVALID_ACCESS_TOKEN") == 0)
{
result = this.GetAccessToken(AccessType.ClientCredential, ref responseString);
}
}
if (this.accessToken == null || this.accessToken.Length <= 0)
{
return false;
}
else
{
return result;
}
}
/// <summary>
/// This function get the access token based on the type parameter type values.
/// If type value is 1, access token is fetch for client credential flow
/// If type value is 2, access token is fetch for client credential flow based on the exisiting refresh token
/// </summary>
/// <param name="type">Type as integer</param>
/// <param name="panelParam">Panel details</param>
/// <returns>Return boolean</returns>
private bool GetAccessToken(AccessType type, ref string message)
{
FileStream fileStream = null;
Stream postStream = null;
StreamWriter streamWriter = null;
// This is client credential flow
if (type == AccessType.ClientCredential)
{
try
{
DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();
WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create(string.Empty + this.endPoint + "/oauth/token");
accessTokenRequest.Method = "POST";
string oauthParameters = string.Empty;
if (type == AccessType.ClientCredential)
{
oauthParameters = "client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&grant_type=client_credentials&scope=" + this.scope;
}
else
{
oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken;
}
accessTokenRequest.ContentType = "application/x-www-form-urlencoded";
UTF8Encoding encoding = new UTF8Encoding();
byte[] postBytes = encoding.GetBytes(oauthParameters);
accessTokenRequest.ContentLength = postBytes.Length;
postStream = accessTokenRequest.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
WebResponse accessTokenResponse = accessTokenRequest.GetResponse();
using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream()))
{
string jsonAccessToken = accessTokenResponseStream.ReadToEnd().ToString();
JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
AccessTokenResponse deserializedJsonObj = (AccessTokenResponse)deserializeJsonObject.Deserialize(jsonAccessToken, typeof(AccessTokenResponse));
this.accessToken = deserializedJsonObj.access_token;
this.accessTokenExpiryTime = currentServerTime.AddSeconds(Convert.ToDouble(deserializedJsonObj.expires_in)).ToString();
this.refreshToken = deserializedJsonObj.refresh_token;
DateTime refreshExpiry = currentServerTime.AddHours(this.refreshTokenExpiresIn);
if (deserializedJsonObj.expires_in.Equals("0"))
{
int defaultAccessTokenExpiresIn = 100; // In Yearsint yearsToAdd = 100;
this.accessTokenExpiryTime = currentServerTime.AddYears(defaultAccessTokenExpiresIn).ToLongDateString() + " " + currentServerTime.AddYears(defaultAccessTokenExpiresIn).ToLongTimeString();
}
this.refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString();
fileStream = new FileStream(Request.MapPath(this.accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Write);
streamWriter = new StreamWriter(fileStream);
streamWriter.WriteLine(this.accessToken);
streamWriter.WriteLine(this.accessTokenExpiryTime);
streamWriter.WriteLine(this.refreshToken);
streamWriter.WriteLine(this.refreshTokenExpiryTime);
// Close and clean up the StreamReader
accessTokenResponseStream.Close();
return true;
}
}
catch (WebException we)
{
string errorResponse = string.Empty;
try
{
using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
{
errorResponse = sr2.ReadToEnd();
sr2.Close();
}
}
catch
{
errorResponse = "Unable to get response";
}
message = errorResponse + Environment.NewLine + we.ToString();
}
catch (Exception ex)
{
message = ex.Message;
return false;
}
finally
{
if (null != postStream)
{
postStream.Close();
}
if (null != streamWriter)
{
streamWriter.Close();
}
if (null != fileStream)
{
fileStream.Close();
}
}
}
else if (type == AccessType.RefreshToken)
{
try
{
DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();
WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create(string.Empty + this.endPoint + "/oauth/token");
accessTokenRequest.Method = "POST";
string oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken;
accessTokenRequest.ContentType = "application/x-www-form-urlencoded";
UTF8Encoding encoding = new UTF8Encoding();
byte[] postBytes = encoding.GetBytes(oauthParameters);
accessTokenRequest.ContentLength = postBytes.Length;
postStream = accessTokenRequest.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
WebResponse accessTokenResponse = accessTokenRequest.GetResponse();
using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream()))
{
string accessTokenJSon = accessTokenResponseStream.ReadToEnd().ToString();
JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
AccessTokenResponse deserializedJsonObj = (AccessTokenResponse)deserializeJsonObject.Deserialize(accessTokenJSon, typeof(AccessTokenResponse));
this.accessToken = deserializedJsonObj.access_token.ToString();
DateTime accessTokenExpiryTime = currentServerTime.AddMilliseconds(Convert.ToDouble(deserializedJsonObj.expires_in.ToString()));
this.refreshToken = deserializedJsonObj.refresh_token.ToString();
fileStream = new FileStream(Request.MapPath(this.accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Write);
streamWriter = new StreamWriter(fileStream);
streamWriter.WriteLine(this.accessToken);
streamWriter.WriteLine(this.accessTokenExpiryTime);
streamWriter.WriteLine(this.refreshToken);
// Refresh token valids for 24 hours
DateTime refreshExpiry = currentServerTime.AddHours(24);
this.refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString();
streamWriter.WriteLine(refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString());
accessTokenResponseStream.Close();
return true;
}
}
catch (WebException we)
{
string errorResponse = string.Empty;
try
{
using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
{
errorResponse = sr2.ReadToEnd();
sr2.Close();
}
}
catch
{
errorResponse = "Unable to get response";
}
message = errorResponse + Environment.NewLine + we.ToString();
}
catch (Exception ex)
{
message = ex.Message;
return false;
}
finally
{
if (null != postStream)
{
postStream.Close();
}
if (null != streamWriter)
{
streamWriter.Close();
}
if (null != fileStream)
{
fileStream.Close();
}
}
}
return false;
}
/// <summary>
/// This function validates the input fields and if they are valid send sms api is invoked
/// </summary>
private void SendSms()
{
try
{
string outBoundSmsJson = string.Empty;
List<string> destinationNumbers = new List<string>();
if (!string.IsNullOrEmpty(address.Value))
{
string addressInput = address.Value;
string[] multipleAddresses = addressInput.Split(',');
foreach (string addr in multipleAddresses)
{
if (addr.StartsWith("tel:"))
{
destinationNumbers.Add(addr);
}
else
{
string phoneNumberWithTel = "tel:" + addr;
destinationNumbers.Add(phoneNumberWithTel);
}
}
if (multipleAddresses.Length == 1)
{
SendSMSDataForSingle outBoundSms = new SendSMSDataForSingle();
outBoundSms.outboundSMSRequest = new OutboundSMSRequestForSingle();
outBoundSms.outboundSMSRequest.notifyDeliveryStatus = chkGetOnlineStatus.Checked;
outBoundSms.outboundSMSRequest.address = destinationNumbers[0];
outBoundSms.outboundSMSRequest.message = message.SelectedValue;
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
outBoundSmsJson = javaScriptSerializer.Serialize(outBoundSms);
}
else
{
SendSMSDataForMultiple outBoundSms = new SendSMSDataForMultiple();
outBoundSms.outboundSMSRequest = new OutboundSMSRequestForMultiple();
outBoundSms.outboundSMSRequest.notifyDeliveryStatus = chkGetOnlineStatus.Checked;
outBoundSms.outboundSMSRequest.address = destinationNumbers;
outBoundSms.outboundSMSRequest.message = message.SelectedValue;
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
outBoundSmsJson = javaScriptSerializer.Serialize(outBoundSms);
}
}
else
{
sendSMSErrorMessage = "No input provided for Address";
return;
}
string sendSmsResponseData;
HttpWebRequest sendSmsRequestObject = (HttpWebRequest)System.Net.WebRequest.Create(string.Empty + this.endPoint + this.sendSMSURL);
sendSmsRequestObject.Method = "POST";
sendSmsRequestObject.Headers.Add("Authorization", "Bearer " + this.accessToken);
sendSmsRequestObject.ContentType = "application/json";
sendSmsRequestObject.Accept = "application/json";
UTF8Encoding encoding = new UTF8Encoding();
byte[] postBytes = encoding.GetBytes(outBoundSmsJson);
sendSmsRequestObject.ContentLength = postBytes.Length;
Stream postStream = sendSmsRequestObject.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
HttpWebResponse sendSmsResponseObject = (HttpWebResponse)sendSmsRequestObject.GetResponse();
using (StreamReader sendSmsResponseStream = new StreamReader(sendSmsResponseObject.GetResponseStream()))
{
sendSmsResponseData = sendSmsResponseStream.ReadToEnd();
JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
sendSMSResponseData = new SendSMSResponse();
sendSMSResponseData.outBoundSMSResponse = new OutBoundSMSResponse();
sendSMSResponseData = (SendSMSResponse)deserializeJsonObject.Deserialize(sendSmsResponseData, typeof(SendSMSResponse));
if (!chkGetOnlineStatus.Checked)
{
Session["lastSentSMSID"] = sendSMSResponseData.outBoundSMSResponse.messageId;
messageId.Value = Session["lastSentSMSID"].ToString();
}
sendSMSSuccessMessage = "Success";
sendSmsResponseStream.Close();
}
}
catch (WebException we)
{
string errorResponse = string.Empty;
try
{
using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
{
errorResponse = sr2.ReadToEnd();
sr2.Close();
}
}
catch
{
errorResponse = "Unable to get response";
}
sendSMSErrorMessage= errorResponse;
}
catch (Exception ex)
{
sendSMSErrorMessage = ex.ToString();
}
}
#region Get SMS Delivery Status code.
/// <summary>
/// This method is called when user clicks on get delivery status button
/// </summary>
/// <param name="sender">Sender Information</param>
/// <param name="e">List of Arguments</param>
protected void GetDeliveryStatusButton_Click(object sender, EventArgs e)
{
try
{
Session["lastSentSMSID"] = System.Web.HttpUtility.HtmlEncode(messageId.Value);
if (this.ReadAndGetAccessToken(ref getSMSDeliveryStatusErrorMessage) == true)
{
this.GetSmsDeliveryStatus();
}
else
{
getSMSDeliveryStatusErrorMessage = "Unable to get access token.";
}
}
catch (Exception ex)
{
getSMSDeliveryStatusErrorMessage = ex.ToString();
}
}
/// <summary>
/// This function is called when user clicks on get delivery status button.
/// this funciton calls get sms delivery status API to fetch the status.
/// </summary>
private void GetSmsDeliveryStatus()
{
try
{
string getSmsDeliveryStatusResponseData;
HttpWebRequest getSmsDeliveryStatusRequestObject = (HttpWebRequest)System.Net.WebRequest.Create(string.Empty + this.endPoint + this.getDeliveryStatusURL + messageId.Value);
getSmsDeliveryStatusRequestObject.Method = "GET";
getSmsDeliveryStatusRequestObject.Headers.Add("Authorization", "BEARER " + this.accessToken);
getSmsDeliveryStatusRequestObject.ContentType = "application/JSON";
getSmsDeliveryStatusRequestObject.Accept = "application/json";
HttpWebResponse getSmsDeliveryStatusResponse = (HttpWebResponse)getSmsDeliveryStatusRequestObject.GetResponse();
using (StreamReader getSmsDeliveryStatusResponseStream = new StreamReader(getSmsDeliveryStatusResponse.GetResponseStream()))
{
getSmsDeliveryStatusResponseData = getSmsDeliveryStatusResponseStream.ReadToEnd();
getSmsDeliveryStatusResponseData = getSmsDeliveryStatusResponseData.Replace("-", string.Empty);
JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
getSMSDeliveryStatusResponseData = new GetDeliveryStatus();
getSMSDeliveryStatusResponseData = (GetDeliveryStatus)deserializeJsonObject.Deserialize(getSmsDeliveryStatusResponseData, typeof(GetDeliveryStatus));
getSMSDeliveryStatusSuccessMessagae = "Success";
getSmsDeliveryStatusResponseStream.Close();
}
}
catch (WebException we)
{
string errorResponse = string.Empty;
try
{
using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
{
errorResponse = sr2.ReadToEnd();
sr2.Close();
}
}
catch
{
errorResponse = "Unable to get response";
}
getSMSDeliveryStatusErrorMessage = errorResponse ;
}
catch (Exception ex)
{
getSMSDeliveryStatusErrorMessage = ex.ToString();
}
}
#endregion
#region SMS Application related Data Structures
#region Data structure for get access token
/// <summary>
/// Class to hold access token response
/// </summary>
public class AccessTokenResponse
{
/// <summary>
/// Gets or sets access token
/// </summary>
public string access_token { get; set; }
/// <summary>
/// Gets or sets refresh token
/// </summary>
public string refresh_token { get; set; }
/// <summary>
/// Gets or sets expires in
/// </summary>
public string expires_in { get; set; }
}
#endregion
#region Data structure for send sms response
///<summary>
///Class to hold ResourceReference
///</summary>
public class ResourceReference
{
///<summary>
///Gets or sets resourceURL
///</summary>
public string resourceURL { get; set; }
}
public class SendSMSResponse
{
public OutBoundSMSResponse outBoundSMSResponse;
}
/// <summary>
/// Class to hold send sms response
/// </summary>
public class OutBoundSMSResponse
{
/// <summary>
/// Gets or sets messageId
/// </summary>
public string messageId { get; set; }
/// <summary>
/// Gets or sets ResourceReference
/// </summary>
public ResourceReference resourceReference { get; set; }
}
public class SendSMSDataForSingle
{
public OutboundSMSRequestForSingle outboundSMSRequest { get; set; }
}
public class OutboundSMSRequestForSingle
{
/// <summary>
/// Gets or sets the address to send.
/// </summary>
public string address
{
get;
set;
}
/// <summary>
/// Gets or sets message text to send.
/// </summary>
public string message
{
get;
set;
}
public bool notifyDeliveryStatus
{
get;
set;
}
}
public class SendSMSDataForMultiple
{
public OutboundSMSRequestForMultiple outboundSMSRequest { get; set; }
}
public class OutboundSMSRequestForMultiple
{
/// <summary>
/// Gets or sets the list of address to send.
/// </summary>
public List<string> address
{
get;
set;
}
/// <summary>
/// Gets or sets message text to send.
/// </summary>
public string message
{
get;
set;
}
public bool notifyDeliveryStatus
{
get;
set;
}
}
#endregion
#region Data structure for Get SMS (offline)
/// <summary>
/// Class to hold rececive sms response
/// </summary>
public class GetSmsResponse
{
/// <summary>
/// Gets or sets inbound sms message list
/// </summary>
public InboundSMSMessageList InboundSMSMessageList { get; set; }
}
/// <summary>
/// Class to hold inbound sms message list
/// </summary>
public class InboundSMSMessageList
{
/// <summary>
/// Gets or sets inbound sms message
/// </summary>
public List<InboundSMSMessage> InboundSMSMessage { get; set; }
/// <summary>
/// Gets or sets number of messages in a batch
/// </summary>
public int NumberOfMessagesInThisBatch { get; set; }
/// <summary>
/// Gets or sets resource url
/// </summary>
public string ResourceURL { get; set; }
/// <summary>
/// Gets or sets total number of pending messages
/// </summary>
public int TotalNumberOfPendingMessages { get; set; }
}
/// <summary>
/// Class to hold inbound sms message
/// </summary>
public class InboundSMSMessage
{
/// <summary>
/// Gets or sets message id
/// </summary>
public string MessageId { get; set; }
/// <summary>
/// Gets or sets message
/// </summary>
public string Message { get; set; }
/// <summary>
/// Gets or sets sender address
/// </summary>
public string SenderAddress { get; set; }
}
#endregion
#region Data structure for Receive SMS (online)
/// <summary>
/// Class to hold inbound sms message
/// </summary>
public class ReceiveSMS
{
/// <summary>
/// Gets or sets datetime
/// </summary>
public string DateTime { get; set; }
/// <summary>
/// Gets or sets destination address
/// </summary>
public string DestinationAddress { get; set; }
/// <summary>
/// Gets or sets message id
/// </summary>
public string MessageId { get; set; }
/// <summary>
/// Gets or sets message
/// </summary>
public string Message { get; set; }
/// <summary>
/// Gets or sets sender address
/// </summary>
public string SenderAddress { get; set; }
}
#endregion
#region Data structure for Get Delivery Status (offline)
/// <summary>
/// Class to hold delivery status
/// </summary>
public class GetDeliveryStatus
{
/// <summary>
/// Gets or sets delivery info list
/// </summary>
public DeliveryInfoList DeliveryInfoList { get; set; }
}
/// <summary>
/// Class to hold delivery info list
/// </summary>
public class DeliveryInfoList
{
/// <summary>
/// Gets or sets resource url
/// </summary>
public string ResourceURL { get; set; }
/// <summary>
/// Gets or sets delivery info
/// </summary>
public List<DeliveryInfo> DeliveryInfo { get; set; }
}
/// <summary>
/// Class to hold delivery info
/// </summary>
public class DeliveryInfo
{
/// <summary>
/// Gets or sets id
/// </summary>
public string Id { get; set; }
/// <summary>
/// Gets or sets address
/// </summary>
public string Address { get; set; }
/// <summary>
/// Gets or sets delivery status
/// </summary>
public string Deliverystatus { get; set; }
}
#endregion
#region Data structure for receive delivery status
public class ReceiveDeliveryInfo
{
/// <summary>
/// Gets or sets the list of address.
/// </summary>
public string address
{
get;
set;
}
/// <summary>
/// Gets or sets the list of deliveryStatus.
/// </summary>
public string deliveryStatus
{
get;
set;
}
}
public class deliveryInfoNotification
{
/// <summary>
/// Gets or sets the list of messageId.
/// </summary>
public string messageId
{
get;
set;
}
/// <summary>
/// Gets or sets message text to send.
/// </summary>
public ReceiveDeliveryInfo deliveryInfo
{
get;
set;
}
}
#endregion
#endregion
}
<!--
Licensed by AT&T under 'Software Development Kit Tools Agreement.' 2013
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION: http://developer.att.com/sdk_agreement/
Copyright 2013 AT&T Intellectual Property. All rights reserved. http://developer.att.com
For more information contact developer.support@att.com
-->
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Listener.aspx.cs" Inherits="Listener" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
// <copyright file="Listener.aspx.cs" company="AT&amp;T">
// Licensed by AT&amp;T under 'Software Development Kit Tools Agreement.' 2013
// TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION: http://developer.att.com/sdk_agreement/
// Copyright 2013 AT&amp;T Intellectual Property. All rights reserved. http://developer.att.com
// For more information contact developer.support@att.com
// </copyright>
#region References
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
#endregion
/// <summary>
/// Listener class for saving message counts.
/// </summary>
public partial class Listener : System.Web.UI.Page
{
#region variables
public string receivedMessagesFilePath = string.Empty;
public int numberOfMessagesToStore = 0;
#endregion
#region Events
/// <summary>
/// This method called when the page is loaded into the browser. This method requests input stream and parses it to get message counts.
/// </summary>
/// <param name="sender">object, which invoked this method</param>
/// <param name="e">EventArgs, which specifies arguments specific to this method</param>
protected void Page_Load(object sender, EventArgs e)
{
System.IO.Stream stream = Request.InputStream;
this.receivedMessagesFilePath = ConfigurationManager.AppSettings["ReceivedMessagesFilePath"];
if (string.IsNullOrEmpty(this.receivedMessagesFilePath))
this.receivedMessagesFilePath = "~\\Messages.txt";
string count = ConfigurationManager.AppSettings["NumberOfMessagesToStore"];
if (!string.IsNullOrEmpty(count))
this.numberOfMessagesToStore = Convert.ToInt32(count);
if (null != stream)
{
byte[] bytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(bytes, 0, (int)stream.Length);
string responseData = Encoding.ASCII.GetString(bytes);
JavaScriptSerializer serializeObject = new JavaScriptSerializer();
InboundSMSMessage message = (InboundSMSMessage)serializeObject.Deserialize(responseData, typeof(InboundSMSMessage));
if (null != message)
{
this.SaveMessage(message);
}
}
}
#endregion
#region Method to store the received message to file
/// <summary>
/// This method reads the incoming message and stores the received message details.
/// </summary>
/// <param name="message">InboundSMSMessage, message received from Request</param>
private void SaveMessage(InboundSMSMessage message)
{
try
{
List<string> list = new List<string>();
FileStream file = new FileStream(Request.MapPath(this.receivedMessagesFilePath), FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(file);
string line;
while ((line = sr.ReadLine()) != null)
{
list.Add(line);
}
sr.Close();
file.Close();
if (list.Count > this.numberOfMessagesToStore)
{
int diff = list.Count - this.numberOfMessagesToStore;
list.RemoveRange(0, diff);
}
if (list.Count == this.numberOfMessagesToStore)
{
list.RemoveAt(0);
}
string messageLineToStore = message.DateTime.ToString() + "_-_-" +
message.MessageId.ToString() + "_-_-" +
message.Message.ToString() + "_-_-" +
message.SenderAddress.ToString() + "_-_-" +
message.DestinationAddress.ToString();
list.Add(messageLineToStore);
using (StreamWriter sw = File.CreateText(Request.MapPath(this.receivedMessagesFilePath)))
{
int tempCount = 0;
while (tempCount < list.Count)
{
string lineToWrite = list[tempCount];
sw.WriteLine(lineToWrite);
tempCount++;
}
sw.Close();
}
}
catch (Exception ex)
{
return;
}
}
#endregion
}
#region Message Structure
/// <summary>
/// Message structure received
/// </summary>
public class InboundSMSMessage
{
/// <summary>
/// Gets or sets the value of DateTime
/// </summary>
public string DateTime
{
get;
set;
}
/// <summary>
/// Gets or sets the value of MessageId
/// </summary>
public string MessageId
{
get;
set;
}
/// <summary>
/// Gets or sets the value of Message
/// </summary>
public string Message
{
get;
set;
}
/// <summary>
/// Gets or sets the value of SenderAddress
/// </summary>
public string SenderAddress
{
get;
set;
}
/// <summary>
/// Gets or sets the value of DestinationAddress
/// </summary>
public string DestinationAddress
{
get;
set;
}
}
#endregion
<!--
Licensed by AT&T under 'Software Development Kit Tools Agreement.' 2013
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION: http://developer.att.com/sdk_agreement/
Copyright 2013 AT&T Intellectual Property. All rights reserved. http://developer.att.com
For more information contact developer.support@att.com
-->
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="StatusListener.aspx.cs" Inherits="StatusListener" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
// <copyright file="Listener.aspx.cs" company="AT&amp;T">
// Licensed by AT&amp;T under 'Software Development Kit Tools Agreement.' 2013
// TERMS AND CONITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION: http://developer.att.com/sdk_agreement/
// Copyright 2013 AT&amp;T Intellectual Property. All rights reserved. http://developer.att.com
// For more information contact developer.support@att.com
// </copyright>
#region References
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
#endregion
/// <summary>
/// Listener class for saving message counts.
/// </summary>
public partial class StatusListener : System.Web.UI.Page
{
#region variables
public string receivedDeliveryStatusFilePath = string.Empty;
public int numberOfDeliveryStatusToStore = 0;
#endregion
#region Events
/// <summary>
/// This method called when the page is loaded into the browser. This method requests input stream and parses it to get message counts.
/// </summary>
/// <param name="sender">object, which invoked this method</param>
/// <param name="e">EventArgs, which specifies arguments specific to this method</param>
protected void Page_Load(object sender, EventArgs e)
{
System.IO.Stream stream = Request.InputStream;
this.receivedDeliveryStatusFilePath = ConfigurationManager.AppSettings["ReceivedDeliveryStatusFilePath"];
if (string.IsNullOrEmpty(this.receivedDeliveryStatusFilePath))
this.receivedDeliveryStatusFilePath = "~\\DeliveryStatus.txt";
string count = ConfigurationManager.AppSettings["NumberOfDeliveryStatusToStore"];
if (!string.IsNullOrEmpty(count))
this.numberOfDeliveryStatusToStore = Convert.ToInt32(count);
if (null != stream)
{
byte[] bytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(bytes, 0, (int)stream.Length);
string responseData = Encoding.ASCII.GetString(bytes);
JavaScriptSerializer serializeObject = new JavaScriptSerializer();
DeliveryStatusNotification message = (DeliveryStatusNotification)serializeObject.Deserialize(responseData, typeof(DeliveryStatusNotification));
if (null != message)
{
this.SaveMessage(message);
}
}
}
#endregion
#region Method to store the received message to file
/// <summary>
/// This method reads the incoming message and stores the received message details.
/// </summary>
/// <param name="message">InboundSMSMessage, message received from Request</param>
private void SaveMessage(DeliveryStatusNotification message)
{
try
{
List<string> list = new List<string>();
FileStream file = new FileStream(Request.MapPath(this.receivedDeliveryStatusFilePath), FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(file);
string line;
while ((line = sr.ReadLine()) != null)
{
list.Add(line);
}
sr.Close();
file.Close();
if (list.Count > this.numberOfDeliveryStatusToStore)
{
int diff = list.Count - this.numberOfDeliveryStatusToStore;
list.RemoveRange(0, diff);
}
if (list.Count == this.numberOfDeliveryStatusToStore)
{
list.RemoveAt(0);
}
string messageLineToStore = message.deliveryInfoNotification.messageId.ToString() + "_-_-" +
message.deliveryInfoNotification.deliveryInfo.address.ToString() + "_-_-" +
message.deliveryInfoNotification.deliveryInfo.deliveryStatus.ToString();
list.Add(messageLineToStore);
using (StreamWriter sw = File.CreateText(Request.MapPath(this.receivedDeliveryStatusFilePath)))
{
int tempCount = 0;
while (tempCount < list.Count)
{
string lineToWrite = list[tempCount];
sw.WriteLine(lineToWrite);
tempCount++;
}
sw.Close();
}
}
catch (Exception ex)
{
return;
}
}
#endregion
}
#region Data structure for receive delivery status
public class ReceiveDeliveryInfo
{
/// <summary>
/// Gets or sets the list of address.
/// </summary>
public string address
{
get;
set;
}
/// <summary>
/// Gets or sets the list of deliveryStatus.
/// </summary>
public string deliveryStatus
{
get;
set;
}
}
public class DeliveryInfoNotification
{
/// <summary>
/// Gets or sets the list of messageId.
/// </summary>
public string messageId
{
get;
set;
}
/// <summary>
/// Gets or sets message text to send.
/// </summary>
public ReceiveDeliveryInfo deliveryInfo
{
get;
set;
}
}
public class DeliveryStatusNotification
{
/// <summary>
/// Gets or sets the list of messageId.
/// </summary>
public DeliveryInfoNotification deliveryInfoNotification
{
get;
set;
}
}
#endregion
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<customErrors mode="Off"></customErrors>
</system.web>
<appSettings>
<!-- This is mandatory key and value should be equal
to SMS Service registered application 'API key'
example: value="edd036a37549f429ca6546474c0865c5c85" -->
<add key="api_key" value=""/>
<!-- This is mandatory key and value should be equal
to SMS Service registered application 'Secret key'
example: value="e0d0cc6a2dfs93627fe"-->
<add key="secret_key" value=""/>
<!-- This is mandatory key and value should be equal
to https://api.att.com for production environment -->
<add key="endPoint" value=""></add>
<!-- This is optional key, which points to the file path, and application uses this key's value to create/update
the file with access token information, so, make sure to give write access to the folder defined.
If the key is not defined, SMSApp1AccessToken.txt will be created at root folder, so, make sure to give
write access to the root folder
example: value="~\\SMSApp1.txt" -->
<add key="AccessTokenFilePath" value =""/>
<!-- This is optional key, which specifies the expiry time of refresh token in Hrs. Default value is 24Hrs.
example: value="24"-->
<add key="refreshTokenExpiresIn" value=""/>
<!-- This is mandatory key, the value of the this key is used to populate Messages drop down list.
The value of this key should contain list of messages values separated by _-_- -->
<add key="SMSSampleMessage" value=""/>
<!-- These are optional parameters and they are used to link the header-->
<add key="SourceLink" value=""/>
<add key="DownloadLink" value=""/>
<add key="HelpLink" value=""/>
<!-- This is mandatory key, which will specify the shortcode of the registered application
example: value="99999999"-->
<add key="OnlineShortCode" value =""/>
<!-- This is mandatory key, which will specify the shortcode of the registered application
example: value="99999999"-->
<add key="OfflineShortCode" value =""/>
<!-- This is mandatory key, which will point to the file, which is used by application to store
the received online delivery status messages.
example: value="~\\Status.txt"-->
<add key="ReceivedDeliveryStatusFilePath" value =""/>
<!-- This is mandatory key, which will point to the file, which is used by application to store
the received online messages.
example: value="~\\Messages.txt"-->
<add key="ReceivedMessagesFilePath" value =""/>
<!-- These are mandatory key and value, which defines API endpoints-->
<add key="SendSMSURL" value ="/sms/v3/messaging/outbox"/>
<!-- append message id at end-->
<add key="GetDeliveryStatusURL" value="/sms/v3/messaging/outbox/"/>
<!-- append short code as query parameter RegistrationID at end -->
<add key="GetSMSURL" value="/sms/v3/messaging/inbox"/>
<!-- This is optional parameter, these many records will be stored in file-->
<add key="NumberOfMessagesToStore" value="5"/>
<!-- This is optional parameter, these many records will be stored in file-->
<add key="NumberOfDeliveryStatusToStore" value="5"/>
</appSettings>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment