-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathApiClient.cs
1122 lines (995 loc) · 42.2 KB
/
ApiClient.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Web;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using RestSharp;
using PureCloudPlatform.Client.V2.Extensions;
using System.Net.Http;
namespace PureCloudPlatform.Client.V2.Client
{
/// <summary>
/// API client is mainly responible for making the HTTP call to the API backend.
/// </summary>
public class ApiClient
{
private JsonSerializerSettings serializerSettings = new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
MetadataPropertyHandling = MetadataPropertyHandling.Ignore
};
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default configuration and base path (https://api.mypurecloud.com).
/// </summary>
public ApiClient()
{
// Use TLS 1.2
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Configuration = Configuration.Default;
ClientOptions = new ClientRestOptions();
ClientOptions.BaseUrl = new Uri("https://api.mypurecloud.com");
RetryConfig = DEFAULT_RETRY_CONFIG;
AddSerializerSettings();
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default base path (https://api.mypurecloud.com).
/// </summary>
/// <param name="config">An instance of Configuration.</param>
public ApiClient(Configuration config = null)
{
// Use TLS 1.2
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
if (config == null)
Configuration = Configuration.Default;
else
Configuration = config;
ClientOptions = new ClientRestOptions();
ClientOptions.BaseUrl = new Uri("https://api.mypurecloud.com");
RetryConfig = DEFAULT_RETRY_CONFIG;
AddSerializerSettings();
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default configuration.
/// </summary>
/// <param name="basePath">The base path.</param>
public ApiClient(String basePath = "https://api.mypurecloud.com")
{
// Use TLS 1.2
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
if (String.IsNullOrEmpty(basePath))
throw new ArgumentException("basePath cannot be empty");
ClientOptions = new ClientRestOptions();
ClientOptions.BaseUrl = new Uri(basePath);
RetryConfig = DEFAULT_RETRY_CONFIG;
Configuration = Configuration.Default;
AddSerializerSettings();
}
private void AddSerializerSettings()
{
serializerSettings.Converters.Add(new Iso8601DateTimeConverter());
serializerSettings.Converters.Add(new UpgradeSdkEnumConverter());
}
/// <summary>
/// Gets or sets the default API client for making HTTP calls.
/// </summary>
/// <value>The default API client.</value>
[Obsolete("ApiClient.Default is deprecated, please use 'Configuration.Default.ApiClient' instead.")]
public static ApiClient Default;
/// <summary>
/// Gets or sets the Configuration.
/// </summary>
/// <value>An instance of the Configuration.</value>
public Configuration Configuration { get; set; }
/// <summary>
/// Gets or sets the RestClient.
/// </summary>
/// <value>An instance of the RestClient</value>
private RestClient RestClient { get; set; }
private RetryConfiguration retryConfig;
public RetryConfiguration RetryConfig { get; set; }
private static readonly RetryConfiguration DEFAULT_RETRY_CONFIG = new RetryConfiguration();
private GatewayConfiguration gatewayConfig;
public GatewayConfiguration GatewayConfig {
get
{
return this.gatewayConfig;
}
set
{
if (value != null) {
this.gatewayConfig = value;
} else {
// Reset
this.gatewayConfig = null;
}
}
}
public Uri GetConfUri(String pathType, Uri baseUri) {
if (pathType.Equals("login")) {
if (this.GatewayConfig == null || String.IsNullOrEmpty(this.GatewayConfig.Host)) {
var regex = new Regex(@"://(api)\.");
var authUrl = regex.Replace(baseUri.ToString(), "://login.");
return new Uri(authUrl);
} else {
String confUrl = this.GatewayConfig.Protocol + "://" + this.GatewayConfig.Host;
if (this.GatewayConfig.Port > 0) confUrl = confUrl + ":" + this.GatewayConfig.Port.ToString();
if (!String.IsNullOrEmpty(this.GatewayConfig.PathParamsLogin)) {
if (this.GatewayConfig.PathParamsLogin.StartsWith("/")) {
confUrl = confUrl + this.GatewayConfig.PathParamsLogin;
} else {
confUrl = confUrl + "/" + this.GatewayConfig.PathParamsLogin;
}
}
return new Uri(confUrl);
}
} else {
if (this.GatewayConfig == null || String.IsNullOrEmpty(this.GatewayConfig.Host)) {
return baseUri;
} else {
String confUrl = this.GatewayConfig.Protocol + "://" + this.GatewayConfig.Host;
if (this.GatewayConfig.Port > 0) confUrl = confUrl + ":" + this.GatewayConfig.Port.ToString();
if (!String.IsNullOrEmpty(this.GatewayConfig.PathParamsApi)) {
if (this.GatewayConfig.PathParamsApi.StartsWith("/")) {
confUrl = confUrl + this.GatewayConfig.PathParamsApi;
} else {
confUrl = confUrl + "/" + this.GatewayConfig.PathParamsApi;
}
}
return new Uri(confUrl);
}
}
}
public void SetGateway(String host,
String protocol,
int port,
String pathParamsLogin,
String pathParamsApi,
String username,
String password) {
this.GatewayConfig = new GatewayConfiguration(host, protocol, port, pathParamsLogin, pathParamsApi, username, password);
}
public void SetGateway(String host,
String protocol,
int port,
String pathParamsLogin,
String pathParamsApi) {
this.GatewayConfig = new GatewayConfiguration(host, protocol, port, pathParamsLogin, pathParamsApi);
}
// These fields are only applicable to the Code Authorization OAuth flow:
public bool UsingCodeAuth { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
// Creates and sets up a RestRequest prior to a call.
private RestRequest PrepareRequest(
String path, RestSharp.Method method, List<Tuple<String, String>> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = new RestRequest(path, method);
// add path parameter, if any
foreach(var param in pathParams)
request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment);
// add header parameter, if any
foreach(var param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(var param in queryParams)
request.AddQueryParameter(param.Item1, param.Item2);
// add form parameter, if any
foreach(var param in formParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(var param in fileParams)
{
request.AddFile(param.Value.Name, param.Value.GetFile, param.Value.FileName, param.Value.ContentType);
}
if (postBody != null) // http body (model or byte[]) parameter
{
if (postBody.GetType() == typeof(String))
{
request.AddParameter("application/json", postBody, ParameterType.RequestBody);
}
else if (postBody.GetType() == typeof(byte[]))
{
request.AddParameter(contentType, postBody, ParameterType.RequestBody);
}
}
return request;
}
private void HandleExpiredAccessToken()
{
if (Monitor.TryEnter(Configuration, 0))
{
try
{
Extensions.AuthExtensions.PostToken(this, ClientId, ClientSecret, authorizationCode: Configuration.AuthTokenInfo.RefreshToken, isRefreshRequest: true);
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
finally
{
Monitor.Exit(Configuration);
}
}
else
{
// Abort with error if we have waited the configured time and refresh still isn't complete
if (!Monitor.TryEnter(Configuration, TimeSpan.FromSeconds(Configuration.RefreshTokenWaitTime))) {
throw new ApiException(500, $"Token refresh took longer than {Configuration.RefreshTokenWaitTime} seconds");
}
else
{
Monitor.Exit(Configuration);
}
}
}
/// <summary>
/// Makes the HTTP request (Sync).
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="pathParams">Path parameters.</param>
/// <param name="contentType">Content Type of the request</param>
/// <returns>Object</returns>
public Object CallApi(
String path, RestSharp.Method method, List<Tuple<String, String>> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
// Set SDK version
request.AddHeader("purecloud-sdk", "227.0.0");
Retry retry = new Retry(this.RetryConfig);
RestResponse response;
var options = new RestClientOptions(GetConfUri("api", ClientOptions.BaseUrl)){};
if (ClientOptions.HttpMessageHandler != null)
{
options = new RestClientOptions(GetConfUri("api", ClientOptions.BaseUrl))
{
ConfigureMessageHandler = _ => ClientOptions.HttpMessageHandler
};
}
if (Configuration.UserAgent != null)
{
options.UserAgent = Configuration.UserAgent;
}
if (Configuration.Timeout > 0)
{
options.MaxTimeout = Configuration.Timeout;
}
if (ClientOptions.Proxy != null)
{
options.Proxy = ClientOptions.Proxy;
}
RestClient = new RestClient(options);
var fullUrl = RestClient.BuildUri(request);
string url = fullUrl == null ? path : fullUrl.ToString();
do
{
response = RestClient.Execute(request);
Configuration.Logger.Debug(method.ToString(), url, postBody, (int)response.StatusCode, headerParams);
Configuration.Logger.Trace(method.ToString(), url, postBody, (int)response.StatusCode, headerParams, response.Headers?
.GroupBy(header => header?.Name)
.Select(header => new
{
Name = header?.FirstOrDefault()?.Name,
Value = header.Select(x => x?.Value)?.ToList()
}).ToDictionary(header => header?.Name?.ToString(), header => String.Join(", ", header?.Value?.ToArray()))
?? new Dictionary<string, string>());
}while(retry.ShouldRetry(response));
if (UsingCodeAuth && Configuration.ShouldRefreshAccessToken)
{
int statusCode = (int) response.StatusCode;
if (statusCode == 401)
{
HandleExpiredAccessToken();
headerParams["Authorization"] = "Bearer " + Configuration.AccessToken;
return CallApi(path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType);
}
}
if ((int)response.StatusCode < 200 || (int)response.StatusCode >= 300)
Configuration.Logger.Error(method.ToString(), url, postBody, response.Content, (int)response.StatusCode, headerParams, response.Headers?
.GroupBy(header => header?.Name)
.Select(header => new
{
Name = header?.FirstOrDefault()?.Name,
Value = header.Select(x => x?.Value)?.ToList()
}).ToDictionary(header => header?.Name?.ToString(), header => String.Join(", ", header?.Value?.ToArray()))
?? new Dictionary<string, string>());
return (Object) response;
}
/// <summary>
/// Makes the asynchronous HTTP request.
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="pathParams">Path parameters.</param>
/// <param name="contentType">Content type.</param>
/// <returns>The Task instance.</returns>
public async System.Threading.Tasks.Task<Object> CallApiAsync(
String path, RestSharp.Method method, List<Tuple<String, String>> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
Retry retry = new Retry(this.RetryConfig);
RestResponse response;
var options = new RestClientOptions(GetConfUri("api", ClientOptions.BaseUrl)){};
if (ClientOptions.HttpMessageHandler != null)
{
options = new RestClientOptions(GetConfUri("api", ClientOptions.BaseUrl))
{
ConfigureMessageHandler = _ => ClientOptions.HttpMessageHandler
};
}
if (Configuration.UserAgent != null)
{
options.UserAgent = Configuration.UserAgent;
}
if (ClientOptions.Proxy != null)
{
options.Proxy = ClientOptions.Proxy;
}
if (Configuration.Timeout > 0)
{
options.MaxTimeout = Configuration.Timeout;
}
RestClient = new RestClient(options);
var fullUrl = RestClient.BuildUri(request);
string url = fullUrl == null ? path : fullUrl.ToString();
do
{
response = await RestClient.ExecuteAsync(request);
Configuration.Logger.Debug(method.ToString(), url, postBody, (int)response.StatusCode, headerParams);
Configuration.Logger.Trace(method.ToString(), url, postBody, (int)response.StatusCode, headerParams, response.Headers?
.GroupBy(header => header?.Name)
.Select(header => new
{
Name = header?.FirstOrDefault()?.Name,
Value = header.Select(x => x?.Value)?.ToList()
}).ToDictionary(header => header?.Name?.ToString(), header => String.Join(", ", header?.Value?.ToArray()))
?? new Dictionary<string, string>());
}while(retry.ShouldRetry(response));
if (UsingCodeAuth && Configuration.ShouldRefreshAccessToken)
{
int statusCode = (int) response.StatusCode;
if (statusCode == 401)
{
HandleExpiredAccessToken();
headerParams["Authorization"] = "Bearer " + Configuration.AccessToken;
return await CallApiAsync(path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType);
}
}
return (Object)response;
}
/// <summary>
/// Escape string (url-encoded).
/// </summary>
/// <param name="str">String to be escaped.</param>
/// <returns>Escaped string.</returns>
public string EscapeString(string str)
{
return UrlEncode(str);
}
/// <summary>
/// Create FileParameter based on Stream.
/// </summary>
/// <param name="name">Parameter name.</param>
/// <param name="stream">Input stream.</param>
/// <returns>FileParameter.</returns>
public FileParameter ParameterToFile(string name, Stream stream)
{
if (stream is FileStream)
return FileParameter.Create(name, ReadAsBytes(stream), Path.GetFileName(((FileStream)stream).Name));
else
return FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided");
}
/// <summary>
/// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime.
/// If parameter is a list, join the list with ",".
/// Otherwise just return the string.
/// </summary>
/// <param name="obj">The parameter (header, path, query, form).</param>
/// <returns>Formatted string.</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return ((DateTime)obj).ToString (Configuration.DateTimeFormat);
else if (obj is DateTimeOffset)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat);
else if (obj is IList)
{
var flattenedString = new StringBuilder();
foreach (var param in (IList)obj)
{
if (flattenedString.Length > 0)
flattenedString.Append(",");
flattenedString.Append(param);
}
return flattenedString.ToString();
}
else if (obj is bool)
{
return Convert.ToString(obj).ToLower();
}
else
return Convert.ToString (obj);
}
/// <summary>
/// Creates a restclient with a base path string input
/// </summary>
/// <returns>Return changed from RestClient to Void . Since no purpose to expose underlying RestClient to Consumer and
/// design changed to One Restclient per API</returns>
public void setBasePath(String basePath){
if (String.IsNullOrEmpty(basePath))
throw new ArgumentException("basePath cannot be empty");
ClientOptions.BaseUrl = new Uri(basePath);
}
/// <summary>
/// Creates a restclient with a PureCloudRegionHost string input
/// </summary>
/// <returns>Return changed from RestClient to Void . Since no purpose to expose underlying RestClient to Consumer and
/// design changed to One Restclient per API</returns>
public void setBasePath(PureCloudRegionHosts region){
setBasePath(region.GetDescription());
}
/// <summary>
/// Deserialize the JSON string into a proper object.
/// </summary>
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
public object Deserialize(RestResponse response, Type type)
{
IReadOnlyCollection<RestSharp.HeaderParameter> headers = response.Headers;
if (type == typeof(byte[])) // return byte array
{
return response.RawBytes;
}
if (type == typeof(Stream))
{
if (headers != null)
{
var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath)
? Path.GetTempPath()
: Configuration.TempFolderPath;
var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
foreach (var header in headers)
{
var match = regex.Match(header.ToString());
if (match.Success)
{
string fileName = filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", ""));
File.WriteAllBytes(fileName, response.RawBytes);
return new FileStream(fileName, FileMode.Open);
}
}
}
var stream = new MemoryStream(response.RawBytes);
return stream;
}
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
{
return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind);
}
if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type
{
return ConvertType(response.Content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(response.Content, type, serializerSettings);
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Serialize an input (model) into JSON string
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>JSON string.</returns>
public String Serialize(object obj)
{
try
{
if (obj != null){
return obj is string str ? str : JsonConvert.SerializeObject(obj);
} else {
return null;
}
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Select the Content-Type header's value from the given content-type array:
/// if JSON exists in the given array, use it;
/// otherwise use the first one defined in 'consumes'
/// </summary>
/// <param name="contentTypes">The Content-Type array to select from.</param>
/// <returns>The Content-Type header to use.</returns>
public String SelectHeaderContentType(String[] contentTypes)
{
if (contentTypes.Length == 0)
return null;
if (contentTypes.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return contentTypes[0]; // use the first content type specified in 'consumes'
}
/// <summary>
/// Select the Accept header's value from the given accepts array:
/// if JSON exists in the given array, use it;
/// otherwise use all of them (joining into a string)
/// </summary>
/// <param name="accepts">The accepts array to select from.</param>
/// <returns>The Accept header to use.</returns>
public String SelectHeaderAccept(String[] accepts)
{
if (accepts.Length == 0)
return null;
if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return String.Join(",", accepts);
}
/// <summary>
/// Encode string in base64 format.
/// </summary>
/// <param name="text">String to be encoded.</param>
/// <returns>Encoded string.</returns>
public static string Base64Encode(string text)
{
return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text));
}
/// <summary>
/// Dynamically cast the object into target type.
/// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast
/// </summary>
/// <param name="source">Object to be casted</param>
/// <param name="dest">Target type</param>
/// <returns>Casted object</returns>
public static dynamic ConvertType(dynamic source, Type dest)
{
return Convert.ChangeType(source, dest);
}
/// <summary>
/// Convert stream to byte array
/// Credit/Ref: http://stackoverflow.com/a/221941/677735
/// </summary>
/// <param name="input">Input stream to be converted</param>
/// <returns>Byte array</returns>
public static byte[] ReadAsBytes(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
/// <summary>
/// URL encode a string
/// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50
/// </summary>
/// <param name="input">String to be URL encoded</param>
/// <returns>Byte array</returns>
public static string UrlEncode(string input)
{
const int maxLength = 32766;
if (input == null)
{
throw new ArgumentNullException("input");
}
if (input.Length <= maxLength)
{
return Uri.EscapeDataString(input);
}
StringBuilder sb = new StringBuilder(input.Length * 2);
int index = 0;
while (index < input.Length)
{
int length = Math.Min(input.Length - index, maxLength);
string subString = input.Substring(index, length);
sb.Append(Uri.EscapeDataString(subString));
index += subString.Length;
}
return sb.ToString();
}
/// <summary>
/// Sanitize filename by removing the path
/// </summary>
/// <param name="filename">Filename</param>
/// <returns>Filename</returns>
public static string SanitizeFilename(string filename)
{
Match match = Regex.Match(filename, @".*[/\\](.*)$");
if (match.Success)
{
return match.Groups[1].Value;
}
else
{
return filename;
}
}
public class RetryConfiguration
{
private long backoffIntervalMs = 300000L;
private long retryAfterDefaultMs = 3000L;
private int maxRetryTimeSec = 0;
private int retryMax = 5;
public long BackOffIntervalMs
{
get
{
return backoffIntervalMs;
}
set
{
if (value < 0)
{
throw new ArgumentException("BackOffIntervalMs should be a positive integer");
}
this.backoffIntervalMs = value;
}
}
public long RetryAfterDefaultMs
{
get
{
return retryAfterDefaultMs;
}
set
{
if (value < 0)
{
throw new ArgumentException("RetryAfterDefaultMs should be a positive integer");
}
this.retryAfterDefaultMs = value;
}
}
public int MaxRetryTimeSec
{
get
{
return maxRetryTimeSec;
}
set
{
if (value < 0)
{
throw new ArgumentException("MaxRetryTimeSec should be a positive integer");
}
this.maxRetryTimeSec = value;
}
}
public int RetryMax
{
get
{
return retryMax;
}
set
{
if (value < 0)
{
throw new ArgumentException("RetryMax should be a positive integer");
}
this.retryMax = value;
}
}
}
public class GatewayConfiguration
{
// Gateway Host
private String host = null;
// Gateway Protocol
private String protocol = "https";
// Gateway Port
private int port = -1;
// Gateway Path Param for Login
private String pathParamsLogin = "";
// Gateway Path Param for API
private String pathParamsApi = "";
// Gateway Username (future)
private String username = null;
// Gateway Password (future)
private String password = null;
public GatewayConfiguration()
{
this.protocol = "https";
this.port = -1;
this.pathParamsLogin = "";
this.pathParamsApi = "";
}
public GatewayConfiguration(String host,
String protocol,
int port,
String pathParamsLogin,
String pathParamsApi,
String username,
String password)
{
this.Host = host;
this.Protocol = protocol;
this.Port = port;
this.PathParamsLogin = pathParamsLogin;
this.PathParamsApi = pathParamsApi;
this.Username = username;
this.Password = password;
}
public GatewayConfiguration(String host,
String protocol,
int port,
String pathParamsLogin,
String pathParamsApi)
{
this.Host = host;
this.Protocol = protocol;
this.Port = port;
this.PathParamsLogin = pathParamsLogin;
this.PathParamsApi = pathParamsApi;
}
public String Host
{
get
{
return this.host;
}
set
{
if (!String.IsNullOrEmpty(value)) {
this.host = value;
}
}
}
public String Protocol
{
get
{
return this.protocol;
}
set
{
if (!String.IsNullOrEmpty(value)) {
this.protocol = value;
} else {
this.protocol = "https";
}
}
}
public int Port
{
get
{
return this.port;
}
set
{
if (value > -1) {
this.port = value;
} else {
this.port = -1;
}
}
}
public String PathParamsLogin
{
get
{
return this.pathParamsLogin;
}
set
{
if (!String.IsNullOrEmpty(value)) {
this.pathParamsLogin = value;
if (this.pathParamsLogin.EndsWith("/")) {
this.pathParamsLogin = this.pathParamsLogin.Substring(0, this.pathParamsLogin.Length-1);
}
} else {
this.pathParamsLogin = "";
}
}
}
public String PathParamsApi
{
get
{
return this.pathParamsApi;
}
set
{
if (!String.IsNullOrEmpty(value)) {
this.pathParamsApi = value;
if (this.pathParamsApi.EndsWith("/")) {
this.pathParamsApi = this.pathParamsApi.Substring(0, this.pathParamsApi.Length-1);
}
} else {
this.pathParamsApi = "";
}
}
}
public String Username
{
get
{
return this.username;
}
set
{
if (!String.IsNullOrEmpty(value)) {
this.username = value;
}
}
}
public String Password
{
get
{
return this.password;
}
set
{
if (!String.IsNullOrEmpty(value)) {
this.password = value;
}
}
}
}