This repository was archived by the owner on Nov 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathRestClientExtensions.cs
More file actions
114 lines (104 loc) · 4.66 KB
/
Copy pathRestClientExtensions.cs
File metadata and controls
114 lines (104 loc) · 4.66 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
/* Code below modified from a version taken from Laurent Kempé's blog
* http://www.laurentkempe.com/post/Extending-existing-NET-API-to-support-asynchronous-operations.aspx
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using System.Threading;
using System.Net;
using DropNet.Exceptions;
namespace DropNet.Extensions
{
public static class RestClientExtensions
{
public static Task<TResult> ExecuteTask<TResult>(this IRestClient client,
IRestRequest request) where TResult : new()
{
var tcs = new TaskCompletionSource<TResult>();
WaitCallback
asyncWork = _ =>
{
try
{
#if WINDOWS_PHONE
//check for network connection
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
tcs.SetException(new DropboxRestException
{
StatusCode = System.Net.HttpStatusCode.BadGateway
});
return;
}
#endif
client.ExecuteAsync<TResult>(request,
(response, asynchandle) =>
{
if (response.StatusCode != HttpStatusCode.OK)
{
tcs.SetException(new DropboxRestException(response, HttpStatusCode.OK));
}
else
{
tcs.SetResult(response.Data);
}
});
}
catch (Exception exc)
{
tcs.SetException(exc);
}
};
return ExecuteTask(asyncWork, tcs);
}
public static Task<IRestResponse> ExecuteTask(this IRestClient client,
IRestRequest request)
{
var tcs = new TaskCompletionSource<IRestResponse>();
WaitCallback
asyncWork = _ =>
{
try
{
#if WINDOWS_PHONE
//check for network connection
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
tcs.SetException(new DropboxRestException
{
StatusCode = System.Net.HttpStatusCode.BadGateway
});
return;
}
#endif
client.ExecuteAsync(request,
(response, asynchandle) =>
{
if (response.StatusCode != HttpStatusCode.OK)
{
tcs.SetException(new DropboxRestException(response, HttpStatusCode.OK));
}
else
{
tcs.SetResult(response);
}
});
}
catch (Exception exc)
{
tcs.SetException(exc);
}
};
return ExecuteTask(asyncWork, tcs);
}
private static Task<TResult> ExecuteTask<TResult>(WaitCallback asyncWork,
TaskCompletionSource<TResult> tcs)
{
ThreadPool.QueueUserWorkItem(asyncWork);
return tcs.Task;
}
}
}