forked from arnoldthebat/RandomJSONRPC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RandomJSONRPC.cs
694 lines (639 loc) · 34.3 KB
/
RandomJSONRPC.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace org.random.JSONRPC
{
public class RandomJSONRPC
{
/** The URL to send the remote procedure calls to */
private readonly string URL = "https://api.random.org/json-rpc/1/invoke";
/** The following members are the names of the basic methods available in the random.org api */
private readonly string INTEGER_METHOD = "generateIntegers";
private readonly string DECIMALFRACTION_METHOD = "generateDecimalFractions";
private readonly string GAUSSIAN_METHOD = "generateGaussians";
private readonly string STRING_METHOD = "generateStrings";
private readonly string UUID_METHOD = "generateUUIDs";
// Signed method calls
private readonly string SIGNED_INTEGER_METHOD = "generateSignedIntegers";
private readonly string SIGNED_DECIMALFRACTION_METHOD = "generateSignedDecimalFractions";
private readonly string SIGNED_GAUSSIAN_METHOD = "generateSignedGaussians";
private readonly string SIGNED_STRING_METHOD = "generateSignedStrings";
private readonly string SIGNED_UUID_METHOD = "generateSignedUUIDs";
private readonly string VERIFY_SIGNATURE = "verifySignature";
private readonly string GET_USAGE_METHOD = "getUsage";
/** The HTTP content type for the requests */
private readonly string CONTENT_TYPE = "application/json";
/** The default value for the optional replacement parameter */
private bool REPLACEMENT_DEFAULT = true;
private readonly int ONE_HOUR_IN_MILLIS = 3600000;
private string mApiKey;
private long mMaxBlockingTime = 3000;
/** The request object to be sent to the server */
private JObject mJSONRequest;
/** The response object received from the server */
private JObject mJSONResponse;
/** The parameters supplied with the request object */
private JObject mJSONParams;
/** The time of the last received response */
private long mLastResponseReceived;
/** The advisory delay given by the random.org server */
private long mAdvisoryDelay = 0;
// Signed Keys and Signature Authenticity requirements
private readonly string SIGNATURE = "signature";
private readonly string AUTHENTICITY = "authenticity";
// Other hard coding required
private readonly string RESULT = "result";
private readonly string RANDOM = "random";
private readonly string APIKEY = "apiKey";
/// <summary>
/// Creates a new RandomJSONRPC object with the given api key
/// </summary>
/// <param name="apiKey">The api Key from random.org</param>
public RandomJSONRPC(String apiKey)
{
mApiKey = apiKey;
}
/// <summary>
/// Creates a new RandomJSONRPC object with the given api key and the maximum time the user wants to wait for the server.
/// </summary>
/// <param name="apiKey">The api key from random.org</param>
/// <param name="maxBlockingTime">The longest amount of time (in milliseconds) that the user wants to wait for the server (default is 3 seconds).
/// This does not take into account the time it takes to send the request over the network.
/// Only the advisory delay given by the server is used. If the maxBlockingTime value is exceeded a RuntimeException will be thrown.
/// </param>
public RandomJSONRPC(String apiKey, long maxBlockingTime)
{
mApiKey = apiKey;
mMaxBlockingTime = maxBlockingTime;
}
/// <summary>
/// Calls <code> GenerateIntegers(int n, int min, int max, true, 10) </code>
/// </summary>
/// <param name="n">How many random integers are needed. Must be within the [1,1e4] range.</param>
/// <param name="min">The lower boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range.</param>
/// <param name="max">The upper boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range.</param>
/// <returns>a set of random integers limited by the parameters listed above and generated by random.org</returns>
public int[] GenerateIntegers(int n, int min, int max)
{
return GenerateIntegers(n, min, max, REPLACEMENT_DEFAULT);
}
/// <summary>
/// Calls <code> GenerateIntegers(int n, int min, int max, bool replacement, 10) </code>
/// </summary>
/// <param name="n">How many random integers are needed. Must be within the [1,1e4] range.</param>
/// <param name="min">The lower boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range.</param>
/// <param name="max">The upper boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range.</param>
/// <param name="replacement">(default value true) Specifies whether the random numbers should be picked with replacement.</param>
/// <returns>a set of random integers limited by the parameters listed above and generated by random.org</returns>
public int[] GenerateIntegers(int n, int min, int max, bool replacement)
{
return Array.ConvertAll(GenerateIntegers(n, min, max, replacement, 10), int.Parse);
}
/// <summary>
/// Generates true random integers within a user-defined range
/// </summary>
/// <param name="n">How many random integers are needed. Must be within the [1,1e4] range.</param>
/// <param name="min">The lower boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range.</param>
/// <param name="max">The upper boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range.</param>
/// <param name="replacement">(default value true) Specifies whether the random numbers should be picked with replacement.</param>
/// <param name="baseNum">Specifies the base that will be used to display the numbers. Values allowed are 2, 8, 10 and 16.</param>
/// <returns>a set of random integers limited by the parameters listed above and generated by random.org</returns>
public string[] GenerateIntegers(int n, int min, int max, bool replacement, int baseNum)
{
mJSONParams = InitIntegerParams(n, min, max, replacement, baseNum);
mJSONRequest = InitMethod(INTEGER_METHOD);
SendRequest();
return ExtractStrings();
}
/// <summary>
/// Calls <code> GenerateDecimalFractions(int n, int decimalPlaces, true) </code>
/// </summary>
/// <param name="n">How many random decimal fractions are needed. Must be within the [1,1e4] range.</param>
/// <param name="decimalPlaces">The number of decimal places to use. Must be within the [1,20] range.</param>
/// <returns>a set of random integers limited by the parameters listed above and generated by random.org</returns>
public double[] GenerateDecimalFractions(int n, int decimalPlaces)
{
return GenerateDecimalFractions(n, decimalPlaces, true);
}
/// <summary>
/// Generates true random decimal fractions from a uniform distribution across the [0,1] interval with a user-defined number of decimal places.
/// </summary>
/// <param name="n">How many random decimal fractions are needed. Must be within the [1,1e4] range.</param>
/// <param name="decimalPlaces">The number of decimal places to use. Must be within the [1,20] range.</param>
/// <param name="replacement">(default value true) Specifies whether the random numbers should be picked with replacement.</param>
/// <returns>a set of random integers limited by the parameters listed above and generated by random.org</returns>
public double[] GenerateDecimalFractions(int n, int decimalPlaces, bool replacement)
{
mJSONParams = InitDecimalFractionParams(n, decimalPlaces, replacement);
mJSONRequest = InitMethod(DECIMALFRACTION_METHOD);
SendRequest();
return ExtractDoubles();
}
/// <summary>
/// Generates true random numbers from a Gaussian distribution (also known as a normal distribution).
/// </summary>
/// <param name="n">How many random Gaussian numbers are needed. Must be within the [1,1e4] range.</param>
/// <param name="mean">The distribution's mean. Must be within the [-1e6,1e6] range.</param>
/// <param name="standardDeviation">The distribution's standard deviation. Must be within the [-1e6,1e6] range.</param>
/// <param name="significantDigits">The number of significant digits to use. Must be within the [2,20] range.</param>
/// <returns>a set of random Gaussians limited by the parameters listed above and generated by random.org</returns>
public double[] GenerateGaussians(int n, double mean, double standardDeviation, int significantDigits)
{
mJSONParams = InitGaussiansParams(n, mean, standardDeviation, significantDigits);
mJSONRequest = InitMethod(GAUSSIAN_METHOD);
SendRequest();
return ExtractDoubles();
}
/// <summary>
/// Generates true random strings.
/// </summary>
/// <param name="n">How many strings are needed. Must be within the [1,1e4] range. </param>
/// <param name="length">The length of each string. Must be within the [1,20] range. All strings will be of the same length.</param>
/// <param name="characters">A string that contains the set of characters that are allowed to occur in the random strings. The maximum number of characters is 80.</param>
/// <returns>a set of random strings limited by the parameters listed above and generated by random.org</returns>
public String[] GenerateStrings(int n, int length, String characters)
{
return GenerateStrings(n, length, characters, true);
}
/// <summary>
/// Generates true random strings.
/// </summary>
/// <param name="n">How many strings are needed. Must be within the [1,1e4] range. </param>
/// <param name="length">The length of each string. Must be within the [1,20] range. All strings will be of the same length.</param>
/// <param name="characters">A string that contains the set of characters that are allowed to occur in the random strings. The maximum number of characters is 80.</param>
/// <param name="replacement">(default value true) Specifies whether the random strings should be picked with replacement</param>
/// <returns>a set of random strings limited by the parameters listed above and generated by random.org</returns>
public String[] GenerateStrings(int n, int length, String characters, bool replacement)
{
mJSONParams = InitStringParams(n, length, characters, replacement);
mJSONRequest = InitMethod(STRING_METHOD);
SendRequest();
return ExtractStrings();
}
/// <summary>
/// Generates version 4 true random Universally Unique IDentifiers (UUIDs) in accordance with section 4.4 of RFC 4122.
/// </summary>
/// <param name="n">How many UUIDs are needed. Must be within the [1,1e3] range.</param>
/// <returns>a set of random UUIDS limited by the parameters listed above and generated by random.org</returns>
public Guid[] GenerateUUIDs(int n)
{
mJSONParams = InitUUIDParams(n);
mJSONRequest = InitMethod(UUID_METHOD);
SendRequest();
return ExtractUUIDs();
}
/// <summary>
/// calls <code>GenerateSignedIntegers(n, min, max, true, 10)</code>
/// </summary>
/// <param name="n">How many random integers you need. Must be within the [1,1e4] range.</param>
/// <param name="min">The lower boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range.</param>
/// <param name="max">The upper boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range.</param>
/// <returns>a set of random integers limited by the parameters listed above and generated by random.org</returns>
public int[] GenerateSignedIntegers(int n, int min, int max)
{
return GenerateSignedIntegers(n, min, max, REPLACEMENT_DEFAULT) ;
}
/// <summary>
/// Calls <code>GenerateSignedIntegers(n, min, max, replacement, 10)</code>
/// </summary>
/// <param name="n">How many random integers you need. Must be within the [1,1e4] range.</param>
/// <param name="min">The lower boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range.</param>
/// <param name="max">The upper boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range.</param>
/// <param name="replacement">(default value true) Specifies whether the random numbers should be picked with replacement</param>
/// <returns>a set of random integers limited by the parameters listed above and generated by random.org</returns>
public int[] GenerateSignedIntegers(int n, int min, int max, bool replacement)
{
return Array.ConvertAll(GenerateSignedIntegers(n, min, max, replacement, 10), int.Parse);
}
/// <summary>
/// Generates true random integers within a user-defined range
/// </summary>
/// <param name="n">How many random integers you need. Must be within the [1,1e4] range.</param>
/// <param name="min">The lower boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range.</param>
/// <param name="max">The upper boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range.</param>
/// <param name="replacement">(default value true) Specifies whether the random numbers should be picked with replacement</param>
/// <param name="baseValue">(default value 10) Specifies the base that will be used to display the numbers. Values allowed are 2, 8, 10 and 16. </param>
/// <returns>a set of random integers limited by the parameters listed above and generated by random.org
/// Since bases other than 10 will require alphe numeric or padding, returns as a string array</returns>
public string[] GenerateSignedIntegers(int n, int min, int max, bool replacement, int baseValue)
{
mJSONParams = InitIntegerParams(n, min, max, replacement, baseValue);
mJSONRequest = InitMethod(SIGNED_INTEGER_METHOD);
SendRequest();
return ExtractStrings();
}
/// <summary>
/// Calls <code> GenerateSignedDecimalFractions(int n, int decimalPlaces, true) </code>
/// </summary>
/// <param name="n">How many random decimal fractions are needed. Must be within the [1,1e4] range.</param>
/// <param name="decimalPlaces">The number of decimal places to use. Must be within the [1,20] range.</param>
/// <returns>a set of random integers limited by the parameters listed above and generated by random.org</returns>
public double[] GenerateSignedDecimalFractions(int n, int decimalPlaces)
{
return GenerateSignedDecimalFractions(n, decimalPlaces, true);
}
/// <summary>
/// Generates true random decimal fractions from a uniform distribution across the [0,1] interval with a user-defined number of decimal places.
/// </summary>
/// <param name="n">How many random decimal fractions are needed. Must be within the [1,1e4] range.</param>
/// <param name="decimalPlaces">The number of decimal places to use. Must be within the [1,20] range.</param>
/// <param name="replacement">(default value true) Specifies whether the random numbers should be picked with replacement.</param>
/// <returns>a set of random integers limited by the parameters listed above and generated by random.org</returns>
public double[] GenerateSignedDecimalFractions(int n, int decimalPlaces, bool replacement)
{
mJSONParams = InitDecimalFractionParams(n, decimalPlaces, replacement);
mJSONRequest = InitMethod(SIGNED_DECIMALFRACTION_METHOD);
SendRequest();
return ExtractDoubles();
}
/// <summary>
/// Generates true random numbers from a Gaussian distribution (also known as a normal distribution).
/// </summary>
/// <param name="n">How many random Gaussian numbers are needed. Must be within the [1,1e4] range.</param>
/// <param name="mean">The distribution's mean. Must be within the [-1e6,1e6] range.</param>
/// <param name="standardDeviation">The distribution's standard deviation. Must be within the [-1e6,1e6] range.</param>
/// <param name="significantDigits">The number of significant digits to use. Must be within the [2,20] range.</param>
/// <returns>a set of random Gaussians limited by the parameters listed above and generated by random.org</returns>
public double[] GenerateSignedGaussians(int n, double mean, double standardDeviation, int significantDigits)
{
mJSONParams = InitGaussiansParams(n, mean, standardDeviation, significantDigits);
mJSONRequest = InitMethod(SIGNED_GAUSSIAN_METHOD);
SendRequest();
return ExtractDoubles();
}
/// <summary>
/// Calls <code>GenerateSignedStrings(n, length, characters, true)</code>
/// </summary>
/// <param name="n">How many strings are needed. Must be within the [1,1e4] range. </param>
/// <param name="length">The length of each string. Must be within the [1,20] range. All strings will be of the same length.</param>
/// <param name="characters">A string that contains the set of characters that are allowed to occur in the random strings. The maximum number of characters is 80.</param>
/// <returns>a set of random strings limited by the parameters listed above and generated by random.org</returns>
public String[] GenerateSignedStrings(int n, int length, String characters)
{
return GenerateSignedStrings(n, length, characters, true);
}
/// <summary>
/// Generates true random strings.
/// </summary>
/// <param name="n">How many strings are needed. Must be within the [1,1e4] range. </param>
/// <param name="length">The length of each string. Must be within the [1,20] range. All strings will be of the same length.</param>
/// <param name="characters">A string that contains the set of characters that are allowed to occur in the random strings. The maximum number of characters is 80.</param>
/// <param name="replacement">(default value true) Specifies whether the random strings should be picked with replacement</param>
/// <returns>a set of random strings limited by the parameters listed above and generated by random.org</returns>
public String[] GenerateSignedStrings(int n, int length, String characters, bool replacement)
{
mJSONParams = InitStringParams(n, length, characters, replacement);
mJSONRequest = InitMethod(SIGNED_STRING_METHOD);
SendRequest();
return ExtractStrings();
}
/// <summary>
/// Generates version 4 true random Universally Unique IDentifiers (UUIDs) in accordance with section 4.4 of RFC 4122.
/// </summary>
/// <param name="n">How many UUIDs are needed. Must be within the [1,1e3] range.</param>
/// <returns>a set of random UUIDS limited by the parameters listed above and generated by random.org</returns>
public Guid[] GenerateSignedUUIDs(int n)
{
mJSONParams = InitUUIDParams(n);
mJSONRequest = InitMethod(SIGNED_UUID_METHOD);
SendRequest();
return ExtractUUIDs();
}
/// <summary>
/// Returns the number of requests left on the quota
/// </summary>
/// <returns>The number of remaining requests</returns>
public int GetRequestsLeft()
{
return GetObjectsLeft(RESULT, "requestsLeft");
}
/// <summary>
/// Returns the number of bits left on the quota
/// </summary>
/// <returns>The number of remaining bits</returns>
public int GetBitsLeft()
{
return GetObjectsLeft(RESULT, "bitsLeft");
}
/// <summary>
/// Verifies the signature of a response previously received from one of the methods in the Signed API. This is used to examine the authenticity of numbers.
/// This must be run therefore after a valisd request to retrive signed objects
/// </summary>
/// <returns>True or False</returns>
public bool VerifySignature()
{
mJSONParams.RemoveAll();
mJSONParams.Add(RANDOM, ResultObject.GetValue(RANDOM));
mJSONParams.Add(SIGNATURE, ResultObject.GetValue(SIGNATURE));
mJSONRequest = InitMethod(VERIFY_SIGNATURE);
SendRequest();
//RandomObject = ((JObject)mJSONResponse.GetValue(RESULT));
return (bool)((JObject)mJSONResponse.GetValue(RESULT)).GetValue(AUTHENTICITY);
}
/// <summary>
/// Initialise the parameters to put in the JSON request object for integer generation
/// </summary>
/// <param name="n"></param>
/// <param name="min"></param>
/// <param name="max"></param>
/// <param name="replacement"></param>
/// <returns>An initialised JSON object holding the parameters necessary to generate integers</returns>
private JObject InitIntegerParams(int n, int min, int max, bool replacement, int baseNum)
{
mJSONParams = new JObject(
new JProperty(APIKEY, mApiKey),
new JProperty("n", n),
new JProperty("min", min),
new JProperty("max", max),
new JProperty("replacement", replacement),
new JProperty("base", baseNum)
);
return mJSONParams;
}
/// <summary>
/// Generic GetUsage for quota lookups
/// </summary>
/// <returns>JOBject with method params</returns>
private JObject GetUsage()
{
mJSONParams = new JObject(new JProperty(APIKEY, mApiKey));
mJSONRequest = InitMethod(GET_USAGE_METHOD);
SendRequest();
return mJSONResponse;
}
/// <summary>
/// Initialise the parameters to put in the JSON request object for decimal fraction generation
/// </summary>
/// <param name="n"></param>
/// <param name="decimalPlaces"></param>
/// <param name="replacement"></param>
/// <returns>An initialised JSON object holding the parameters necessary to generate decimal fractions</returns>
private JObject InitDecimalFractionParams(int n, int decimalPlaces, bool replacement)
{
mJSONParams = new JObject(
new JProperty(APIKEY, mApiKey),
new JProperty("n", n),
new JProperty("decimalPlaces", decimalPlaces),
new JProperty("replacement", replacement));
return mJSONParams;
}
/// <summary>
/// Initialise the parameters to put in the JSON request object for Gaussian generation
/// </summary>
/// <param name="n"></param>
/// <param name="mean"></param>
/// <param name="standardDeviation"></param>
/// <param name="significantDigits"></param>
/// <returns>An initialised JSON object holding the parameters necessary to generate Gaussians</returns>
private JObject InitGaussiansParams(int n, double mean, double standardDeviation, int significantDigits)
{
mJSONParams = new JObject(
new JProperty(APIKEY, mApiKey),
new JProperty("n", n),
new JProperty("mean", mean),
new JProperty("standardDeviation", standardDeviation),
new JProperty("significantDigits", significantDigits));
return mJSONParams;
}
/// <summary>
/// Initialise the parameters to put in the JSON request object for string generation
/// </summary>
/// <param name="n"></param>
/// <param name="length"></param>
/// <param name="characters"></param>
/// <param name="replacement"></param>
/// <returns>An initialised JSON object holding the parameters necessary to generate strings</returns>
private JObject InitStringParams(int n, int length, String characters, bool replacement)
{
mJSONParams = new JObject(
new JProperty(APIKEY, mApiKey),
new JProperty("n", n),
new JProperty("length", length),
new JProperty("characters", characters),
new JProperty("replacement", replacement));
return mJSONParams;
}
/// <summary>
/// Initialise the JSON object representing the request to be sent over the network
/// </summary>
/// <param name="n">method The name of the method to be invoked on the server</param>
/// <returns>An initialised JSON object holding the fields that the api methods use</returns>
private JObject InitUUIDParams(int n)
{
mJSONParams = new JObject(
new JProperty(APIKEY, mApiKey),
new JProperty("n", n));
return mJSONParams;
}
/// <summary>
/// Initialise the JSON object representing the request to be sent over the network
/// </summary>
/// <param name="method">The name of the method to be invoked on the server</param>
/// <returns>An initialised JSON object holding the fields that the api methods use</returns>
private JObject InitMethod(string method)
{
mJSONRequest = new JObject(
new JProperty("jsonrpc", "2.0"),
new JProperty("method", method),
new JProperty("params", mJSONParams),
new JProperty("id", new Random().Next()));
return mJSONRequest;
}
/// <summary>
/// Wait for advisory delay and make the call to the method that does the actual networking.
/// </summary>
private void SendRequest()
{
mJSONResponse = null;
long timeSinceLastRequest = DateTime.Now.Ticks - mLastResponseReceived;
long waitingTime = mAdvisoryDelay - timeSinceLastRequest;
if (waitingTime > 0)
{
if (waitingTime > mMaxBlockingTime)
{
//if the waiting time advised by random.org is larger than the time the user wants to wait, throw an exception
throw new RandomJSONRPCRunTimeException("The advised waiting is higher than the max accepted value");
}
else
{
System.Threading.Thread.Sleep(TimeSpan.FromTicks(waitingTime * 10000));
}
}
DoPost();
ErrorCheck();
//store the time when the response is received (unless the response is an error or the response of a getUsage request)
//set the delay if needed
if (mJSONResponse.GetValue("result").SelectToken("advisoryDelay", false) != null)
{
mLastResponseReceived = DateTime.Now.Ticks;
mAdvisoryDelay = Convert.ToInt64(mJSONResponse.GetValue("result").SelectToken("advisoryDelay"));
}
}
/// <summary>
/// Do the actual connect() call to to open the connection and send the data over the network
/// </summary>
private void DoPost()
{
Stream requestStream = null; ;
StreamReader reader = null; ;
WebResponse response = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
//set HTTP properties
request.Method = "POST";
request.ContentType = CONTENT_TYPE;
byte[] bytes = Encoding.UTF8.GetBytes(mJSONRequest.ToString());
try
{
using (requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
using (response = request.GetResponse())
{
using (reader = new StreamReader(response.GetResponseStream()))
{
string content = reader.ReadToEnd();
mJSONResponse = JObject.Parse(content);
}
}
}
}
catch (Exception e)
{
throw new RandomJSONRPCRunTimeException("Code: 9999", e);
}
finally
{
// Clean up resources
requestStream.Flush();
requestStream.Close();
reader.Close();
response.Close();
}
}
/// <summary>
/// Check if an error occurred and in that case throw the appropriate exception
/// </summary>
private void ErrorCheck()
{
JObject error;
if (!(mJSONResponse.GetValue("error") != null))
return;
else
{
error = (JObject)mJSONResponse.GetValue("error");
int errorCode = (int)error.SelectToken("code");
string message = (string)error.SelectToken("message");
//the cases where an illegal argument has been supplied by the user
if (errorCode == 200 || errorCode == 201 || errorCode == 202 || errorCode == 203 || errorCode == 300 || errorCode == 301 || errorCode == 301 || errorCode == 400 || errorCode == 401)
throw new RandomJSONRPCException("Code: " + Convert.ToString(errorCode) + ". Message: " + message);
//the case where an unknown error occurred, or an error that has nothing to do with the parameters supplied by the client occurred
throw new RandomJSONRPCRunTimeException("Code: " + Convert.ToString(errorCode) + ". Message: " + message);
}
}
/// <summary>
/// Returns the number of objects left on the quota
/// </summary>
/// <returns></returns>
private int GetObjectsLeft(string value, string token)
{
if (mJSONResponse == null || DateTime.Now.Ticks > mLastResponseReceived + ONE_HOUR_IN_MILLIS)
GetUsage();
JObject resultObject = (JObject)mJSONResponse.GetValue(value);
return (int)resultObject.GetValue(token);
}
/// <summary>
/// Extract integers from the JSON response object
/// </summary>
/// <returns>An array containing the integers</returns>
private int[] ExtractInts()
{
JArray dataArray = UnwrapJSONResponse();
int length = dataArray.Count();
int i = 0;
int[] result = new int[length];
while (i < length)
{
result[i] = (int)dataArray[i];
i++;
}
return result;
}
/// <summary>
/// Extract doubles from the JSON response object
/// </summary>
/// <returns>An array containing the doubles</returns>
private double[] ExtractDoubles()
{
JArray dataArray = UnwrapJSONResponse();
int length = dataArray.Count();
int i = 0;
double[] result = new double[length];
while (i < length)
{
result[i] = (Double)dataArray[i];
i++;
}
return result;
}
/// <summary>
/// Extract strings from the JSON response object
/// </summary>
/// <returns>An array containing the strings</returns>
private String[] ExtractStrings()
{
JArray dataArray = UnwrapJSONResponse();
int length = dataArray.Count();
int i = 0;
string[] result = new string[length];
while (i < length)
{
result[i] = (string)dataArray[i];
i++;
}
return result;
}
/// <summary>
/// Extract UUIDs from the JSON response object
/// </summary>
/// <returns>An array containing the UUIDs</returns>
private Guid[] ExtractUUIDs()
{
JArray dataArray = UnwrapJSONResponse();
int length = dataArray.Count();
int i = 0;
Guid[] result = new Guid[length];
while (i < length)
{
result[i] = (Guid)dataArray[i];
i++;
}
return result;
}
/// <summary>
/// Unwrap the data from inside the result and random fields
/// </summary>
/// <returns>The JSON object with the data</returns>
private JArray UnwrapJSONResponse()
{
if (!mJSONResponse.GetValue("result").HasValues)
{
throw new RandomJSONRPCException("Code: 9999" + ". Message: Request is valid but Response result payload is null");
}
// allows later interrogation for signed methods
ResultObject = (JObject)mJSONResponse.GetValue(RESULT);
RandomObject = (JObject)ResultObject.GetValue(RANDOM);
return (JArray)RandomObject.GetValue("data");
}
/// <summary>
/// Getters/Setters for the JSON responses
/// </summary>
private JObject ResultObject { get; set; }
private JObject RandomObject { get; set; }
}
}