Skip to content

Instantly share code, notes, and snippets.

@t2-support-gists
Last active December 15, 2015 02:49
Show Gist options
  • Select an option

  • Save t2-support-gists/5189713 to your computer and use it in GitHub Desktop.

Select an option

Save t2-support-gists/5189713 to your computer and use it in GitHub Desktop.
ADS 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 [email protected]<mailto:[email protected]>
******************************************************************************************
AT&T API Platform Samples - Ad App 1
-------------------------------------
This application demonstrates the usage of Advertisement API of AT&T platform.
The Advertisement API is a service that returns advertisements enabling the
developer to insert the advertisements into their application.
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 developer site 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 developer site with the proper services and endpoints, depending on the type of
client-side application (autonomous/non-autonomous).
To register an application, go to https://developer.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 Ads 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.
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/ads/app1/ folder.
In order to run the sample application, type in'http://IIS_HOSTNAME/ads/app1/Default.aspx'.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Ad_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 [email protected]
-->
<!--[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">
<!--<![endif]-->
<head>
<title>AT&amp;T Sample Application - Advertisement</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" />
<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>
</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 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 - Advertisement</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">
<h2>
Feature 1: Get Advertisement</h2>
<div id="getAds">
<label>
Category</label>
<select name="category" id="category" runat="server">
<option value="auto" selected="selected">auto</option>
<option value="business">business</option>
<option value="chat">chat</option>
<option value="communication">communication</option>
<option value="community">community</option>
<option value="entertainment">entertainment</option>
<option value="finance">finance</option>
<option value="games">games</option>
<option value="health">health</option>
<option value="local">local</option>
<option value="maps">maps</option>
<option value="medical">medical</option>
<option value="movies">movies</option>
<option value="music">music</option>
<option value="news">news</option>
<option value="other">other</option>
<option value="personals">personals</option>
<option value="photos">photos</option>
<option value="shopping">shopping</option>
<option value="social">social</option>
<option value="sports">sports</option>
<option value="technology">technology</option>
<option value="tools">tools</option>
<option value="travel">travel</option>
<option value="tv">tv</option>
<option value="video">video</option>
<option value="weather">weather</option>
</select>
<div class="inputSeperator">
</div>
<label>
MMA Size:</label>
<select name="MMA" id="MMA" runat="server">
<option value=""></option>
<option value="120 x 20">120 x 20</option>
<option value="168 x 28">168 x 28</option>
<option value="216 x 36">216 x 36</option>
<option value="300 x 50">300 x 50</option>
<option value="300 x 250">300 x 250</option>
<option value="320 x 50">320 x 50</option>
</select>
<div class="inputSeperator">
</div>
<label>
Age Group:</label>
<select name="ageGroup" id="ageGroup" runat="server">
<option value="" selected="selected"></option>
<option value="1-13">1-13</option>
<option value="14-25" >14-25</option>
<option value="26-35">26-35</option>
<option value="36-55">36-55</option>
<option value="55-100">55-100</option>
</select>
<div class="inputSeperator">
</div>
<label>
Premium:</label>
<select name="Premium" id="Premium" runat="server">
<option value=""></option>
<option value="0">NonPremium</option>
<option value="1">Premium Only</option>
<option value="2">Both</option>
</select>
<div class="inputSeperator">
</div>
<label>
Gender:</label>
<select name="gender" id="gender" runat="server">
<option value="" selected="selected"></option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
<div class="inputSeperator">
</div>
<label>
Over 18 Ad Content:</label>
<select name="over18" id="over18" runat="server">
<option value=""></option>
<option value="0">Deny Over 18</option>
<option value="2">Only Over 18</option>
<option value="3">Allow All Ads</option>
</select>
<div class="inputSeperator">
</div>
<label>
Zip Code:&nbsp;</label><input runat="server" placeholder="Zip Code" type="text" id="zipCode"
name="zipCode" />
<div class="inputSeperator">
</div>
<label>
City:&nbsp;</label><input runat="server" placeholder="City" type="text" id="city"
name="city" />
<div class="inputSeperator">
</div>
<label>
Area Code:&nbsp;</label><input runat="server" placeholder="Area Code" type="text"
id="areaCode" name="areaCode" />
<div class="inputSeperator">
</div>
<label>
Country:&nbsp;</label><input runat="server" placeholder="Country" type="text" id="country"
name="country" />
<div class="inputSeperator">
</div>
<label>
Latitude:&nbsp;</label><input runat="server" placeholder="Latitude" type="text" id="latitude"
name="latitude" />
<div class="inputSeperator">
</div>
<label>
Longitude:&nbsp;</label><input runat="server" placeholder="Longitude" type="text"
id="longitude" name="longitude" />
<div class="inputSeperator">
</div>
<label>
Keywords:&nbsp;</label><input runat="server" placeholder="Keywords" type="text" id="keywords"
name="keywords" />
<div class="inputSeperator">
</div>
<button type="submit" name="btnGetAds" runat="server" onserverclick="BtnGetADS_Click">
Get Advertisement</button>
</div>
<!-- end of getAds -->
<% if (!string.IsNullOrEmpty(getAdsSuccessResponse))
{ %>
<div class="successWide">
<strong>SUCCESS:</strong><br /><%= getAdsSuccessResponse%>
</div>
<% if (adRequestResponse != null && adRequestResponse.AdsResponse != null && adRequestResponse.AdsResponse.Ads != null)
{ %>
<table class="kvp" id="kvp">
<thead>
<tr>
<th>
Parameter
</th>
<th>
Value
</th>
</tr>
</thead>
<tbody>
<% if (!string.IsNullOrEmpty(adRequestResponse.AdsResponse.Ads.Type))
{%>
<tr>
<td data-value="Parameter">
Type
</td>
<td data-value="Value">
<%= adRequestResponse.AdsResponse.Ads.Type%>
</td>
</tr>
<% } %>
<% if (!string.IsNullOrEmpty(adRequestResponse.AdsResponse.Ads.ClickUrl))
{%>
<tr>
<td data-value="Parameter">
ClickUrl
</td>
<td data-value="Value">
<%= adRequestResponse.AdsResponse.Ads.ClickUrl%>
</td>
</tr>
<% } %>
<% if ( adRequestResponse.AdsResponse.Ads.ImageUrl != null && !string.IsNullOrEmpty(adRequestResponse.AdsResponse.Ads.ImageUrl.Image))
{%>
<tr>
<td data-value="Parameter">
ImageUrl
</td>
<td data-value="Value">
<%= adRequestResponse.AdsResponse.Ads.ImageUrl.Image %>
</td>
</tr>
<% } %>
<% if (!string.IsNullOrEmpty(adRequestResponse.AdsResponse.Ads.Text))
{%>
<tr>
<td data-value="Parameter">
Text
</td>
<td data-value="Value">
<%= adRequestResponse.AdsResponse.Ads.Text %>
</td>
</tr>
<% } %>
<% if (!string.IsNullOrEmpty(adRequestResponse.AdsResponse.Ads.Content))
{%>
<tr>
<td data-value="Parameter">
Content
</td>
<td data-value="Value">
<%= adRequestResponse.AdsResponse.Ads.Content %>
</td>
</tr>
<% } %>
</tbody>
</table>
<%if ( ((adRequestResponse.AdsResponse.Ads.ImageUrl != null) &&
(!string.IsNullOrEmpty(adRequestResponse.AdsResponse.Ads.ImageUrl.Image))) ||
!string.IsNullOrEmpty(adRequestResponse.AdsResponse.Ads.Text))
{%>
<asp:HyperLink ID="hplImage" runat="server" Target="_blank"></asp:HyperLink>
<%} %>
<%} %>
<%} %>
<% if (!string.IsNullOrEmpty(getAdsErrorResponse))
{ %>
<div class="errorWide">
<strong>ERROR:</strong>
<br />
<%=getAdsErrorResponse%>
</div>
<% } %>
<!-- SAMPLE APP CONTENT ENDS HERE! -->
</div>
<!-- end of formContainer -->
</div>
<!-- end of formBox -->
</div>
<!-- end of content -->
<!-- end of formBox -->
<!-- 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://developer.att.com/"
target="_blank">https://developer.att.com</a>
<br />
For more information contact <a href="mailto:[email protected]">[email protected]</a>
<br />
<br />
&copy; 2014 AT&amp;T Intellectual Property. All rights reserved. <a href="https://developer.att.com/"
target="_blank">https://developer.att.com</a>
</p>
</div>
<!-- end of footer -->
</div>
<!-- end of page_container -->
</form>
</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 [email protected]
// </copyright>
#region References
using System;
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;
#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 Refresh Token
/// </summary>
Refresh_Token
}
/// <summary>
/// This application demonstrates the usage of Advertisement API of AT&T platform.
/// The Advertisement API is a service that returns advertisements enabling the developer to insert the advertisements into their application.
/// </summary>
public partial class Ad_App1 : System.Web.UI.Page
{
#region Instance Variables
/// <summary>
/// Application parameters.
/// </summary>
private string apiKey, secretKey, endPoint, scope, bypassSSL;
/// <summary>
/// Access token file path
/// </summary>
private string accessTokenFilePath;
/// <summary>
/// OAuth access token
/// </summary>
private string accessToken;
/// <summary>
/// OAuth refresh token
/// </summary>
private string refreshToken;
/// <summary>
/// Expirytimes of refresh and access tokens
/// </summary>
private string refreshTokenExpiryTime, accessTokenExpiryTime;
/// <summary>
/// No of hours in which refresh token expires.
/// </summary>
private int refreshTokenExpiresIn;
/// <summary>
/// UDID for Ad tracking purpose.
/// </summary>
private string udid;
/// <summary>
/// Specifies the AD type.
/// </summary>
private string AdType = null;
public string getAdsSuccessResponse = string.Empty;
public string getAdsErrorResponse = string.Empty;
public AdsResponseObject adRequestResponse = null;
#endregion
protected void BtnGetADS_Click(object sender, EventArgs e)
{
this.GetAds();
}
/// <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/v4/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 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 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";
}
}
private void GetAds()
{
try
{
bool ableToGetAccessToken = this.ReadAndGetAccessToken(ref getAdsErrorResponse);
if (ableToGetAccessToken)
{
string adsResponse;
string queryString = this.BuildQueryParameterString();
HttpWebRequest adsRequest = (HttpWebRequest)System.Net.WebRequest.Create(string.Empty + this.endPoint + "/rest/1/ads?" + queryString);
adsRequest.Headers.Add("Authorization", "Bearer " + this.accessToken);
if (string.IsNullOrEmpty(this.udid))
{
adsRequest.Headers.Add("UDID", Guid.NewGuid().ToString());
}
else
{
adsRequest.Headers.Add("UDID", this.udid);
}
adsRequest.UserAgent = Request.UserAgent;
adsRequest.Accept = "application/json";
adsRequest.Method = "GET";
HttpWebResponse adsResponseObject = (HttpWebResponse)adsRequest.GetResponse();
using (StreamReader adResponseStream = new StreamReader(adsResponseObject.GetResponseStream()))
{
adsResponse = adResponseStream.ReadToEnd();
JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
adRequestResponse = (AdsResponseObject)deserializeJsonObject.Deserialize(adsResponse, typeof(AdsResponseObject));
if (null != adRequestResponse && null != adRequestResponse.AdsResponse && null != adRequestResponse.AdsResponse.Ads)
{
if (adRequestResponse.AdsResponse.Ads.ImageUrl != null && !string.IsNullOrEmpty(adRequestResponse.AdsResponse.Ads.ImageUrl.Image))
{
hplImage.ImageUrl = adRequestResponse.AdsResponse.Ads.ImageUrl.Image;
}
if (!string.IsNullOrEmpty(adRequestResponse.AdsResponse.Ads.Text))
{
hplImage.ImageUrl = string.Empty;
hplImage.Text = adRequestResponse.AdsResponse.Ads.Text;
}
if (!string.IsNullOrEmpty(adRequestResponse.AdsResponse.Ads.ClickUrl))
{
hplImage.NavigateUrl = adRequestResponse.AdsResponse.Ads.ClickUrl;
}
getAdsSuccessResponse = " ";
}
else
{
getAdsSuccessResponse = "No ads returned";
}
adResponseStream.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";
}
getAdsErrorResponse = errorResponse + Environment.NewLine + we.Message;
}
catch (Exception ex)
{
getAdsErrorResponse = ex.Message;
}
}
/// <summary>
/// Builds query string based on user input.
/// </summary>
/// <returns>string; query string to be passed along with API Request.</returns>
private string BuildQueryParameterString()
{
string queryParameter = string.Empty;
queryParameter = "Category=" + category.Value;
if (!string.IsNullOrEmpty(gender.Value))
{
queryParameter += "&Gender=" + gender.Value;
}
if (!string.IsNullOrEmpty(zipCode.Value))
{
queryParameter += "&ZipCode=" + zipCode.Value;
}
if (!string.IsNullOrEmpty(areaCode.Value))
{
queryParameter += "&AreaCode=" + areaCode.Value;
}
if (!string.IsNullOrEmpty(city.Value))
{
queryParameter += "&City=" + city.Value;
}
if (!string.IsNullOrEmpty(country.Value))
{
queryParameter += "&Country=" + country.Value;
}
if (!string.IsNullOrEmpty(longitude.Value))
{
queryParameter += "&Longitude=" + longitude.Value;
}
if (!string.IsNullOrEmpty(latitude.Value))
{
queryParameter += "&Latitude=" + latitude.Value;
}
if (!string.IsNullOrEmpty(MMA.Value))
{
string[] dimensions = Regex.Split(MMA.Value, " x ");
queryParameter += "&MaxWidth=" + dimensions[0];
queryParameter += "&MaxHeight=" + dimensions[0];
queryParameter += "&MinHeight=" + dimensions[1];
queryParameter += "&MinWidth=" + dimensions[1];
}
if (!string.IsNullOrEmpty(this.AdType))
{
queryParameter += "&Type=" + this.AdType;
}
if (!string.IsNullOrEmpty(ageGroup.Value))
{
queryParameter += "&AgeGroup=" + ageGroup.Value;
}
if (!string.IsNullOrEmpty(over18.Value))
{
queryParameter += "&Over18=" + over18.Value;
}
if (!string.IsNullOrEmpty(keywords.Value))
{
queryParameter += "&Keywords=" + keywords.Value;
}
if (!string.IsNullOrEmpty(Premium.Value))
{
queryParameter += "&Premium=" + Premium.Value;
}
return queryParameter;
}
protected void Page_Load(object sender, EventArgs e)
{
BypassCertificateError();
this.ReadConfigFile();
hplImage.ImageUrl = string.Empty;
hplImage.Text = string.Empty;
}
private static void BypassCertificateError()
{
string bypassSSL = ConfigurationManager.AppSettings["IgnoreSSL"];
if ((!string.IsNullOrEmpty(bypassSSL))
&& (string.Equals(bypassSSL, "true", StringComparison.OrdinalIgnoreCase)))
{
ServicePointManager.ServerCertificateValidationCallback +=
delegate(Object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
};
}
}
private bool ReadConfigFile()
{
this.apiKey = ConfigurationManager.AppSettings["apiKey"];
if (string.IsNullOrEmpty(this.apiKey))
{
getAdsErrorResponse = "apiKey is not defined in configuration file";
return false;
}
this.secretKey = ConfigurationManager.AppSettings["secretKey"];
if (string.IsNullOrEmpty(this.secretKey))
{
getAdsErrorResponse = "secretKey is not defined in configuration file";
return false;
}
this.endPoint = ConfigurationManager.AppSettings["endPoint"];
if (string.IsNullOrEmpty(this.endPoint))
{
getAdsErrorResponse = "endPoint is not defined in configuration file";
return false;
}
this.scope = ConfigurationManager.AppSettings["scope"];
if (string.IsNullOrEmpty(this.scope))
{
this.scope = "ADS";
}
this.udid = ConfigurationManager.AppSettings["udid"];
this.accessTokenFilePath = ConfigurationManager.AppSettings["AccessTokenFilePath"];
if (string.IsNullOrEmpty(this.accessTokenFilePath))
{
this.accessTokenFilePath = "~\\AdsSApp1AccessToken.txt";
}
string refreshTokenExpires = ConfigurationManager.AppSettings["refreshTokenExpiresIn"];
if (!string.IsNullOrEmpty(refreshTokenExpires))
{
this.refreshTokenExpiresIn = Convert.ToInt32(refreshTokenExpires);
}
else
{
this.refreshTokenExpiresIn = 24;
}
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
}
return true;
}
/// <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
}
}
#region Access Token Data Structure
/// <summary>
/// AccessTokenResponse Object, returned upon calling get auth token api.
/// </summary>
public class AccessTokenResponse
{
/// <summary>
/// Gets or sets the value of access_token
/// </summary>
public string access_token
{
get;
set;
}
/// <summary>
/// Gets or sets the value of refresh_token
/// </summary>
public string refresh_token
{
get;
set;
}
/// <summary>
/// Gets or sets the value of expires_in
/// </summary>
public string expires_in
{
get;
set;
}
}
#endregion
#region AdResponse Data Structures
/// <summary>
/// Object that containes the link to the image of the advertisement and tracking Url.
/// </summary>
public class ImageUrlResponse
{
/// <summary>
/// Gets or sets the value of Image.
/// This parameter returns the link to the image of the advertisement.
/// </summary>
public string Image { get; set; }
/// <summary>
/// Gets or sets the value of Track.
/// This parameter contains the pixel tracking URL.
/// </summary>
public string Track { get; set; }
}
/// <summary>
/// Container structure for the advertisement details
/// </summary>
public class Ad
{
/// <summary>
/// Gets or sets the value of Text.
/// Specifies the type of advertisement.
/// </summary>
public string Type { get; set; }
/// <summary>
/// Gets or sets the value of ClickUrl.
/// This parameter contains the click URLs. It returns all the possible sizes available.
/// For SMS ads, the URL is shortened to 35-40 characters.
/// </summary>
public string ClickUrl { get; set; }
/// <summary>
/// Gets or sets the value of ImageUrl.
/// This parameter returns the link to the image of the advertisement.
/// </summary>
public ImageUrlResponse ImageUrl { get; set; }
/// <summary>
/// Gets or sets the value of Text.
/// Any ad text(either independent or below the ad)
/// </summary>
public string Text { get; set; }
/// <summary>
/// Gets or sets the value of TrackUrl.
/// This parameter contains the pixel tracking URL.
/// </summary>
public string TrackUrl { get; set; }
/// <summary>
/// Gets or sets the value of Content
/// All of the ad content is placed in this node as is from 3rd party.
/// </summary>
public string Content { get; set; }
}
/// <summary>
/// Container structure for AdResponse
/// </summary>
public class AdResponse
{
/// <summary>
/// Gets or sets the value of Ads
/// Advertisement details
/// </summary>
public Ad Ads { get; set; }
}
/// <summary>
/// High level container structure for AdsResponse
/// </summary>
public class AdsResponseObject
{
/// <summary>
/// AdsResponse object
/// </summary>
public AdResponse AdsResponse { get; set; }
}
#endregion

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "App1", ".", "{02FD2C21-3379-48B0-B3C1-23BB1A086D9E}"
ProjectSection(WebsiteProperties) = preProject
TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.0"
Debug.AspNetCompiler.VirtualPath = "/App1"
Debug.AspNetCompiler.PhysicalPath = "D:\Wdev SVN\Code\MSRestfulSampleApplications\Csharp\Ad\App1\"
Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\App1\"
Debug.AspNetCompiler.Updateable = "true"
Debug.AspNetCompiler.ForceOverwrite = "true"
Debug.AspNetCompiler.FixedNames = "false"
Debug.AspNetCompiler.Debug = "True"
Release.AspNetCompiler.VirtualPath = "/App1"
Release.AspNetCompiler.PhysicalPath = "D:\Wdev SVN\Code\MSRestfulSampleApplications\Csharp\Ad\App1\"
Release.AspNetCompiler.TargetPath = "PrecompiledWeb\App1\"
Release.AspNetCompiler.Updateable = "true"
Release.AspNetCompiler.ForceOverwrite = "true"
Release.AspNetCompiler.FixedNames = "false"
Release.AspNetCompiler.Debug = "False"
VWDPort = "63939"
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{02FD2C21-3379-48B0-B3C1-23BB1A086D9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{02FD2C21-3379-48B0-B3C1-23BB1A086D9E}.Debug|Any CPU.Build.0 = Debug|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
<?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"/>
</system.web>
<appSettings>
<!-- Set this parameter value to "true", if you need to bypass the SSL certificate. Default FALSE -->
<add key="IgnoreSSL" value="false"/>
<!-- This is mandatory key and value should be equal
to Ads Service registered application 'API key'
example: value=""-->
<add key="apikey" value=""/>
<!-- This is mandatory key and value should be equal
to Ads Service registered application 'Secret key'
example: value=""-->
<add key="secretkey" value=""/>
<!-- This is mandatory key and value should be equal
to https://api.att.com for production environment-->
<add key="endPoint" value="" />
<!-- This is mandatory key and value should be equal
to Ads Service registered application scope-->
<add key="scope" value=""/>
<!-- This is mandatory key and value should be equal to Ads UDID-->
<add key="udid" value=""/>
<!-- This is an 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 and file defined.
If the key is not defined, AdsApp1AccessToken.txt will be created
at root folder, so, make sure to give write access to the root folder.
example: value="AdsApp1AccessToken.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=""/>
<!-- These are optional keys. the values are used for hyperlink -->
<add key="SourceLink" value="#"/>
<add key="DownloadLink" value="#"/>
<add key="HelpLink" value="#"/>
</appSettings>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment