/
ServiceRequest.cs
76 lines (71 loc) · 2.35 KB
/
ServiceRequest.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using AlbertoMonteiroWP7Tools.Controls;
using Newtonsoft.Json;
using QCon12.Mobile.Cache;
namespace QCon12.Mobile.Requests
{
public abstract class ServiceRequest<T>
{
protected readonly CacheContext cacheContext;
protected readonly string controller;
protected string additional;
protected int count = 0;
protected JsonSerializerSettings settings;
#if DEBUG
protected string URL = @"http://192.168.25.2/qcon12/api/";
#else
protected string URL = @"http://qcon12sp.azurewebsites.net/api/";
#endif
protected ServiceRequest(string controller = "")
{
settings = new JsonSerializerSettings();
this.controller = controller;
cacheContext = new CacheContext();
}
public async Task<List<T>> BaseList(int skip = 0)
{
if (skip != 0)
additional = "/?$skip=" + skip;
return await DownloadAndDeserialize<List<T>>();
}
public async Task<T> BaseGet(int id)
{
additional = "/" + id;
return await DownloadAndDeserialize<T>();
}
protected async Task<TR> DownloadAndDeserialize<TR>()
{
var instance = default(TR);
GlobalLoading.Instance.PushLoading();
var keepTrying = true;
while (keepTrying)
{
var request = new WebClient();
var uri = new Uri(URL + controller + additional);
try
{
var str = await request.DownloadStringTaskAsync(uri);
var serializer = JsonSerializer.Create(settings);
using (var stringReader = new StringReader(str))
{
instance = serializer.Deserialize<TR>(new JsonTextReader(stringReader));
stringReader.Close();
keepTrying = false;
}
}
catch (Exception e)
{
if (count++ < 3)
keepTrying = false;
}
}
GlobalLoading.Instance.PopLoading();
return instance;
}
}
}