Skip to content

Instantly share code, notes, and snippets.

@shyampurk
Last active May 9, 2016 16:07
Show Gist options
  • Save shyampurk/b9bc9b3b951c72c494990a0b599f7087 to your computer and use it in GitHub Desktop.
Save shyampurk/b9bc9b3b951c72c494990a0b599f7087 to your computer and use it in GitHub Desktop.
public static List<decimal> arrUSDEUR = new List<decimal>();// globally declaring list for USDEUR
public static List<decimal> arrUSDAUD = new List<decimal>();// globally declaring list for USDAUD
public static List<decimal> arrUSDCNY = new List<decimal>();// globally declaring list for USDCNY
public static List<decimal> arrUSDINR = new List<decimal>();// globally declaring list for USDINR
public static Dictionary<string, List<decimal>> ArrayDictMap = new Dictionary<string, List<decimal>>()
{
{ "USDEUR", arrUSDEUR },
{ "USDAUD", arrUSDAUD },
{ "USDCNY", arrUSDCNY },
{ "USDINR", arrUSDINR },
};
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Quartz;// For Schedule Task
using Quartz.Impl;
using Quartz.Impl.Triggers;
namespace CurrencyTrack
{
public class JobScheduler : ScheduledTask
{
/// <summary>
/// The scheduleTask is called at an regular interval of 30 seconds.
/// </summary>
public static void Start()
{
IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
scheduler.Start();
IJobDetail job = JobBuilder.Create<ScheduledTask>().Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartNow()
.WithSimpleSchedule
(s =>
s.WithIntervalInMinutes(60)
.RepeatForever()
).Build();
scheduler.ScheduleJob(job, trigger);
}// End method Start()
}// End JobScheduler
}
var sendRequest = function(p_name,p_status){
pubnub.publish({
channel : 'appRequestChannel',
message : '{\"name\":\"' + p_name + '\",\"requestType\":'+ p_status +'}'
});
}
var updatePrice = function(p_rcvmessage){
var p_message = JSON.parse(p_rcvmessage);
if(p_message.responseType == 0){
if(counterDisplayState[p_message.name] == true){
$('#' + p_message['name']).html(parseFloat(p_message['value']).toFixed(2))
valueChange(p_message['name'],p_message['direction'],parseFloat(p_message['magnitude']).toFixed(5))
var date = new Date(p_message['time'] * 1000);
var timeString = date.toLocaleTimeString();
$('#' + p_message['name'] + '-time' ).html(timeString);
}
else{
if(trend_graph[p_message.name] != null){
valueChange(p_message.name,p_message['direction'],parseFloat(p_message['magnitude']).toFixed(5))
trend_graph[p_message.name].shift();
trend_graph[p_message.name].push(p_message.value);
$('#'+p_message.name).sparkline(trend_graph[p_message.name])
var date = new Date(p_message['time'] * 1000);
var timeString = date.toLocaleTimeString();
$('#' + p_message['name'] + '-time' ).html(timeString);
$('[data-index='+p_message.name+']').text(BUTTON_TXT_COUNTER);
}
}
}
else if(p_message.responseType == 1){
if(counterDisplayState[p_message.name] == false){
trend_graph[p_message['name']] = p_message['value'];
$('#'+p_message.name).sparkline(trend_graph[p_message.name])
$('[data-index='+p_message.name+']').text(BUTTON_TXT_COUNTER);
}
}
};
var pubnub = PUBNUB.init({
publish_key: pub_key,
subscribe_key: sub_key
});
$(document ).ready(function() {
pubnub.subscribe({
channel: 'exchangedata',
message: updatePrice
});
sendRequest("EUR",0);
sendRequest("AUD",0);
sendRequest("CNY",0);
sendRequest("INR",0);
$('button').click(function(){
if($(this).text() == BUTTON_TXT_TREND){
//If the Button text is 'Trend' , send request to fetch historical values
$(this).text('Loading..');
sendRequest($(this).data('index'),1);
counterDisplayState[$(this).data('index')] = false;
} else if($(this).text() == BUTTON_TXT_COUNTER) {
//Change the text
counterDisplayState[$(this).data('index')] = true;
$(this).text(BUTTON_TXT_TREND);
sendRequest($(this).data('index'),0);
}
});
});
{"name": "EUR" , "requestType":1}
{"responseType":0,"name":"EUR","value":1.33,"direction":"+","magnitude":0.00345,"time":1412322567}
{"responseType":1,"name":"EUR","value": [1.36,1.34,1.37,1.28,1.33] ,"direction":"+","magnitude":0.00365,"time":1412322567}
/// <summary>
/// Publish Latest Counter data in response to app request = 0
/// </summary>
/// <param name="pCurr">Currency Name</param>
void PublishCounter(string pCurr)
{
string trendJSON = string.Empty;
string currKey = "USD" + pCurr;
int arrayCount = Global.ArrayDictMap[currKey].Count;
if (arrayCount > 0)
{
CurrencyData currencyDataPublish = new CurrencyData();
currencyDataPublish.name = pCurr;
currencyDataPublish.value = ArrayDictMap[currKey][arrayCount - 1].ToString();
currencyDataPublish.time = LastTimeStamp;
try
{
if (Global.ArrayDictMap[currKey][arrayCount - 1] > Global.ArrayDictMap[currKey][arrayCount - 2])
{
currencyDataPublish.direction = "+";
}
else
{
currencyDataPublish.direction = "-";
}
currencyDataPublish.magnitude = Math.Abs(Global.ArrayDictMap[currKey][arrayCount - 1] - Global.ArrayDictMap[currKey][arrayCount - 2]);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine(e.ToString());
Console.WriteLine("Can be ignored if list has one or less elements");
currencyDataPublish.direction = "+";
currencyDataPublish.magnitude = Global.ArrayDictMap[currKey][arrayCount - 1];
}
trendJSON = JsonConvert.SerializeObject(currencyDataPublish);
_pubnub.Publish<string>(respChannel, trendJSON, DisplayReturnMessage, DisplayErrorMessage);
}
}//End of PublishCounter
/// <summary>
/// Publish Trend data in response to app request = 1
/// </summary>
/// <param name="pCurr">Currency Name</param>
void PublishTrend(string pCurr)
{
string trendJSON = string.Empty;
string currKey = "USD" + pCurr;
CurrencyTrendData currencyDataPublish = new CurrencyTrendData();
currencyDataPublish.name = pCurr;
currencyDataPublish.value = ArrayDictMap[currKey];
currencyDataPublish.time = LastTimeStamp;
trendJSON = JsonConvert.SerializeObject(currencyDataPublish);
_pubnub.Publish<string>(respChannel, trendJSON, DisplayReturnMessage, DisplayErrorMessage);
}//End of PublishTrend
void PNInit()
{
_pubnub = new Pubnub(System.Web.Configuration.WebConfigurationManager.AppSettings["PNPubKey"], System.Web.Configuration.WebConfigurationManager.AppSettings["PNSubKey"]);
}
void StoreAndPublishCurrencyData(string currencyLabel, Dictionary<string, decimal> currencyObj , int TimeStamp )
{
int arrayCount = 0;
bool isSameValue = false;
//Get the count of historical values stored
arrayCount = Global.ArrayDictMap[currencyLabel].Count;// getting the length of an array(for USDEUR, USDAUD, USDCNY, USDINR)
if (arrayCount >= 1)
{
isSameValue = Global.ArrayDictMap[currencyLabel][arrayCount - 1] == currencyObj[currencyLabel];
}
if (!isSameValue)
{
if (arrayCount >= 30)
{
Global.ArrayDictMap[currencyLabel].RemoveAt(0);
}
CurrencyData currencyDataPublish = new CurrencyData();
currencyDataPublish.name = currencyLabel.Substring(3);
currencyDataPublish.value = currencyObj[currencyLabel].ToString();
currencyDataPublish.time = TimeStamp;
try {
if (currencyObj[currencyLabel] > Global.ArrayDictMap[currencyLabel][arrayCount - 1])
{
currencyDataPublish.direction = "+";
}
else
{
currencyDataPublish.direction = "-";
}
currencyDataPublish.magnitude = Math.Abs(currencyObj[currencyLabel] - Global.ArrayDictMap[currencyLabel][arrayCount - 1]);
}
catch(ArgumentOutOfRangeException e)
{
Console.WriteLine(e.ToString());
Console.WriteLine("Can be ignored if list has one or less elements");
currencyDataPublish.direction = "+";
currencyDataPublish.magnitude = currencyObj[currencyLabel];
}
Global.ArrayDictMap[currencyLabel].Add(currencyObj[currencyLabel]);
string json_Publish = JsonConvert.SerializeObject(currencyDataPublish);
Global._pubnub.Publish<string>(strCHANNELNAME, json_Publish, DisplayReturnMessage, DisplayErrorMessage);
}
}
const string url = "http://apilayer.net/api/live?access_key=1a142e188a7b4a43e404eee3bbf52378&currencies=EUR,AUD,CNY,INR&source=USD&format=1"; // URL of currencylayer site
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment