Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

.

  • Loading branch information...
commit df0ebd231a2d7db89bd0bf3712a91def44af2caa 1 parent 32be7d0
attdevsupport authored
Showing with 15,027 additions and 10,042 deletions.
  1. +181 −177 MMS/Csharp/app1/Default.aspx
  2. +985 −621 MMS/Csharp/app1/Default.aspx.cs
  3. +8 −15 MMS/Csharp/app1/README.txt
  4. +10 −11 MMS/Csharp/app1/Web.config
  5. +6 −6 MMS/Csharp/app1/style/common.css
  6. +149 −129 MMS/Csharp/app2/Default.aspx
  7. +889 −548 MMS/Csharp/app2/Default.aspx.cs
  8. +7 −14 MMS/Csharp/app2/README.txt
  9. +15 −10 MMS/Csharp/app2/Web.config
  10. +1 −0  MMS/Csharp/app2/coupon_info/message.txt
  11. +6 −6 MMS/Csharp/app2/style/common.css
  12. +78 −66 MMS/Csharp/app3/Default.aspx
  13. +140 −81 MMS/Csharp/app3/Default.aspx.cs
  14. +1 −1  MMS/Csharp/app3/Listener.aspx
  15. +72 −42 MMS/Csharp/app3/Listener.aspx.cs
  16. +9 −13 MMS/Csharp/app3/README.txt
  17. +2 −2 MMS/Csharp/app3/Web.config
  18. +6 −6 MMS/Csharp/app3/style/common.css
  19. +12 −8 MMS/Java/app1/MMS.jsp
  20. +11 −4 MMS/Java/app1/OauthStorage.jsp
  21. +7 −1 MMS/Java/app1/README.txt
  22. +7 −0 MMS/Java/app1/config.jsp
  23. +15 −4 MMS/Java/app1/getToken.jsp
  24. +14 −14 MMS/Java/app2/MMS2.jsp
  25. +4 −4 MMS/Java/app2/OauthStorage.jsp
  26. +14 −3 MMS/Java/app2/getToken.jsp
  27. +1 −3 MMS/Java/app2/phones.txt
  28. +5 −5 MMS/Java/app3/OauthStorage.jsp
  29. +2 −2 MMS/PHP/app1/config.php
  30. +47 −33 MMS/PHP/app1/index.php
  31. +1 −1  MMS/PHP/app2/README.txt
  32. +2 −2 MMS/PHP/app2/config.php
  33. +41 −27 MMS/PHP/app2/index.php
  34. +2 −2 MMS/PHP/app3/config.php
  35. +4 −4 MMS/PHP/app3/index.php
  36. +7 −17 MMS/Ruby/app1/common.rb
  37. +11 −5 MMS/Ruby/app1/mms.rb
  38. +13 −8 MMS/Ruby/app1/views/mms.erb
  39. +19 −22 MMS/Ruby/app2/mms2.rb
  40. +1 −3 MMS/Ruby/app2/phones.txt
  41. +12 −6 MMS/Ruby/app2/views/mms2.erb
  42. +6 −0 MMS/Ruby/app3/mms3.rb
  43. +9 −3 MMS/Ruby/app3/views/mms3.erb
  44. +181 −174 MMS/Vb/app1/Default.aspx
  45. +865 −561 MMS/Vb/app1/Default.aspx.vb
  46. +7 −13 MMS/Vb/app1/README.txt
  47. +13 −12 MMS/Vb/app1/Web.config
  48. +6 −6 MMS/Vb/app1/style/common.css
  49. +149 −129 MMS/Vb/app2/Default.aspx
  50. +822 −502 MMS/Vb/app2/Default.aspx.vb
  51. +6 −12 MMS/Vb/app2/README.txt
  52. +16 −11 MMS/Vb/app2/Web.config
  53. BIN  MMS/Vb/app2/coupon_info/coupon.jpg
  54. +1 −1  MMS/Vb/app2/coupon_info/message.txt
  55. +0 −2  MMS/Vb/app2/coupon_info/phone.txt
  56. +6 −6 MMS/Vb/app2/style/common.css
  57. +78 −66 MMS/Vb/app3/Default.aspx
  58. +173 −121 MMS/Vb/app3/Default.aspx.vb
  59. +3 −3 MMS/Vb/app3/Listener.aspx
  60. +71 −50 MMS/Vb/app3/Listener.aspx.vb
  61. +6 −12 MMS/Vb/app3/README.txt
  62. +2 −2 MMS/Vb/app3/Web.config
  63. +6 −6 MMS/Vb/app3/style/common.css
  64. +123 −105 Notary/Csharp/app1/Default.aspx
  65. +14 −1 Notary/Csharp/app1/Default.aspx.cs
  66. +6 −11 Notary/Csharp/app1/README.txt
  67. +14 −16 Notary/Csharp/app1/Web.config
  68. +6 −6 Notary/Csharp/app1/style/common.css
  69. +5 −5 Notary/Java/app1/notary.jsp
  70. +7 −0 Notary/PHP/app1/config.php
  71. +15 −18 Notary/PHP/app1/index.php
  72. +6 −0 Notary/Ruby/app1/notary.rb
  73. +9 −3 Notary/Ruby/app1/views/notary.erb
  74. +122 −105 Notary/Vb/app1/Default.aspx
  75. +58 −41 Notary/Vb/app1/Default.aspx.vb
  76. +6 −11 Notary/Vb/app1/README.txt
  77. +8 −6 Notary/Vb/app1/Web.config
  78. +6 −6 Notary/Vb/app1/style/common.css
  79. +206 −183 Payment/Csharp/app1/Default.aspx
  80. +1,175 −736 Payment/Csharp/app1/Default.aspx.cs
  81. +42 −29 Payment/Csharp/app1/README.txt
  82. +21 −6 Payment/Csharp/app1/Web.config
  83. +0 −1  Payment/Csharp/app1/refundFile.txt
  84. +6 −6 Payment/Csharp/app1/style/common.css
  85. +225 −190 Payment/Csharp/app2/Default.aspx
  86. +1,470 −770 Payment/Csharp/app2/Default.aspx.cs
  87. +44 −30 Payment/Csharp/app2/README.txt
  88. +35 −8 Payment/Csharp/app2/Web.config
  89. +6 −6 Payment/Csharp/app2/style/common.css
  90. +0 −1  Payment/Csharp/app2/subsDetailsFile.txt
  91. +0 −5 Payment/Csharp/app2/subsRefundFile.txt
  92. +12 −5 Payment/Java/app1/OauthStorage.jsp
  93. +9 −1 Payment/Java/app1/README.txt
  94. +10 −5 Payment/Java/app1/config.jsp
  95. +1 −1  Payment/Java/app1/getLatestNotifications.jsp
  96. +1 −1  Payment/Java/app1/getLatestTransactions.jsp
  97. +13 −6 Payment/Java/app1/getToken.jsp
  98. +6 −5 Payment/Java/app1/notary.jsp
  99. +128 −64 Payment/Java/app1/singlepay.jsp
  100. +5 −5 Payment/Java/app2/OauthStorage.jsp
  101. +5 −3 Payment/Java/app2/README.txt
  102. +0 −2  Payment/Java/app2/config.jsp
  103. +4 −4 Payment/Java/app2/getToken.jsp
  104. +6 −5 Payment/Java/app2/notary.jsp
  105. +110 −80 Payment/Java/app2/subscription.jsp
  106. +7 −0 Payment/PHP/app1/config.php
  107. +2 −2 Payment/PHP/app1/notary.php
  108. +236 −74 Payment/PHP/app1/singlepay.php
  109. +7 −0 Payment/PHP/app2/config.php
  110. +2 −2 Payment/PHP/app2/notary.php
  111. +337 −173 Payment/PHP/app2/subscription.php
  112. +27 −16 Payment/Ruby/app1/app1.rb
  113. +22 −21 Payment/Ruby/app1/public/css/common.css
  114. +303 −295 Payment/Ruby/app1/views/app1.erb
  115. +130 −72 Payment/Ruby/app2/app2.rb
  116. +2 −0  Payment/Ruby/app2/config.yml
  117. +22 −21 Payment/Ruby/app2/public/css/common.css
  118. +398 −504 Payment/Ruby/app2/views/app2.erb
  119. +206 −182 Payment/Vb/app1/Default.aspx
  120. +1,219 −781 Payment/Vb/app1/Default.aspx.vb
  121. +8 −8 Payment/Vb/app1/README.txt
  122. +22 −8 Payment/Vb/app1/Web.config
  123. +0 −1  Payment/Vb/app1/refundFile.txt
  124. +6 −6 Payment/Vb/app1/style/common.css
  125. +225 −191 Payment/Vb/app2/Default.aspx
  126. +1,422 −716 Payment/Vb/app2/Default.aspx.vb
  127. +36 −13 Payment/Vb/app2/Web.config
  128. +6 −6 Payment/Vb/app2/style/common.css
  129. +0 −1  Payment/Vb/app2/subsDetailsFile.txt
  130. +0 −1  Payment/Vb/app2/subsRefundFile.txt
  131. +182 −180 SMS/Csharp/app1/Default.aspx
  132. +851 −511 SMS/Csharp/app1/Default.aspx.cs
  133. +6 −12 SMS/Csharp/app1/README.txt
  134. +13 −7 SMS/Csharp/app1/Web.config
  135. +6 −6 SMS/Csharp/app1/style/common.css
  136. +136 −122 SMS/Csharp/app2/Default.aspx
Sorry, we could not display the entire diff because it was too big.
View
358 MMS/Csharp/app1/Default.aspx
@@ -1,180 +1,184 @@
-<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
+<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="MMS_App1" %>
+
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
- <title>AT&T Sample MMS Application 1 &#8211; Basic MMS Service Application</title>
- <meta content="text/html; charset=ISO-8859-1" http-equiv="Content-Type"/>
- <link rel="stylesheet" type="text/css" href="../../style/common.css"/>
- <style type="text/css">
- .style1
- {
- font-style: normal;
- font-variant: normal;
- font-weight: bold;
- font-size: 12px;
- line-height: normal;
- font-family: Arial, Sans-serif;
- width: 92px;
- }
- </style>
- </head>
+<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en">
+<head>
+ <title>AT&T Sample MMS Application 1 &#8211; Basic MMS Service Application</title>
+ <link rel="stylesheet" type="text/css" href="style/common.css" />
+</head>
<body>
-<div id="container">
-<!-- open HEADER --><div id="header">
-<div>
- <div id="hcLeft">Server Time:</div>
- <div id="hcRight">
- <asp:Label ID="serverTimeLabel" runat="server" Text="Label"></asp:Label>
+ <form id="form1" runat="server">
+ <div id="container">
+ <!-- open HEADER -->
+ <div id="header">
+ <div>
+ <div class="hcLeft">
+ Server Time:</div>
+ <div class="hcRight">
+ <asp:Label ID="serverTimeLabel" runat="server" Text="Label"></asp:Label>
+ </div>
+ </div>
+ <div>
+ <div class="hcLeft">
+ Client Time:</div>
+ <div class="hcRight">
+ <script language="JavaScript" type="text/javascript">
+ var myDate = new Date();
+ document.write(myDate);
+ </script>
+ </div>
+ </div>
+ <div>
+ <div class="hcLeft">
+ User Agent:</div>
+ <div class="hcRight">
+ <script language="JavaScript" type="text/javascript">
+ document.write("" + navigator.userAgent);
+ </script>
+ </div>
+ </div>
+ <br clear="all" />
</div>
- </div>
-<div>
- <div id="hcLeft">Client Time:</div>
- <div id="hcRight">
- <script language="JavaScript" type="text/javascript">
- var myDate = new Date();
- document.write(myDate);
- </script>
- </div>
-</div>
-<div>
- <div id="hcLeft">User Agent:</div>
- <div id="hcRight">
- <script language="JavaScript" type="text/javascript">
- document.write("" + navigator.userAgent);
- </script>
- </div>
-</div>
-
-<br clear="all" />
-</div><!-- close HEADER -->
-
-<div id="wrapper">
-<div id="content">
-
-<h1>AT&T Sample MMS Application 1 – Basic MMS Service Application</h1>
-<h2>Feature 1: Send MMS Message</h2>
-
-</div>
-</div>
-
-<br clear="all" />
-<form id="form1" runat="server">
-<div id="navigation">
-
-<table border="0" width="100%">
- <tbody>
- <tr>
- <td width="20%" valign="top" class="label">Phone:</td>
- <td class="cell">
- <asp:TextBox ID="phoneTextBox" runat="server" Width="199px" MaxLength="16"></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td valign="top" class="label">Message:</td>
- <td class="cell">
- <asp:TextBox ID="messageTextBox" runat="server" Height="99px"
- TextMode="MultiLine" Width="291px"></asp:TextBox></td>
- </tr>
- </tbody>
-</table>
-
-</div>
-
-<div id="extraleft">
-<div class="warning" >
-<strong>WARNING:</strong><br />
-total size of all attachments cannot exceed 600 KB.
-</div>
-</div>
-<div id="extra">
-<table border="0" width="100%">
- <tbody>
- <tr>
- <td valign="bottom" class="style1">Attachment 1:</td>
- <td class="cell"><asp:FileUpload ID="FileUpload1" runat="server"/>
- </td>
- </tr>
- <tr>
- <td valign="bottom" class="style1">Attachment 2:</td>
- <td class="cell"><asp:FileUpload ID="FileUpload2" runat="server"/>
- </td>
- </tr>
- <tr>
- <td valign="bottom" class="style1">Attachment 3:</td>
- <td class="cell"><asp:FileUpload ID="FileUpload3" runat="server"/>
- </td>
- </tr>
- </tbody></table>
- <table>
- <tbody>
- <tr>
- <td>
- <asp:Button ID="sendMMSMessageButton" runat="server" Text="Send MMS Message"
- onclick="sendMMSMessageButton_Click" /></td>
- </tr>
- </tbody></table>
-</div>
-<br clear="all" />
-<div align="center">
- <asp:Panel ID="sendMessagePanel" runat="server" Font-Names="Calibri" Font-Size="XX-Small">
- </asp:Panel></div>
-<br clear="all" />
-
-<div id="wrapper">
-<div id="content">
-
-<h2><br />
-Feature 2: Get Delivery Status</h2>
-
-</div>
-</div>
-<div id="navigation">
-
-<table border="0" width="100%">
- <tbody>
- <tr>
- <td width="20%" valign="top" class="label">Message ID:</td>
- <td class="cell">
- <asp:TextBox ID="messageIDTextBox" runat="server" Width="233px"></asp:TextBox>
- </td>
- </tr>
- </tbody></table>
-
-</div>
-<div id="extra">
-
-<table border="0" width="100%">
- <tbody>
- <tr>
- <td class="cell">
- <asp:Button ID="getStatusButton" runat="server" Text="GetStatus"
- onclick="getStatusButton_Click" />
- </td>
- </tr>
- </tbody></table>
-
-</div>
-<br clear="all" />
-<div align="center">
- <asp:Panel ID="getStatusPanel" runat="server" Font-Names="Calibri" Font-Size="XX-Small">
- </asp:Panel>
-</div>
-<br clear="all" />
-
-
-
-
-<div id="footer">
-
- <div style="float: right; width: 20%; font-size: 9px; text-align: right">Powered by AT&amp;T Virtual Mobile</div>
- <p>© 2011 AT&amp;T Intellectual Property. All rights reserved. <a href="http://developer.att.com/" target="_blank">http://developer.att.com</a>
-<br>
-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>
-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>
-
-</div>
-</form>
-
-</body></html>
+ <!-- close HEADER -->
+ <div class="wrapper">
+ <div class="content">
+ <h1>
+ AT&T Sample MMS Application 1 – Basic MMS Service Application</h1>
+ <h2>
+ Feature 1: Send MMS Message</h2>
+ </div>
+ </div>
+ <br clear="all" />
+ <div class="navigation">
+ <table border="0" width="100%">
+ <tbody>
+ <tr>
+ <td width="20%" valign="top" class="label">
+ Phone:
+ </td>
+ <td class="cell">
+ <asp:TextBox ID="phoneTextBox" runat="server" Width="199px" MaxLength="16"></asp:TextBox>
+ </td>
+ </tr>
+ <tr>
+ <td valign="top" class="label">
+ Message:
+ </td>
+ <td class="cell">
+ <asp:TextBox ID="messageTextBox" runat="server" Height="99px" TextMode="MultiLine"
+ Width="291px"></asp:TextBox>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <div id="extraleft">
+ <div class="warning">
+ <strong>WARNING:</strong><br />
+ total size of all attachments cannot exceed 600 KB.
+ </div>
+ </div>
+ <div class="extra">
+ <table border="0" width="100%">
+ <tbody>
+ <tr>
+ <td valign="bottom" class="cell">
+ Attachment 1:
+ </td>
+ <td class="cell">
+ <asp:FileUpload ID="FileUpload1" runat="server" />
+ </td>
+ </tr>
+ <tr>
+ <td valign="bottom" class="cell">
+ Attachment 2:
+ </td>
+ <td class="cell">
+ <asp:FileUpload ID="FileUpload2" runat="server" />
+ </td>
+ </tr>
+ <tr>
+ <td valign="bottom" class="cell">
+ Attachment 3:
+ </td>
+ <td class="cell">
+ <asp:FileUpload ID="FileUpload3" runat="server" />
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ <table>
+ <tbody>
+ <tr>
+ <td>
+ <asp:Button ID="sendMMSMessageButton" runat="server" Text="Send MMS Message" OnClick="SendMMSMessageButton_Click" />
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <br clear="all" />
+ <div align="center">
+ <asp:Panel ID="sendMessagePanel" runat="server" Font-Names="Calibri" Font-Size="XX-Small">
+ </asp:Panel>
+ </div>
+ <br clear="all" />
+ <div class="wrapper">
+ <div class="content">
+ <h2>
+ <br />
+ Feature 2: Get Delivery Status</h2>
+ </div>
+ </div>
+ <div class="navigation">
+ <table border="0" width="100%">
+ <tbody>
+ <tr>
+ <td width="20%" valign="top" class="label">
+ Message ID:
+ </td>
+ <td class="cell">
+ <asp:TextBox ID="messageIDTextBox" runat="server" Width="233px"></asp:TextBox>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <div class="extra">
+ <table border="0" width="100%">
+ <tbody>
+ <tr>
+ <td class="cell">
+ <asp:Button ID="getStatusButton" runat="server" Text="Get Status" OnClick="GetStatusButton_Click" />
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <br clear="all" />
+ <div align="center">
+ <asp:Panel ID="getStatusPanel" runat="server" Font-Names="Calibri" Font-Size="XX-Small">
+ </asp:Panel>
+ </div>
+ <br clear="all" />
+ <div id="footer" align="center">
+ <div style="float: right; width: 20%; font-size: 9px; text-align: right">
+ Powered by AT&amp;T Cloud Architecture</div>
+ <p>
+ © 2012 AT&amp;T Intellectual Property. All rights reserved. <a href="http://developer.att.com/"
+ target="_blank">http://developer.att.com</a>
+ <br/>
+ 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/>
+ 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>
+ </div>
+ </div>
+ </form>
+</body>
+</html>
View
1,606 MMS/Csharp/app1/Default.aspx.cs
@@ -1,809 +1,1173 @@
-//Licensed by AT&T under 'Software Development Kit Tools Agreement.' September 2011
-//TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION: http://developer.att.com/sdk_agreement/
-//Copyright 2011 AT&T Intellectual Property. All rights reserved. http://developer.att.com
-//For more information contact developer.support@att.com
+// <copyright file="Default.aspx.cs" company="AT&amp;T">
+// Licensed by AT&amp;T under 'Software Development Kit Tools Agreement.' 2012
+// TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION: http://developer.att.com/sdk_agreement/
+// Copyright 2012 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.Linq;
-using System.Web;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Net;
-using System.IO;
-using System.Web.Services;
-using System.Text;
using System.Configuration;
-using System.Web.Script.Serialization;
using System.Drawing;
+using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
+using System.Text;
+using System.Web.Script.Serialization;
+using System.Web.UI.WebControls;
+
+#endregion
+
+/// <summary>
+/// Access Token Types
+/// </summary>
+public enum AccessTokenType
+{
+ /// <summary>
+ /// Access Token Type is based on Client Credential Mode
+ /// </summary>
+ Client_Credential,
+
+ /// <summary>
+ /// Access Token Type is based on Authorization Code
+ /// </summary>
+ Authorization_Code,
+
+ /// <summary>
+ /// Access Token Type is based on Refresh Token
+ /// </summary>
+ Refresh_Token
+}
-public partial class Default : System.Web.UI.Page
+/// <summary>
+/// MMS_App1 class
+/// </summary>
+/// <remarks> This application allows an end user to send an MMS message with up to three attachments of any common format,
+/// and check the delivery status of that MMS message.
+/// </remarks>
+public partial class MMS_App1 : System.Web.UI.Page
{
- string shortCode, FQDN, accessTokenFilePath, oauthFlow;
- string api_key, secret_key, auth_code, access_token, authorize_redirect_uri, scope, expiryMilliSeconds, refresh_token, lastTokenTakenTime, refreshTokenExpiryTime;
-
- /* 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
- */
- public bool readAccessTokenFile()
+ /// <summary>
+ /// Instance variables for local processing
+ /// </summary>
+ private string endPoint, accessTokenFilePath, apiKey, secretKey, accessToken, scope, refreshToken;
+
+ /// <summary>
+ /// Instance variables for local processing
+ /// </summary>
+ private string expirySeconds, refreshTokenExpiryTime;
+
+ /// <summary>
+ /// Instance variables for local processing
+ /// </summary>
+ private DateTime accessTokenExpiryTime;
+
+ /// <summary>
+ /// Gets or sets the value of refreshTokenExpiresIn
+ /// </summary>
+ private int refreshTokenExpiresIn;
+
+ #region Bypass SSL Certificate Error
+
+ /// <summary>
+ /// This method neglects the ssl handshake error with authentication server
+ /// </summary>
+ public static void BypassCertificateError()
+ {
+ ServicePointManager.ServerCertificateValidationCallback +=
+ delegate(Object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
+ {
+ return true;
+ };
+ }
+
+ #endregion
+
+ #region Page and Button Events
+
+ /// <summary>
+ /// Event, that triggers when the applicaiton page is loaded into the browser, reads the web.config and gets the values of the attributes
+ /// </summary>
+ /// <param name="sender">object, that caused this event</param>
+ /// <param name="e">Event that invoked this function</param>
+ protected void Page_Load(object sender, EventArgs e)
{
try
{
- FileStream file = new FileStream(Request.MapPath(accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Read);
- StreamReader sr = new StreamReader(file);
- access_token = sr.ReadLine();
- expiryMilliSeconds = sr.ReadLine();
- refresh_token = sr.ReadLine();
- lastTokenTakenTime = sr.ReadLine();
- refreshTokenExpiryTime = sr.ReadLine();
- sr.Close();
- file.Close();
+ BypassCertificateError();
+
+ DateTime currentServerTime = DateTime.UtcNow;
+ serverTimeLabel.Text = String.Format("{0:ddd, MMM dd, yyyy HH:mm:ss}", currentServerTime) + " UTC";
+
+ this.ReadConfigFile();
}
catch (Exception ex)
{
- return false;
- }
- if ((access_token == null) || (expiryMilliSeconds == null) || (refresh_token == null) || (lastTokenTakenTime == null) || (refreshTokenExpiryTime == null))
- {
- return false;
+ this.DrawPanelForFailure(sendMessagePanel, ex.ToString());
}
- return true;
}
- /* 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
- */
- public string isTokenValid()
+ /// <summary>
+ /// This method will be called when user clicks on send mms button
+ /// </summary>
+ /// <param name="sender">object, that caused this event</param>
+ /// <param name="e">Event that invoked this function</param>
+ protected void SendMMSMessageButton_Click(object sender, EventArgs e)
{
try
{
+ if (this.ReadAndGetAccessToken() == true)
+ {
+ long fileSize = 0;
+ if (!string.IsNullOrEmpty(FileUpload1.FileName))
+ {
+ FileUpload1.SaveAs(Request.MapPath(FileUpload1.FileName.ToString()));
+ Session["mmsFilePath1"] = Request.MapPath(FileUpload1.FileName);
+ FileInfo fileInfoObj = new FileInfo(Session["mmsFilePath1"].ToString());
+ fileSize = fileSize + (fileInfoObj.Length / 1024);
+ if (fileSize > 600)
+ {
+ this.DrawPanelForFailure(sendMessagePanel, "Attachment file size exceeded 600kb");
+ return;
+ }
+ }
- DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();
- DateTime lastRefreshTokenTime = DateTime.Parse(refreshTokenExpiryTime);
- TimeSpan refreshSpan = currentServerTime.Subtract(lastRefreshTokenTime);
- if (currentServerTime >= lastRefreshTokenTime)
- {
- return "INVALID_ACCESS_TOKEN";
- }
- DateTime lastTokenTime = DateTime.Parse(lastTokenTakenTime);
- TimeSpan tokenSpan = currentServerTime.Subtract(lastTokenTime);
- if (((tokenSpan.TotalSeconds)) > Convert.ToInt32(expiryMilliSeconds))
- {
- return "REFRESH_ACCESS_TOKEN";
- }
- else
- {
- return "VALID_ACCESS_TOKEN";
+ if (!string.IsNullOrEmpty(FileUpload2.FileName))
+ {
+ FileUpload2.SaveAs(Request.MapPath(FileUpload2.FileName));
+ Session["mmsFilePath2"] = Request.MapPath(FileUpload2.FileName);
+ FileInfo fileInfoObj = new FileInfo(Session["mmsFilePath2"].ToString());
+ fileSize = fileSize + (fileInfoObj.Length / 1024);
+ if (fileSize > 600)
+ {
+ this.DrawPanelForFailure(sendMessagePanel, "Attachment file size exceeded 600kb");
+ return;
+ }
+ }
+
+ if (!string.IsNullOrEmpty(FileUpload3.FileName))
+ {
+ FileUpload3.SaveAs(Request.MapPath(FileUpload3.FileName));
+ Session["mmsFilePath3"] = Request.MapPath(FileUpload3.FileName);
+ FileInfo fileInfoObj = new FileInfo(Session["mmsFilePath3"].ToString());
+ fileSize = fileSize + (fileInfoObj.Length / 1024);
+ if (fileSize > 600)
+ {
+ this.DrawPanelForFailure(sendMessagePanel, "Attachment file size exceeded 600kb");
+ return;
+ }
+ }
+
+ if (fileSize <= 600)
+ {
+ this.SendMMS();
+ }
+ else
+ {
+ this.DrawPanelForFailure(sendMessagePanel, "Attachment file size exceeded 600kb");
+ return;
+ }
}
}
catch (Exception ex)
{
- return "INVALID_ACCESS_TOKEN";
+ this.DrawPanelForFailure(sendMessagePanel, ex.ToString());
+ return;
}
}
+ /// <summary>
+ /// This method will be called when user click on get status button
+ /// </summary>
+ /// <param name="sender">object, that caused this event</param>
+ /// <param name="e">Event that invoked this function</param>
+ protected void GetStatusButton_Click(object sender, EventArgs e)
+ {
+ this.GetMmsDeliveryStatus();
+ }
+
+ #endregion
- /* 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
- */
- public bool getAccessToken(int type, Panel panelParam)
+ #region Access Token Methods
+
+ /// <summary>
+ /// This function reads access token file, validates the access token and gets a new access token
+ /// </summary>
+ /// <returns>true if access token is valid, or else false is returned</returns>
+ private bool ReadAndGetAccessToken()
{
- /* This is client credential flow: */
- if (type == 1)
+ bool ableToGetToken = true;
+
+ if (this.ReadAccessTokenFile() == false)
{
- try
- {
- DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();
- WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create("" + FQDN + "/oauth/token");
- accessTokenRequest.Method = "POST";
- string oauthParameters = "client_id=" + api_key.ToString() + "&client_secret=" + secret_key.ToString() + "&grant_type=client_credentials&scope=MMS";
- accessTokenRequest.ContentType = "application/x-www-form-urlencoded";
- //sendSmsRequestObject.Accept = "application/json";
- UTF8Encoding encoding = new UTF8Encoding();
- byte[] postBytes = encoding.GetBytes(oauthParameters);
- accessTokenRequest.ContentLength = postBytes.Length;
- Stream postStream = accessTokenRequest.GetRequestStream();
- postStream.Write(postBytes, 0, postBytes.Length);
- postStream.Close();
- 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));
- access_token = deserializedJsonObj.access_token.ToString();
- expiryMilliSeconds = deserializedJsonObj.expires_in.ToString();
- refresh_token = deserializedJsonObj.refresh_token.ToString();
- FileStream file = new FileStream(Request.MapPath(accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Write);
- StreamWriter sw = new StreamWriter(file);
- sw.WriteLine(access_token);
- sw.WriteLine(expiryMilliSeconds);
- sw.WriteLine(refresh_token);
- sw.WriteLine(currentServerTime.ToLongDateString() + " " + currentServerTime.ToLongTimeString());
- lastTokenTakenTime = currentServerTime.ToLongDateString() + " " + currentServerTime.ToLongTimeString();
- //Refresh token valids for 24 hours
- DateTime refreshExpiry = currentServerTime.AddHours(24);
- refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString();
- sw.WriteLine(refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString());
- sw.Close();
- file.Close();
- // Close and clean up the StreamReader
- accessTokenResponseStream.Close();
- return true;
- }
- }
- catch (Exception ex)
- {
- drawPanelForFailure(panelParam, ex.ToString());
- return false;
- }
+ ableToGetToken = this.GetAccessToken(AccessTokenType.Client_Credential);
}
- else if (type == 2)
+ else
{
- try
+ string tokenValidity = this.IsTokenValid();
+
+ if (tokenValidity.Equals("REFRESH_TOKEN"))
{
- DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();
- WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create("" + FQDN + "/oauth/token");
- accessTokenRequest.Method = "POST";
- string oauthParameters = "grant_type=refresh_token&client_id=" + api_key.ToString() + "&client_secret=" + secret_key.ToString() + "&refresh_token=" + refresh_token.ToString();
- accessTokenRequest.ContentType = "application/x-www-form-urlencoded";
- //sendSmsRequestObject.Accept = "application/json";
- UTF8Encoding encoding = new UTF8Encoding();
- byte[] postBytes = encoding.GetBytes(oauthParameters);
- accessTokenRequest.ContentLength = postBytes.Length;
- Stream postStream = accessTokenRequest.GetRequestStream();
- postStream.Write(postBytes, 0, postBytes.Length);
- postStream.Close();
- WebResponse accessTokenResponse = accessTokenRequest.GetResponse();
- using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream()))
- {
- string access_token_json = accessTokenResponseStream.ReadToEnd().ToString();
- JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
- AccessTokenResponse deserializedJsonObj = (AccessTokenResponse)deserializeJsonObject.Deserialize(access_token_json, typeof(AccessTokenResponse));
- access_token = deserializedJsonObj.access_token.ToString();
- expiryMilliSeconds = deserializedJsonObj.expires_in.ToString();
- refresh_token = deserializedJsonObj.refresh_token.ToString();
- FileStream file = new FileStream(Request.MapPath(accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Write);
- StreamWriter sw = new StreamWriter(file);
- sw.WriteLine(access_token);
- sw.WriteLine(expiryMilliSeconds);
- sw.WriteLine(refresh_token);
- sw.WriteLine(currentServerTime.ToLongDateString() + " " + currentServerTime.ToLongTimeString());
- lastTokenTakenTime = currentServerTime.ToLongDateString() + " " + currentServerTime.ToLongTimeString();
- //Refresh token valids for 24 hours
- DateTime refreshExpiry = currentServerTime.AddHours(24);
- refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString();
- sw.WriteLine(refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString());
- sw.Close();
- file.Close();
- accessTokenResponseStream.Close();
- return true;
- }
+ ableToGetToken = this.GetAccessToken(AccessTokenType.Refresh_Token);
}
- catch (Exception ex)
+ else if (tokenValidity.Equals("INVALID_ACCESS_TOKEN"))
{
- drawPanelForFailure(panelParam, ex.ToString());
- return false;
+ ableToGetToken = this.GetAccessToken(AccessTokenType.Client_Credential);
}
}
- return false;
- }
- /* This function is used to neglect the ssl handshake error with authentication server */
-
- public static void BypassCertificateError()
- {
- ServicePointManager.ServerCertificateValidationCallback +=
- delegate(Object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
- {
- return true;
- };
+ return ableToGetToken;
}
- /* 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
- */
- public bool readAndGetAccessToken(Panel panelParam)
+
+ /// <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.
+ /// </summary>
+ /// <returns>true, if access token file and all others attributes read successfully otherwise returns false</returns>
+ private bool ReadAccessTokenFile()
{
- bool result = true;
- if (readAccessTokenFile() == false)
+ FileStream fileStream = null;
+ StreamReader streamReader = null;
+ bool ableToRead = true;
+ try
{
- result = getAccessToken(1, panelParam);
+ fileStream = new FileStream(Request.MapPath(this.accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Read);
+ streamReader = new StreamReader(fileStream);
+ this.accessToken = streamReader.ReadLine();
+ this.expirySeconds = streamReader.ReadLine();
+ this.refreshToken = streamReader.ReadLine();
+ this.accessTokenExpiryTime = Convert.ToDateTime(streamReader.ReadLine());
+ this.refreshTokenExpiryTime = streamReader.ReadLine();
}
- else
+ catch (Exception ex)
+ {
+ this.DrawPanelForFailure(sendMessagePanel, ex.ToString());
+ ableToRead = false;
+ }
+ finally
{
- string tokenValidity = isTokenValid();
- if (tokenValidity.CompareTo("REFRESH_ACCESS_TOKEN") == 0)
+ if (null != streamReader)
{
- result = getAccessToken(2, panelParam);
+ streamReader.Close();
}
- else if (string.Compare(isTokenValid(), "INVALID_ACCESS_TOKEN") == 0)
+
+ if (null != fileStream)
{
- result = getAccessToken(1, panelParam);
+ fileStream.Close();
}
}
- return result;
+
+ if (this.accessToken == null || this.expirySeconds == null || this.refreshToken == null || this.accessTokenExpiryTime == null || this.refreshTokenExpiryTime == null)
+ {
+ ableToRead = false;
+ }
+
+ return ableToRead;
}
- /*
- * 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
- *
- */
- protected void Page_Load(object sender, EventArgs e)
+
+ /// <summary>
+ /// Validates he expiry of the access token and refresh token
+ /// </summary>
+ /// <returns>string, returns VALID_ACCESS_TOKEN if its valid
+ /// otherwise, returns INVALID_ACCESS_TOKEN if refresh token expired or not able to read session variables
+ /// return REFRESH_TOKEN, if access token in expired and refresh token is valid</returns>
+ private string IsTokenValid()
{
+ if (this.accessToken == null)
+ {
+ return "INVALID_ACCESS_TOKEN";
+ }
+
try
{
- BypassCertificateError();
- DateTime currentServerTime = DateTime.UtcNow;
- serverTimeLabel.Text = String.Format("{0:ddd, MMM dd, yyyy HH:mm:ss}", currentServerTime) + " UTC";
- if (ConfigurationManager.AppSettings["AccessTokenFilePath"] != null)
- {
- accessTokenFilePath = ConfigurationManager.AppSettings["AccessTokenFilePath"];
- }
- else
- {
- accessTokenFilePath = "~\\MMSApp1AccessToken.txt";
- }
- if (ConfigurationManager.AppSettings["FQDN"] == null)
- {
- drawPanelForFailure(sendMessagePanel, "FQDN is not defined in configuration file");
- return;
- }
- FQDN = ConfigurationManager.AppSettings["FQDN"].ToString();
- if (ConfigurationManager.AppSettings["short_code"] == null)
- {
- drawPanelForFailure(sendMessagePanel, "short_code is not defined in configuration file");
- return;
- }
- shortCode = ConfigurationManager.AppSettings["short_code"].ToString();
- if (ConfigurationManager.AppSettings["api_key"] == null)
- {
- drawPanelForFailure(sendMessagePanel, "api_key is not defined in configuration file");
- return;
- }
- api_key = ConfigurationManager.AppSettings["api_key"].ToString();
- if (ConfigurationManager.AppSettings["secret_key"] == null)
- {
- drawPanelForFailure(sendMessagePanel, "secret_key is not defined in configuration file");
- return;
- }
- secret_key = ConfigurationManager.AppSettings["secret_key"].ToString();
- if (ConfigurationManager.AppSettings["scope"] == null)
+ DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();
+ if (currentServerTime >= this.accessTokenExpiryTime)
{
- scope = "MMS";
+ if (currentServerTime >= DateTime.Parse(this.refreshTokenExpiryTime))
+ {
+ return "INVALID_ACCESS_TOKEN";
+ }
+ else
+ {
+ return "REFRESH_TOKEN";
+ }
}
else
{
- scope = ConfigurationManager.AppSettings["scope"].ToString();
+ return "VALID_ACCESS_TOKEN";
}
}
- catch (Exception ex)
+ catch
{
- drawPanelForFailure(sendMessagePanel, ex.ToString());
- Response.Write(ex.ToString());
+ return "INVALID_ACCESS_TOKEN";
}
}
- /*
- * This funciton calls send mms message to send the selected files
- */
- private void sendMms()
+
+ /// <summary>
+ /// This method gets access token based on either client credentials mode or refresh token.
+ /// </summary>
+ /// <param name="type">AccessTokenType; either Client_Credential or Refresh_Token</param>
+ /// <returns>true/false; true if able to get access token, else false</returns>
+ private bool GetAccessToken(AccessTokenType type)
{
+
+ Stream postStream = null;
+ StreamWriter streamWriter = null;
+ FileStream fileStream = null;
try
{
- string smsAddressInput = phoneTextBox.Text.ToString();
- string smsAddressFormatted;
- string phoneStringPattern = "^\\d{3}-\\d{3}-\\d{4}$";
- if (System.Text.RegularExpressions.Regex.IsMatch(smsAddressInput, phoneStringPattern))
+ 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 == AccessTokenType.Client_Credential)
{
- smsAddressFormatted = smsAddressInput.Replace("-", "");
+ oauthParameters = "client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&grant_type=client_credentials&scope=MMS";
}
else
{
- smsAddressFormatted = smsAddressInput;
- }
- string smsAddressForRequest = smsAddressFormatted.ToString();
- long tryParseResult = 0;
- if (smsAddressFormatted.Length == 16 && smsAddressFormatted.StartsWith("tel:+1"))
- {
- smsAddressFormatted = smsAddressFormatted.Substring(6, 10);
- }
- else if (smsAddressFormatted.Length == 15 && smsAddressFormatted.StartsWith("tel:+"))
- {
- smsAddressFormatted = smsAddressFormatted.Substring(5, 10);
- }
- else if (smsAddressFormatted.Length == 14 && smsAddressFormatted.StartsWith("tel:"))
- {
- smsAddressFormatted = smsAddressFormatted.Substring(4, 10);
- }
- else if (smsAddressFormatted.Length == 12 && smsAddressFormatted.StartsWith("+1"))
- {
- smsAddressFormatted = smsAddressFormatted.Substring(2, 10);
- }
- else if (smsAddressFormatted.Length == 11 && smsAddressFormatted.StartsWith("1"))
- {
- smsAddressFormatted = smsAddressFormatted.Substring(1, 10);
- }
- if ((smsAddressFormatted.Length != 10) || (!long.TryParse(smsAddressFormatted, out tryParseResult)))
- {
- drawPanelForFailure(sendMessagePanel, "Invalid phone number: " + smsAddressInput);
+ oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken;
}
- else
- {
- string mmsAddress = smsAddressForRequest.ToString();
- string mmsMessage = messageTextBox.Text.ToString();
- if (mmsMessage == null || mmsMessage.Length <=0)
- {
- drawPanelForFailure(sendMessagePanel, "Message is null or empty");
- return;
- }
+ accessTokenRequest.ContentType = "application/x-www-form-urlencoded";
- if ((Session["mmsFilePath1"] == null) && (Session["mmsFilePath2"] == null) && (Session["mmsFilePath3"] == null))
- {
- string boundaryToSend = "----------------------------" + DateTime.Now.Ticks.ToString("x");
- HttpWebRequest mmsRequestObject1 = (HttpWebRequest)WebRequest.Create("" + FQDN + "/rest/mms/2/messaging/outbox?access_token=" + access_token.ToString());
- mmsRequestObject1.ContentType = "multipart/form-data; type=\"application/x-www-form-urlencoded\"; start=\"<startpart>\"; boundary=\"" + boundaryToSend + "\"\r\n";
- mmsRequestObject1.Method = "POST";
- mmsRequestObject1.KeepAlive = true;
- UTF8Encoding encoding1 = new UTF8Encoding();
- byte[] bytesToSend = encoding1.GetBytes("");
- string mmsParameters = "Address=" + Server.UrlEncode("tel:" + mmsAddress) + "&Subject=" + Server.UrlEncode(mmsMessage);
- string dataToSend = "";
- dataToSend += "--" + boundaryToSend + "\r\n";
- dataToSend += "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\nContent-Transfer-Encoding: 8bit\r\nContent-Disposition: form-data; name=\"root-fields\"\r\nContent-ID: <startpart>\r\n\r\n"+ mmsParameters +"\r\n";
- dataToSend += "--" + boundaryToSend + "--\r\n";
- bytesToSend = encoding1.GetBytes(dataToSend);
- int sizeToSend = bytesToSend.Length;
- var memBufToSend = new MemoryStream(new byte[sizeToSend], 0, sizeToSend, true, true);
- memBufToSend.Write(bytesToSend, 0, bytesToSend.Length);
- //ms.Write(image, 0, image.Length);
- byte[] finalData = memBufToSend.GetBuffer();
- mmsRequestObject1.ContentLength = finalData.Length;
- Stream postStream1 = mmsRequestObject1.GetRequestStream();
- postStream1.Write(finalData, 0, finalData.Length);
- postStream1.Close();
-
- WebResponse mmsResponseObject1 = mmsRequestObject1.GetResponse();
- using (StreamReader sr = new StreamReader(mmsResponseObject1.GetResponseStream()))
- {
- string mmsResponseData = sr.ReadToEnd();
- JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
- mmsResponseId deserializedJsonObj = (mmsResponseId)deserializeJsonObject.Deserialize(mmsResponseData, typeof(mmsResponseId));
- messageIDTextBox.Text = deserializedJsonObj.id.ToString();
- drawPanelForSuccess(sendMessagePanel, deserializedJsonObj.id.ToString());
- sr.Close();
- }
- return;
+ UTF8Encoding encoding = new UTF8Encoding();
- }
-
- string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
-
- HttpWebRequest mmsRequestObject = (HttpWebRequest)WebRequest.Create("" + FQDN + "/rest/mms/2/messaging/outbox?access_token=" + access_token.ToString());
- mmsRequestObject.ContentType = "multipart/form-data; type=\"application/x-www-form-urlencoded\"; start=\"<startpart>\"; boundary=\"" + boundary + "\"\r\n";
- mmsRequestObject.Method = "POST";
- mmsRequestObject.KeepAlive = true;
- UTF8Encoding encoding = new UTF8Encoding();
- byte[] postBytes = encoding.GetBytes("");
- byte[] postBytes1 = encoding.GetBytes("");
- byte[] postBytes2 = encoding.GetBytes("");
- byte[] totalpostBytes = encoding.GetBytes("");
- string sendMMSData = "Address=" + Server.UrlEncode("tel:" + mmsAddress) + "&Subject=" + Server.UrlEncode(mmsMessage);
- string data = "";
- data += "--" + boundary + "\r\n";
- data += "Content-Type:application/x-www-form-urlencoded;charset=UTF-8\r\nContent-Transfer-Encoding:8bit\r\nContent-ID:<startpart>\r\n\r\n" + sendMMSData + "\r\n";
+ byte[] postBytes = encoding.GetBytes(oauthParameters);
+ accessTokenRequest.ContentLength = postBytes.Length;
- if (Session["mmsFilePath1"] != null)
- {
- string mmsFileName = Path.GetFileName(Session["mmsFilePath1"].ToString());
- FileStream fs = new FileStream(Session["mmsFilePath1"].ToString(), FileMode.Open, FileAccess.Read);
- BinaryReader br = new BinaryReader(fs);
- byte[] image = br.ReadBytes((int)fs.Length);
- br.Close();
- fs.Close();
- data += "--" + boundary + "\r\n";
- data += "Content-Disposition:attachment;name=\"" + mmsFileName + "\"\r\n";
- data += "Content-Type:image/gif\r\n";
- data += "Content-ID:<" + mmsFileName + ">\r\n";
- data += "Content-Transfer-Encoding:binary\r\n\r\n";
- byte[] firstPart = encoding.GetBytes(data);
- int newSize = firstPart.Length + image.Length;
- var ms = new MemoryStream(new byte[newSize], 0, newSize, true, true);
- ms.Write(firstPart, 0, firstPart.Length);
- ms.Write(image, 0, image.Length);
- postBytes = ms.GetBuffer();
- totalpostBytes = postBytes;
- //Session["mmsFilePath1"] = null;
- }
+ postStream = accessTokenRequest.GetRequestStream();
+ postStream.Write(postBytes, 0, postBytes.Length);
- if (Session["mmsFilePath2"] != null)
- {
- if (Session["mmsFilePath1"] != null)
- data = "--" + boundary + "\r\n";
- else
- data += "--" + boundary + "\r\n";
- string mmsFileName = Path.GetFileName(Session["mmsFilePath2"].ToString());
- FileStream fs = new FileStream(Session["mmsFilePath2"].ToString(), FileMode.Open, FileAccess.Read);
- BinaryReader br = new BinaryReader(fs);
- byte[] image = br.ReadBytes((int)fs.Length);
- br.Close();
- fs.Close();
- data += "Content-Disposition:attachment;name=\"" + mmsFileName + "\"\r\n";
- data += "Content-Type:image/gif\r\n";
- data += "Content-ID:<" + mmsFileName + ">\r\n";
- data += "Content-Transfer-Encoding:binary\r\n\r\n";
- byte[] firstPart = encoding.GetBytes(data);
- int newSize = firstPart.Length + image.Length;
- var ms = new MemoryStream(new byte[newSize], 0, newSize, true, true);
- ms.Write(firstPart, 0, firstPart.Length);
- ms.Write(image, 0, image.Length);
- postBytes1 = ms.GetBuffer();
- //byte[] secondpart = ms.GetBuffer();
- //byte[] thirdpart = encoding.GetBytes("\r\n--" + boundary + "--\r\n");
- if (Session["mmsFilePath1"] != null)
- {
- var ms2 = JoinTwoByteArrays(postBytes, postBytes1);
- totalpostBytes = ms2.GetBuffer();
- }
- else
- {
- totalpostBytes = postBytes1;
- }
- //Session["mmsFilePath2"] = null;
- }
+ WebResponse accessTokenResponse = accessTokenRequest.GetResponse();
- if (Session["mmsFilePath3"] != null)
- {
- if (Session["mmsFilePath1"] != null || Session["mmsFilePath2"] != null)
- data = "--" + boundary + "\r\n";
- else
- data += "--" + boundary + "\r\n";
- string mmsFileName = Path.GetFileName(Session["mmsFilePath3"].ToString());
- FileStream fs = new FileStream(Session["mmsFilePath3"].ToString(), FileMode.Open, FileAccess.Read);
- BinaryReader br = new BinaryReader(fs);
- byte[] image = br.ReadBytes((int)fs.Length);
- br.Close();
- fs.Close();
- data += "Content-Disposition:attachment;name=\"" + mmsFileName + "\"\r\n";
- data += "Content-Type:image/gif\r\n";
- data += "Content-ID:<" + mmsFileName + ">\r\n";
- data += "Content-Transfer-Encoding:binary\r\n\r\n";
- byte[] firstPart = encoding.GetBytes(data);
- int newSize = firstPart.Length + image.Length;
- var ms = new MemoryStream(new byte[newSize], 0, newSize, true, true);
- ms.Write(firstPart, 0, firstPart.Length);
- ms.Write(image, 0, image.Length);
- postBytes2 = ms.GetBuffer();
- if (Session["mmsFilePath1"] != null || Session["mmsFilePath2"] != null)
- {
- byte[] temp = totalpostBytes;
- var ms2 = JoinTwoByteArrays(temp, postBytes2);
- totalpostBytes = ms2.GetBuffer();
- }
- else
- {
- totalpostBytes = postBytes2;
- }
- }
+ using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream()))
+ {
+ string jsonAccessToken = accessTokenResponseStream.ReadToEnd();
+ JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
+ AccessTokenResponse deserializedJsonObj = (AccessTokenResponse)deserializeJsonObject.Deserialize(jsonAccessToken, typeof(AccessTokenResponse));
- byte[] byteLastBoundary = encoding.GetBytes("\r\n--" + boundary + "--\r\n");
- //int totalSize = postBytes.Length + postBytes1.Length + postBytes2.Length + byteLastBoundary.Length;
- int totalSize = totalpostBytes.Length + byteLastBoundary.Length;
- var totalMS = new MemoryStream(new byte[totalSize], 0, totalSize, true, true);
- totalMS.Write(totalpostBytes, 0, totalpostBytes.Length);
- totalMS.Write(byteLastBoundary, 0, byteLastBoundary.Length);
- byte[] finalpostBytes = totalMS.GetBuffer();
- mmsRequestObject.ContentLength = finalpostBytes.Length;
- Stream postStream = mmsRequestObject.GetRequestStream();
- postStream.Write(finalpostBytes, 0, finalpostBytes.Length);
- postStream.Close();
+ this.accessToken = deserializedJsonObj.access_token;
+ this.expirySeconds = deserializedJsonObj.expires_in;
+ this.refreshToken = deserializedJsonObj.refresh_token;
+ this.accessTokenExpiryTime = currentServerTime.AddSeconds(Convert.ToDouble(deserializedJsonObj.expires_in));
- WebResponse mmsResponseObject = mmsRequestObject.GetResponse();
- using (StreamReader sr = new StreamReader(mmsResponseObject.GetResponseStream()))
+ DateTime refreshExpiry = currentServerTime.AddHours(this.refreshTokenExpiresIn);
+
+ if (deserializedJsonObj.expires_in.Equals("0"))
{
- string mmsResponseData = sr.ReadToEnd();
- JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
- mmsResponseId deserializedJsonObj = (mmsResponseId)deserializeJsonObject.Deserialize(mmsResponseData, typeof(mmsResponseId));
- messageIDTextBox.Text = deserializedJsonObj.id.ToString();
- drawPanelForSuccess(sendMessagePanel, deserializedJsonObj.id.ToString());
- sr.Close();
+ int defaultAccessTokenExpiresIn = 100; // In Years
+ this.accessTokenExpiryTime = currentServerTime.AddYears(defaultAccessTokenExpiresIn);
}
- mmsRequestObject = null;
- int indexj = 1;
- while (indexj <= 3)
+
+ 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.expirySeconds);
+ streamWriter.WriteLine(this.refreshToken);
+ streamWriter.WriteLine(this.accessTokenExpiryTime.ToString());
+ 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()))
{
- if (Convert.ToString(Session["mmsFilePath" + indexj]) != "")
- {
- if (File.Exists(Session["mmsFilePath" + indexj].ToString()))
- {
- System.IO.FileInfo fileInfo = new System.IO.FileInfo(Session["mmsFilePath" + indexj].ToString());
- fileInfo.Delete();
- Session["mmsFilePath" + indexj] = null;
- }
- }
- indexj++;
+ errorResponse = sr2.ReadToEnd();
+ sr2.Close();
}
}
+ catch
+ {
+ errorResponse = "Unable to get response";
+ }
+ this.DrawPanelForFailure(sendMessagePanel, errorResponse + Environment.NewLine + we.Message);
}
catch (Exception ex)
{
- drawPanelForFailure(sendMessagePanel, ex.ToString());
- int index = 1;
+ this.DrawPanelForFailure(sendMessagePanel, ex.ToString());
+ }
+ finally
+ {
+ if (null != postStream)
+ {
+ postStream.Close();
+ }
- while (index <= 3)
+ if (null != streamWriter)
{
- if (Convert.ToString(Session["mmsFilePath" + index]) != "")
- {
- if (File.Exists(Session["mmsFilePath" + index].ToString()))
- {
- System.IO.FileInfo fileInfo = new System.IO.FileInfo(Session["mmsFilePath" + index].ToString());
- fileInfo.Delete();
- Session["mmsFilePath" + index] = null;
- }
- }
- index++;
+ streamWriter.Close();
+ }
+
+ if (null != fileStream)
+ {
+ fileStream.Close();
}
}
- }
- /* this function add two byte arrays and returns the address of buffer */
- private static MemoryStream JoinTwoByteArrays(byte[] firstByteArray, byte[] secondByteArray)
- {
- int newSize = firstByteArray.Length + secondByteArray.Length;
- var ms = new MemoryStream(new byte[newSize], 0, newSize, true, true);
- ms.Write(firstByteArray, 0, firstByteArray.Length);
- ms.Write(secondByteArray, 0, secondByteArray.Length);
- return ms;
+ return false;
}
- /* this function draws success table */
- private void drawPanelForSuccess(Panel panelParam, string message)
+ #endregion
+
+ #region Display Status message methods
+ /// <summary>
+ /// Display success message
+ /// </summary>
+ /// <param name="panelParam">Panel to draw success message</param>
+ /// <param name="message">Message to display</param>
+ private void DrawPanelForSuccess(Panel panelParam, string message)
{
+ if (panelParam.HasControls())
+ {
+ panelParam.Controls.Clear();
+ }
+
Table table = new Table();
+ table.CssClass = "successWide";
table.Font.Name = "Sans-serif";
table.Font.Size = 9;
- table.BorderStyle = BorderStyle.Outset;
- table.Width = Unit.Pixel(650);
TableRow rowOne = new TableRow();
TableCell rowOneCellOne = new TableCell();
rowOneCellOne.Font.Bold = true;
rowOneCellOne.Text = "SUCCESS:";
- // rowOneCellOne.BorderWidth = 1;
+ rowOneCellOne.Width = Unit.Pixel(75);
rowOne.Controls.Add(rowOneCellOne);
table.Controls.Add(rowOne);
+
TableRow rowTwo = new TableRow();
TableCell rowTwoCellOne = new TableCell();
rowTwoCellOne.Font.Bold = true;
rowTwoCellOne.Text = "Message ID:";
- rowTwoCellOne.Width = Unit.Pixel(70);
- //rowOneCellOne.BorderWidth = 1;
+ rowTwoCellOne.Width = Unit.Pixel(75);
rowTwo.Controls.Add(rowTwoCellOne);
+
TableCell rowTwoCellTwo = new TableCell();
- rowTwoCellTwo.Text = message.ToString();
- //rowTwoCellOne.BorderWidth = 1;
+ rowTwoCellTwo.Text = message;
+ rowTwoCellTwo.HorizontalAlign = HorizontalAlign.Left;
rowTwo.Controls.Add(rowTwoCellTwo);
table.Controls.Add(rowTwo);
- table.BorderWidth = 2;
- table.BorderColor = Color.DarkGreen;
- table.BackColor = System.Drawing.ColorTranslator.FromHtml("#cfc");
panelParam.Controls.Add(table);
}
- /* this function draws error table */
- private void drawPanelForFailure(Panel panelParam, string message)
+
+ /// <summary>
+ /// Displays error message
+ /// </summary>
+ /// <param name="panelParam">Panel to draw success message</param>
+ /// <param name="message">Message to display</param>
+ private void DrawPanelForFailure(Panel panelParam, string message)
{
+ if (panelParam.HasControls())
+ {
+ panelParam.Controls.Clear();
+ }
+
Table table = new Table();
+ table.CssClass = "errorWide";
table.Font.Name = "Sans-serif";
table.Font.Size = 9;
- table.BorderStyle = BorderStyle.Outset;
- table.Width = Unit.Pixel(650);
TableRow rowOne = new TableRow();
TableCell rowOneCellOne = new TableCell();
rowOneCellOne.Font.Bold = true;
rowOneCellOne.Text = "ERROR:";
rowOne.Controls.Add(rowOneCellOne);
- //rowOneCellOne.BorderWidth = 1;
table.Controls.Add(rowOne);
TableRow rowTwo = new TableRow();
TableCell rowTwoCellOne = new TableCell();
- //rowTwoCellOne.BorderWidth = 1;
rowTwoCellOne.Text = message.ToString();
rowTwo.Controls.Add(rowTwoCellOne);
table.Controls.Add(rowTwo);
- table.BorderWidth = 2;
- table.BorderColor = Color.Red;
- table.BackColor = System.Drawing.ColorTranslator.FromHtml("#fcc");
panelParam.Controls.Add(table);
}
- /* this funciton is called when user clicks on send mms button */
+ /// <summary>
+ /// Displays Resource url upon success of GetMmsDelivery
+ /// </summary>
+ /// <param name="status">string, status of the request</param>
+ /// <param name="url">string, url of the resource</param>
+ private void DrawGetStatusSuccess(string status, string url)
+ {
+ if (getStatusPanel.HasControls())
+ {
+ getStatusPanel.Controls.Clear();
+ }
- protected void sendMMSMessageButton_Click(object sender, EventArgs e)
+ Table table = new Table();
+ table.CssClass = "successWide";
+ table.Font.Name = "Sans-serif";
+ table.Font.Size = 9;
+
+ TableRow rowOne = new TableRow();
+ TableCell rowOneCellOne = new TableCell();
+ rowOneCellOne.Font.Bold = true;
+ rowOneCellOne.Text = "SUCCESS:";
+ rowOne.Controls.Add(rowOneCellOne);
+ table.Controls.Add(rowOne);
+
+ TableRow rowTwo = new TableRow();
+ TableCell rowTwoCellOne = new TableCell();
+ TableCell rowTwoCellTwo = new TableCell();
+ rowTwoCellOne.Text = "Status: ";
+ rowTwoCellOne.Font.Bold = true;
+ rowTwo.Controls.Add(rowTwoCellOne);
+ rowTwoCellTwo.Text = status.ToString();
+ rowTwo.Controls.Add(rowTwoCellTwo);
+ table.Controls.Add(rowTwo);
+ TableRow rowThree = new TableRow();
+ TableCell rowThreeCellOne = new TableCell();
+ TableCell rowThreeCellTwo = new TableCell();
+ rowThreeCellOne.Text = "ResourceURL: ";
+ rowThreeCellOne.Font.Bold = true;
+ rowThree.Controls.Add(rowThreeCellOne);
+ rowThreeCellTwo.Text = url.ToString();
+ rowThree.Controls.Add(rowThreeCellTwo);
+ table.Controls.Add(rowThree);
+
+ getStatusPanel.Controls.Add(table);
+ }
+
+#endregion
+
+ #region Application Specific Methods
+
+ /// <summary>
+ /// This function calls get message delivery status api to fetch the delivery status
+ /// </summary>
+ private void GetMmsDeliveryStatus()
{
try
{
- if (readAndGetAccessToken(sendMessagePanel) == true)
+ string mmsId = messageIDTextBox.Text;
+ if (mmsId == null || mmsId.Length <= 0)
{
- if (access_token == null || access_token.Length <= 0)
- {
- //drawPanelForFailure(sendSMSPanel, "Invalid access token");
- return;
- }
- long fileSize = 0;
- if (FileUpload1.FileName.ToString() != "")
- {
- FileUpload1.SaveAs(Request.MapPath(FileUpload1.FileName.ToString()));
- Session["mmsFilePath1"] = Request.MapPath(FileUpload1.FileName);
- FileInfo fileInfoObj = new FileInfo(Session["mmsFilePath1"].ToString());
- fileSize = fileSize + fileInfoObj.Length / 1024;
- if (fileSize > 600)
- {
- drawPanelForFailure(sendMessagePanel, "Attachment file size exceeded 600kb");
- return;
- }
- }
- if (FileUpload2.FileName.ToString() != "")
- {
- FileUpload2.SaveAs(Request.MapPath(FileUpload2.FileName));
- Session["mmsFilePath2"] = Request.MapPath(FileUpload2.FileName);
- FileInfo fileInfoObj = new FileInfo(Session["mmsFilePath2"].ToString());
- fileSize = fileSize + fileInfoObj.Length / 1024;
- if (fileSize > 600)
- {
- drawPanelForFailure(sendMessagePanel, "Attachment file size exceeded 600kb");
- return;
- }
- }
- if (FileUpload3.FileName.ToString() != "")
- {
- FileUpload3.SaveAs(Request.MapPath(FileUpload3.FileName));
- Session["mmsFilePath3"] = Request.MapPath(FileUpload3.FileName);
- FileInfo fileInfoObj = new FileInfo(Session["mmsFilePath3"].ToString());
- fileSize = fileSize + fileInfoObj.Length / 1024;
- if (fileSize > 600)
- {
- drawPanelForFailure(sendMessagePanel, "Attachment file size exceeded 600kb");
- return;
- }
- }
- if (fileSize <= 600)
+ this.DrawPanelForFailure(getStatusPanel, "Message Id is null or empty");
+ return;
+ }
+
+ if (this.ReadAndGetAccessToken() == true)
+ {
+ string mmsDeliveryStatus;
+ HttpWebRequest mmsStatusRequestObject = (HttpWebRequest)System.Net.WebRequest.Create(string.Empty + this.endPoint + "/rest/mms/2/messaging/outbox/" + mmsId);
+ mmsStatusRequestObject.Headers.Add("Authorization", "Bearer " + this.accessToken);
+ mmsStatusRequestObject.Method = "GET";
+
+ HttpWebResponse mmsStatusResponseObject = (HttpWebResponse)mmsStatusRequestObject.GetResponse();
+ using (StreamReader mmsStatusResponseStream = new StreamReader(mmsStatusResponseObject.GetResponseStream()))
{
- sendMms();
+ mmsDeliveryStatus = mmsStatusResponseStream.ReadToEnd();
+ mmsDeliveryStatus = mmsDeliveryStatus.Replace("-", string.Empty);
+ JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
+ GetDeliveryStatus status = (GetDeliveryStatus)deserializeJsonObject.Deserialize(mmsDeliveryStatus, typeof(GetDeliveryStatus));
+ this.DrawGetStatusSuccess(status.DeliveryInfoList.deliveryInfo[0].deliverystatus, status.DeliveryInfoList.resourceURL);
+ mmsStatusResponseStream.Close();
}
- else
+ }
+ }
+ catch (WebException we)
+ {
+ string errorResponse = string.Empty;
+
+ try
+ {
+ using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
{
- drawPanelForFailure(sendMessagePanel, "Attachment file size exceeded 600kb");
- return;
+ errorResponse = sr2.ReadToEnd();
+ sr2.Close();
}
}
+ catch
+ {
+ errorResponse = "Unable to get response";
+ }
+ this.DrawPanelForFailure(getStatusPanel, errorResponse + Environment.NewLine + we.Message);
}
catch (Exception ex)
{
- drawPanelForFailure(sendMessagePanel, ex.ToString());
- return;
+ this.DrawPanelForFailure(getStatusPanel, ex.ToString());
+ }
+ }
+
+ /// <summary>
+ /// This method reads config file and assigns values to local variables
+ /// </summary>
+ /// <returns>true/false, true- if able to read from config file</returns>
+ private bool ReadConfigFile()
+ {
+ this.apiKey = ConfigurationManager.AppSettings["api_key"];
+ if (string.IsNullOrEmpty(this.apiKey))
+ {
+ this.DrawPanelForFailure(sendMessagePanel, "api_key is not defined in configuration file");
+ return false;
+ }
+
+ this.secretKey = ConfigurationManager.AppSettings["secret_key"];
+ if (string.IsNullOrEmpty(this.secretKey))
+ {
+ this.DrawPanelForFailure(sendMessagePanel, "secret_key is not defined in configuration file");
+ return false;
+ }
+
+ this.endPoint = ConfigurationManager.AppSettings["endPoint"];
+ if (string.IsNullOrEmpty(this.endPoint))
+ {
+ this.DrawPanelForFailure(sendMessagePanel, "endPoint is not defined in configuration file");
+ return false;
+ }
+
+ this.scope = ConfigurationManager.AppSettings["scope"];
+ if (string.IsNullOrEmpty(this.scope))
+ {
+ this.scope = "MMS";
+ }
+
+ this.accessTokenFilePath = ConfigurationManager.AppSettings["AccessTokenFilePath"];
+ if (string.IsNullOrEmpty(this.accessTokenFilePath))
+ {
+ this.accessTokenFilePath = "~\\MMSApp1AccessToken.txt";
+ }
+
+ string refreshTokenExpires = ConfigurationManager.AppSettings["refreshTokenExpiresIn"];
+ if (!string.IsNullOrEmpty(refreshTokenExpires))
+ {
+ this.refreshTokenExpiresIn = Convert.ToInt32(refreshTokenExpires);
+ }
+ else
+ {
+ this.refreshTokenExpiresIn = 24;
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Gets formatted phone number
+ /// </summary>
+ /// <returns>string, phone number</returns>
+ private string GetPhoneNumber()
+ {
+ long tryParseResult = 0;
+
+ string smsAddressInput = phoneTextBox.Text.ToString();
+
+ string smsAddressFormatted = string.Empty;
+
+ string phoneStringPattern = "^\\d{3}-\\d{3}-\\d{4}$";
+ if (System.Text.RegularExpressions.Regex.IsMatch(smsAddressInput, phoneStringPattern))
+ {
+ smsAddressFormatted = smsAddressInput.Replace("-", string.Empty);
+ }
+ else
+ {
+ smsAddressFormatted = smsAddressInput;
+ }
+
+ if (smsAddressFormatted.Length == 16 && smsAddressFormatted.StartsWith("tel:+1"))
+ {
+ smsAddressFormatted = smsAddressFormatted.Substring(6, 10);
+ }
+ else if (smsAddressFormatted.Length == 15 && smsAddressFormatted.StartsWith("tel:+"))
+ {
+ smsAddressFormatted = smsAddressFormatted.Substring(5, 10);
+ }
+ else if (smsAddressFormatted.Length == 14 && smsAddressFormatted.StartsWith("tel:"))
+ {
+ smsAddressFormatted = smsAddressFormatted.Substring(4, 10);
+ }
+ else if (smsAddressFormatted.Length == 12 && smsAddressFormatted.StartsWith("+1"))
+ {
+ smsAddressFormatted = smsAddressFormatted.Substring(2, 10);
+ }
+ else if (smsAddressFormatted.Length == 11 && smsAddressFormatted.StartsWith("1"))
+ {
+ smsAddressFormatted = smsAddressFormatted.Substring(1, 10);
+ }
+
+ if ((smsAddressFormatted.Length != 10) || (!long.TryParse(smsAddressFormatted, out tryParseResult)))
+ {
+ this.DrawPanelForFailure(sendMessagePanel, "Invalid phone number: " + smsAddressInput);
+ smsAddressFormatted = string.Empty;
}
+
+ return smsAddressFormatted;
}
- /* this function calls get message delivery status api to fetch the delivery status */
- private void getMmsDeliveryStatus()
+ /// <summary>
+ /// This funciton initiates send mms api call to send selected files as an mms
+ /// </summary>
+ private void SendMMS()
{
try
{
- string mmsId = messageIDTextBox.Text.ToString();
- if (mmsId == null || mmsId.Length <= 0)
+ string mmsAddress = this.GetPhoneNumber();
+ string mmsMessage = messageTextBox.Text.ToString();
+
+ if (((Session["mmsFilePath1"] == null) && (Session["mmsFilePath2"] == null) && (Session["mmsFilePath3"] == null)) && string.IsNullOrEmpty(mmsMessage))
{
- drawPanelForFailure(getStatusPanel, "Message Id is null or empty");
+ this.DrawPanelForFailure(sendMessagePanel, "Message is null or empty");
return;
}
- if (readAndGetAccessToken(sendMessagePanel) == true)
+
+ if ((Session["mmsFilePath1"] == null) && (Session["mmsFilePath2"] == null) && (Session["mmsFilePath3"] == null))
+ {
+ this.SendMessageNoAttachments(mmsAddress, mmsMessage);
+ }
+ else
+ {
+ this.SendMultimediaMessage(mmsAddress, mmsMessage);
+ }
+ }
+ catch (WebException we)
+ {
+ string errorResponse = string.Empty;
+
+ try
{
- if (access_token == null || access_token.Length <= 0)
+ using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
{
- //drawPanelForFailure(sendSMSPanel, "Invalid access token");
- return;
+ errorResponse = sr2.ReadToEnd();
+ sr2.Close();
}
- String mmsDeliveryStatus;
- HttpWebRequest mmsStatusRequestObject = (HttpWebRequest)System.Net.WebRequest.Create("" + FQDN + "/rest/mms/2/messaging/outbox/" + mmsId + "?access_token=" + access_token.ToString());
- mmsStatusRequestObject.Method = "GET";
- HttpWebResponse mmsStatusResponseObject = (HttpWebResponse)mmsStatusRequestObject.GetResponse();
- using (StreamReader mmsStatusResponseStream = new StreamReader(mmsStatusResponseObject.GetResponseStream()))
+ }
+ catch
+ {
+ errorResponse = "Unable to get response";
+ }
+ this.DrawPanelForFailure(sendMessagePanel, errorResponse + Environment.NewLine + we.Message);
+ }
+ catch (Exception ex)
+ {
+ this.DrawPanelForFailure(sendMessagePanel, ex.ToString());
+ }
+ finally
+ {
+ int index = 1;
+
+ object tmpVar = null;
+ while (index <= 3)
+ {
+ tmpVar = Session["mmsFilePath" + index];
+ if (tmpVar != null)
{
- mmsDeliveryStatus = mmsStatusResponseStream.ReadToEnd();
- mmsDeliveryStatus = mmsDeliveryStatus.Replace("-", "");
- JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
- GetDeliveryStatus status = (GetDeliveryStatus)deserializeJsonObject.Deserialize(mmsDeliveryStatus, typeof(GetDeliveryStatus));
- drawGetStatusSuccess(status.DeliveryInfoList.deliveryInfo[0].deliverystatus, status.DeliveryInfoList.resourceURL);
- mmsStatusResponseStream.Close();
+ if (File.Exists(tmpVar.ToString()))
+ {
+ File.Delete(tmpVar.ToString());
+ Session["mmsFilePath" + index] = null;
+ }
}
+
+ index++;
}
}
+ }
+
+ /// <summary>
+ /// Sends MMS by calling messaging api
+ /// </summary>
+ /// <param name="mmsAddress">string, phone number</param>
+ /// <param name="mmsMessage">string, mms message</param>
+ private void SendMultimediaMessage(string mmsAddress, string mmsMessage)
+ {
+ string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
+
+ HttpWebRequest mmsRequestObject = (HttpWebRequest)WebRequest.Create(string.Empty + this.endPoint + "/rest/mms/2/messaging/outbox");
+ mmsRequestObject.Headers.Add("Authorization", "Bearer " + this.accessToken);
+ mmsRequestObject.ContentType = "multipart/form-data; type=\"application/x-www-form-urlencoded\"; start=\"<startpart>\"; boundary=\"" + boundary + "\"\r\n";
+ mmsRequestObject.Method = "POST";
+ mmsRequestObject.KeepAlive = true;
+
+ UTF8Encoding encoding = new UTF8Encoding();
+
+ byte[] totalpostBytes = encoding.GetBytes(string.Empty);
+ string sendMMSData = "Address=" + Server.UrlEncode("tel:" + mmsAddress) + "&Subject=" + Server.UrlEncode(mmsMessage);
+
+ string data = string.Empty;
+ data += "--" + boundary + "\r\n";
+ data += "Content-Type:application/x-www-form-urlencoded;charset=UTF-8\r\nContent-Transfer-Encoding:8bit\r\nContent-ID:<startpart>\r\n\r\n" + sendMMSData + "\r\n";
+
+ totalpostBytes = this.FormMIMEParts(boundary, ref data);
+
+ byte[] byteLastBoundary = encoding.GetBytes("\r\n--" + boundary + "--\r\n");
+ int totalSize = totalpostBytes.Length + byteLastBoundary.Length;
+
+ var totalMS = new MemoryStream(new byte[totalSize], 0, totalSize, true, true);
+ totalMS.Write(totalpostBytes, 0, totalpostBytes.Length);
+ totalMS.Write(byteLastBoundary, 0, byteLastBoundary.Length);
+
+ byte[] finalpostBytes = totalMS.GetBuffer();
+ mmsRequestObject.ContentLength = finalpostBytes.Length;
+
+ Stream postStream = null;
+ try
+ {
+ postStream = mmsRequestObject.GetRequestStream();
+ postStream.Write(finalpostBytes, 0, finalpostBytes.Length);
+ }
catch (Exception ex)
{
- drawPanelForFailure(getStatusPanel, ex.ToString());
+ throw ex;
+ }
+ finally
+ {
+ if (null != postStream)
+ {
+ postStream.Close();
+ }
+ }
+
+ WebResponse mmsResponseObject = mmsRequestObject.GetResponse();
+ using (StreamReader streamReader = new StreamReader(mmsResponseObject.GetResponseStream()))
+ {
+ string mmsResponseData = streamReader.ReadToEnd();
+ JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
+ MmsResponseId deserializedJsonObj = (MmsResponseId)deserializeJsonObject.Deserialize(mmsResponseData, typeof(MmsResponseId));
+ messageIDTextBox.Text = deserializedJsonObj.id.ToString();
+ this.DrawPanelForSuccess(sendMessagePanel, deserializedJsonObj.id.ToString());
+ streamReader.Close();
}
}
- /* this function draws table for get status result */
- private void drawGetStatusSuccess(string status, string url)
+
+ /// <summary>
+ /// Form mime parts for the user input files
+ /// </summary>
+ /// <param name="boundary">string, boundary data</param>
+ /// <param name="data">string, mms message</param>
+ /// <returns>returns byte array of files</returns>
+ private byte[] FormMIMEParts(string boundary, ref string data)
{
- Table table = new Table();
- table.Font.Name = "Sans-serif";
- table.Font.Size = 9;
- table.BorderStyle = BorderStyle.Outset;
- table.Width = Unit.Pixel(650);
- TableRow rowOne = new TableRow();
- TableCell rowOneCellOne = new TableCell();
- rowOneCellOne.Font.Bold = true;
- rowOneCellOne.Text = "SUCCESS:";
- //rowOneCellOne.BorderWidth = 1;
- rowOne.Controls.Add(rowOneCellOne);
- table.Controls.Add(rowOne);
- TableRow rowTwo = new TableRow();
- TableCell rowTwoCellOne = new TableCell();
- TableCell rowTwoCellTwo = new TableCell();
- //rowTwoCellOne.BorderWidth = 1;
- rowTwoCellOne.Text = "Status: ";
- rowTwoCellOne.Font.Bold = true;
- rowTwo.Controls.Add(rowTwoCellOne);
- rowTwoCellTwo.Text = status.ToString();
- //rowTwoCellTwo.BorderWidth = 1;
- rowTwo.Controls.Add(rowTwoCellTwo);
- table.Controls.Add(rowTwo);
- TableRow rowThree = new TableRow();
- TableCell rowThreeCellOne = new TableCell();
- TableCell rowThreeCellTwo = new TableCell();
- rowThreeCellOne.Text = "ResourceURL: ";
- rowThreeCellOne.Font.Bold = true;
- //rowThreeCellOne.BorderWidth = 1;
- rowThree.Controls.Add(rowThreeCellOne);
- rowThreeCellTwo.Text = url.ToString();
- //rowThreeCellTwo.BorderWidth = 1;
- rowThree.Controls.Add(rowThreeCellTwo);
- table.Controls.Add(rowThree);
- table.BorderWidth = 2;
- table.BorderColor = Color.DarkGreen;
- table.BackColor = System.Drawing.ColorTranslator.FromHtml("#cfc");
- getStatusPanel.Controls.Add(table);
+ UTF8Encoding encoding = new UTF8Encoding();
+
+ byte[] postBytes = encoding.GetBytes(string.Empty);
+ byte[] totalpostBytes = encoding.GetBytes(string.Empty);
+
+ if (Session["mmsFilePath1"] != null)
+ {
+ postBytes = this.GetBytesOfFile(boundary, ref data, Session["mmsFilePath1"].ToString());
+ totalpostBytes = postBytes;
+ }
+
+ if (Session["mmsFilePath2"] != null)
+ {
+ if (Session["mmsFilePath1"] != null)
+ {
+ data = "--" + boundary + "\r\n";
+ }
+ else
+ {
+ data += "--" + boundary + "\r\n";
+ }
+
+ postBytes = this.GetBytesOfFile(boundary, ref data, Session["mmsFilePath2"].ToString());
+
+ if (Session["mmsFilePath1"] != null)
+ {
+ var ms2 = JoinTwoByteArrays(totalpostBytes, postBytes);
+ totalpostBytes = ms2.GetBuffer();
+ }
+ else
+ {
+ totalpostBytes = postBytes;
+ }
+ }
+
+ if (Session["mmsFilePath3"] != null)
+ {
+ if (Session["mmsFilePath1"] != null || Session["mmsFilePath2"] != null)
+ {
+ data = "--" + boundary + "\r\n";
+ }
+ else
+ {
+ data += "--" + boundary + "\r\n";
+ }
+
+ postBytes = this.GetBytesOfFile(boundary, ref data, Session["mmsFilePath3"].ToString());
+
+ if (Session["mmsFilePath1"] != null || Session["mmsFilePath2"] != null)
+ {
+ var ms2 = JoinTwoByteArrays(totalpostBytes, postBytes);
+ totalpostBytes = ms2.GetBuffer();
+ }
+ else
+ {
+ totalpostBytes = postBytes;
+ }
+ }
+
+ return totalpostBytes;
+ }
+
+ /// <summary>
+ /// Gets the bytes representation of file along with mime part
+ /// </summary>
+ /// <param name="boundary">string, boundary message</param>
+ /// <param name="data">string, mms message</param>
+ /// <param name="filePath">string, filepath</param>
+ /// <returns>byte[], representation of file in bytes</returns>
+ private byte[] GetBytesOfFile(string boundary, ref string data, string filePath)
+ {
+ UTF8Encoding encoding = new UTF8Encoding();
+ byte[] postBytes = encoding.GetBytes(string.Empty);
+ FileStream fileStream = null;
+ BinaryReader binaryReader = null;
+
+ try
+ {
+ string mmsFileName = Path.GetFileName(filePath);
+
+ fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
+ binaryReader = new BinaryReader(fileStream);
+
+ byte[] image = binaryReader.ReadBytes((int)fileStream.Length);
+
+ data += "--" + boundary + "\r\n";
+ data += "Content-Disposition:attachment;name=\"" + mmsFileName + "\"\r\n";
+ data += "Content-Type:image/gif\r\n";
+ data += "Content-ID:<" + mmsFileName + ">\r\n";
+ data += "Content-Transfer-Encoding:binary\r\n\r\n";
+
+ byte[] firstPart = encoding.GetBytes(data);
+ int newSize = firstPart.Length + image.Length;
+
+ var memoryStream = new MemoryStream(new byte[newSize], 0, newSize, true, true);
+ memoryStream.Write(firstPart, 0, firstPart.Length);
+ memoryStream.Write(image, 0, image.Length);
+
+ postBytes = memoryStream.GetBuffer();
+ }
+ catch (Exception ex)
+ {
+ throw ex;
+ }
+ finally
+ {
+ if (null != binaryReader)
+ {
+ binaryReader.Close();
+ }
+
+ if (null != fileStream)
+ {
+ fileStream.Close();
+ }
+ }
+
+ return postBytes;
+ }
+
+ /// <summary>
+ /// Invokes messaging api to send message without any attachments
+ /// </summary>
+ /// <param name="mmsAddress">string, phone number</param>
+ /// <param name="mmsMessage">string, mms message</param>
+ private void SendMessageNoAttachments(string mmsAddress, string mmsMessage)
+ {
+ string boundaryToSend = "----------------------------" + DateTime.Now.Ticks.ToString("x");
+
+ HttpWebRequest mmsRequestObject = (HttpWebRequest)WebRequest.Create(string.Empty + this.endPoint + "/rest/mms/2/messaging/outbox");
+ mmsRequestObject.Headers.Add("Authorization", "Bearer " + this.accessToken);
+ mmsRequestObject.ContentType = "multipart/form-data; type=\"application/x-www-form-urlencoded\"; start=\"<startpart>\"; boundary=\"" + boundaryToSend + "\"\r\n";
+ mmsRequestObject.Method = "POST";
+ mmsRequestObject.KeepAlive = true;
+
+ UTF8Encoding encoding = new UTF8Encoding();
+ byte[] bytesToSend = encoding.GetBytes(string.Empty);
+ string mmsParameters = "Address=" + Server.UrlEncode("tel:" + mmsAddress) + "&Subject=" + Server.UrlEncode(mmsMessage);
+
+ string dataToSend = string.Empty;
+ dataToSend += "--" + boundaryToSend + "\r\n";
+ dataToSend += "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\nContent-Transfer-Encoding: 8bit\r\nContent-Disposition: form-data; name=\"root-fields\"\r\nContent-ID: <startpart>\r\n\r\n" + mmsParameters + "\r\n";
+ dataToSend += "--" + boundaryToSend + "--\r\n";
+ bytesToSend = encoding.GetBytes(dataToSend);
+
+ int sizeToSend = bytesToSend.Length;
+ var memBufToSend = new MemoryStream(new byte[sizeToSend], 0, sizeToSend, true, true);
+ memBufToSend.Write(bytesToSend, 0, bytesToSend.Length);
+ byte[] finalData = memBufToSend.GetBuffer();
+ mmsRequestObject.ContentLength = finalData.Length;
+
+ Stream postStream = null;
+ try
+ {
+ postStream = mmsRequestObject.GetRequestStream();
+ postStream.Write(finalData, 0, finalData.Length);
+ }
+ catch (Exception ex)
+ {
+ throw ex;
+ }
+ finally
+ {
+ if (null != postStream)
+ {
+ postStream.Close();
+ }
+ }
+
+ WebResponse mmsResponseObject = mmsRequestObject.GetResponse();
+ using (StreamReader streamReader = new StreamReader(mmsResponseObject.GetResponseStream()))
+ {
+ string mmsResponseData = streamReader.ReadToEnd();
+ JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
+ MmsResponseId deserializedJsonObj = (MmsResponseId)deserializeJsonObject.Deserialize(mmsResponseData, typeof(MmsResponseId));
+ messageIDTextBox.Text = deserializedJsonObj.id.ToString();
+ this.DrawPanelForSuccess(sendMessagePanel, deserializedJsonObj.id.ToString());
+ streamReader.Close();
+ }
}
- /* this function is called when user click on get status button */
- protected void getStatusButton_Click(object sender, EventArgs e)
+ /// <summary>
+ /// This function adds two byte arrays
+ /// </summary>
+ /// <param name="firstByteArray">first array of bytes</param>
+ /// <param name="secondByteArray">second array of bytes</param>
+ /// <returns>returns MemoryStream after joining two byte arrays</returns>
+ private static MemoryStream JoinTwoByteArrays(byte[] firstByteArray, byte[] secondByteArray)
{
- getMmsDeliveryStatus();
+ int newSize = firstByteArray.Length + secondByteArray.Length;
+ var ms = new MemoryStream(new byte[newSize], 0, newSize, true, true);
+ ms.Write(firstByteArray, 0, firstByteArray.Length);
+ ms.Write(secondByteArray, 0, secondByteArray.Length);
+ return ms;
}
+
+ #endregion
}
-/* The following are data structures used for the application */
-public class mmsResponseId
+#region Data Structures
+
+/// <summary>
+/// MmsResponseId object
+/// </summary>
+public class MmsResponseId
{
- public string id;
+ /// <summary>
+ /// Gets or sets the value of id
+ /// </summary>
+ public string id
+ {
+ get;
+ set;
+ }
}
+/// <summary>
+/// Response of GetMmsDelivery
+/// </summary>
public class GetDeliveryStatus
{
- public DeliveryInfoList DeliveryInfoList = new DeliveryInfoList();
+ /// <summary>
+ /// Gets or sets the value of DeliveryInfoList
+ /// </summary>
+ public DeliveryInfoList DeliveryInfoList
+ {
+ get;
+ set;
+ }
}
+
+/// <summary>
+/// DeliveryInfoList object
+/// </summary>
public class DeliveryInfoList
{
- public string resourceURL;
- public List<deliveryInfo> deliveryInfo { get; set; }
+ /// <summary>
+ /// Gets or sets the value of resourceURL
+ /// </summary>
+ public string resourceURL
+ {
+ get;
+ set;
+ }
+
+ /// <summary>
+ /// Gets or sets the value of deliveryInfo
+ /// </summary>
+ public List<deliveryInfo> deliveryInfo
+ {
+ get;
+ set;
+ }
}
+/// <summary>
+/// deliveryInfo object
+/// </summary>
public class deliveryInfo
{
- public string id { get; set; }
- public string address { get; set; }
- public string deliverystatus { get; set; }
+ /// <summary>
+ /// Gets or sets the value of id
+ /// </summary>
+ public string id
+ {
+ get;
+ set;
+ }
+
+ /// <summary>
+ /// Gets or sets the value of address
+ /// </summary>
+ public string address
+ {
+ get;
+ set;
+ }
+
+ /// <summary>
+ /// Gets or sets the value of deliveryStatus
+ /// </summary>