/
NoppaImpl.cs
101 lines (86 loc) · 3.38 KB
/
NoppaImpl.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NoppaLib.DataModel;
namespace NoppaLib
{
public class NoppaImpl
{
private static readonly int _timeout = 35000; /* 5secs */
private static Lazy<NoppaImpl> _instance = new Lazy<NoppaImpl>( () => new NoppaImpl() );
public static NoppaImpl GetInstance()
{
return _instance.Value;
}
#region API Call methods
private Task<HttpWebResponse> CallAPIAsync(string query)
{
var taskComplete = new TaskCompletionSource<HttpWebResponse>();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);
System.Diagnostics.Debug.WriteLine("Query: {0}", request.RequestUri.ToString());
request.Method = "GET";
request.BeginGetResponse(asyncResponse =>
{
try
{
HttpWebRequest responseRequest = (HttpWebRequest)asyncResponse.AsyncState;
HttpWebResponse response = responseRequest.EndGetResponse(asyncResponse) as HttpWebResponse;
taskComplete.TrySetResult(response);
}
catch (WebException webExc)
{
taskComplete.TrySetException(webExc);
}
}, request);
return taskComplete.Task;
}
public async Task<T> GetObject<T>(Cache.PolicyLevel policy, string format, params object[] args) where T : class
{
HttpWebResponse response;
string query = APIConfigHolder.Url + String.Format(format, args);
// Check to see if the cache contains the requested query.
if (Cache.Exists(query) && policy != Cache.PolicyLevel.Reload)
{
return JsonConvert.DeserializeObject<T>(Cache.Get(query));
}
var timeoutCancel = new CancellationTokenSource();
try
{
Task<HttpWebResponse> responseTask = CallAPIAsync(query);
/* Handle the timeout */
var timeoutTask = Task.Delay(_timeout, timeoutCancel.Token);
var completeTask = await Task.WhenAny(responseTask, timeoutTask);
if (completeTask == responseTask)
{
timeoutCancel.Cancel();
response = await responseTask.ConfigureAwait(false);
}
else
{
/* Timeout */
await timeoutTask;
System.Diagnostics.Debug.WriteLine("NoppaApiClient: Timed out ({0} ms)", _timeout);
return null;
}
}
catch (WebException webExc)
{
/* Caught exception */
System.Diagnostics.Debug.WriteLine("NoppaApiClient: Caught exception: {0}", webExc.Message);
timeoutCancel.Cancel();
return null;
}
using (var sr = new StreamReader(response.GetResponseStream()))
{
string json = await sr.ReadToEndAsync();
Cache.Add(query, json, policy);
return JsonConvert.DeserializeObject<T>(json);
}
}
#endregion
}
}