-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathExampleTests.cs
1445 lines (1239 loc) · 56.5 KB
/
ExampleTests.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 NRedisStack.DataTypes;
using NRedisStack.RedisStackCommands;
using NRedisStack.Search;
using NRedisStack.Search.Aggregation;
using NRedisStack.Search.Literals.Enums;
using StackExchange.Redis;
using Xunit;
using Xunit.Abstractions;
using static NRedisStack.Search.Schema;
namespace NRedisStack.Tests;
public class ExampleTests : AbstractNRedisStackTest, IDisposable
{
private readonly ITestOutputHelper testOutputHelper;
// private readonly string key = "EXAMPLES_TESTS";
public ExampleTests(RedisFixture redisFixture, ITestOutputHelper testOutputHelper) : base(redisFixture)
{
this.testOutputHelper = testOutputHelper;
}
[SkipIfRedis(Is.OSSCluster)]
public void HSETandSearch()
{
// Connect to the Redis server
// var redis = ConnectionMultiplexer.Connect("localhost");
// Get a reference to the database and for search commands:
// var db = redis.GetDatabase();
var db = redisFixture.Redis.GetDatabase();
db.Execute("FLUSHALL");
var ft = db.FT();
// Use HSET to add a field-value pair to a hash
db.HashSet("professor:5555", new HashEntry[] { new("first", "Albert"), new("last", "Blue"), new("age", "55") });
db.HashSet("student:1111", new HashEntry[] { new("first", "Joe"), new("last", "Dod"), new("age", "18") });
db.HashSet("pupil:2222", new HashEntry[] { new("first", "Jen"), new("last", "Rod"), new("age", "14") });
db.HashSet("student:3333", new HashEntry[] { new("first", "El"), new("last", "Mark"), new("age", "17") });
db.HashSet("pupil:4444", new HashEntry[] { new("first", "Pat"), new("last", "Shu"), new("age", "21") });
db.HashSet("student:5555", new HashEntry[] { new("first", "Joen"), new("last", "Ko"), new("age", "20") });
db.HashSet("teacher:6666", new HashEntry[] { new("first", "Pat"), new("last", "Rod"), new("age", "20") });
// Create the schema to index first and last as text fields, and age as a numeric field
var schema = new Schema().AddTextField("first").AddTextField("last").AddNumericField("age");
// Filter the index to only include hashes with an age greater than 16, and prefix of student: or pupil:
var parameters = FTCreateParams.CreateParams().Filter("@age>16").Prefix("student:", "pupil:");
// Create the index
ft.Create("example_index", parameters, schema);
//sleep:
System.Threading.Thread.Sleep(2000);
// Search all hashes in the index
var noFilters = ft.Search("example_index", new Query());
// noFilters now contains: student:1111, student:5555, pupil:4444, student:3333
// Search for hashes with a first name starting with Jo
var startWithJo = ft.Search("example_index", new Query("@first:Jo*"));
// startWithJo now contains: student:1111 (Joe), student:5555 (Joen)
// Search for hashes with first name of Pat
var namedPat = ft.Search("example_index", new Query("@first:Pat"));
// namedPat now contains pupil:4444 (Pat). teacher:6666 (Pat) is not included because it does not have a prefix of student: or pupil:
// Search for hashes with last name of Rod
var lastNameRod = ft.Search("example_index", new Query("@last:Rod"));
// lastNameRod is empty because there are no hashes with a last name of Rod that match the index definition
Assert.Equal(4, noFilters.TotalResults);
Assert.Equal(2, startWithJo.TotalResults);
Assert.Equal(1, namedPat.TotalResults);
Assert.Equal(0, lastNameRod.TotalResults);
}
[Fact]
public async Task AsyncExample()
{
// Connect to the Redis server
// var redis = await ConnectionMultiplexer.ConnectAsync("localhost");
// var db = redis.GetDatabase();
var db = redisFixture.Redis.GetDatabase();
db.Execute("FLUSHALL");
var json = db.JSON();
// call async version of JSON.SET/GET
await json.SetAsync("key", "$", new { name = "John", age = 30, city = "New York" });
var john = await json.GetAsync("key");
}
[Fact]
public void PipelineExample()
{
// Pipeline can get IDatabase for pipeline
IDatabase db = redisFixture.Redis.GetDatabase();
db.Execute("FLUSHALL");
var pipeline = new Pipeline(db);
// Add JsonSet to pipeline
pipeline.Json.SetAsync("person", "$",
new { name = "John", age = 30, city = "New York", nicknames = new[] { "John", "Johny", "Jo" } });
// Increase age by 2
_ = pipeline.Json.NumIncrbyAsync("person", "$.age", 2);
// Clear the nicknames from the Json
_ = pipeline.Json.ClearAsync("person", "$.nicknames");
// Del the nicknames
_ = pipeline.Json.DelAsync("person", "$.nicknames");
// Get the Json response
var getResponse = pipeline.Json.GetAsync("person");
// Execute the pipeline
pipeline.Execute();
// Get the result back JSON
var result = getResponse.Result;
// Assert the result
var expected = "{\"name\":\"John\",\"age\":32,\"city\":\"New York\"}";
Assert.Equal(expected, result.ToString());
}
[SkipIfRedis(Is.OSSCluster)]
public async Task JsonWithSearchPipeline()
{
IDatabase db = redisFixture.Redis.GetDatabase();
db.Execute("FLUSHALL");
//Setup pipeline connection
var pipeline = new Pipeline(db);
// Add JsonSet to pipeline
_ = pipeline.Json.SetAsync("person:01", "$", new { name = "John", age = 30, city = "New York" });
_ = pipeline.Json.SetAsync("person:02", "$", new { name = "Joy", age = 25, city = "Los Angeles" });
_ = pipeline.Json.SetAsync("person:03", "$", new { name = "Mark", age = 21, city = "Chicago" });
_ = pipeline.Json.SetAsync("person:04", "$", new { name = "Steve", age = 24, city = "Phoenix" });
_ = pipeline.Json.SetAsync("person:05", "$", new { name = "Michael", age = 55, city = "San Antonio" });
// Create the schema to index name as text field, age as a numeric field and city as tag field.
var schema = new Schema().AddTextField("name").AddNumericField("age", true).AddTagField("city");
// Filter the index to only include Jsons with prefix of person:
var parameters = FTCreateParams.CreateParams().On(IndexDataType.JSON).Prefix("person:");
// Create the index via pipeline
var create = pipeline.Ft.CreateAsync("person-idx", parameters, schema);
// execute the pipeline
pipeline.Execute();
// Search for all indexed person records
Task.Delay(2000).Wait();
var getAllPersons = await db.FT().SearchAsync("person-idx", new Query());
// Get the total count of people records that indexed.
var count = getAllPersons.TotalResults;
// Gets the first person form the result.
var firstPerson = getAllPersons.Documents.FirstOrDefault();
// first person is John here.
Assert.True(create.Result);
Assert.Equal(5, count);
// Assert.Equal("person:01", firstPerson?.Id);
}
[SkipIfRedis(Is.OSSCluster, Is.Enterprise)]
public async Task PipelineWithAsync()
{
// Connect to the Redis server
// var redis = ConnectionMultiplexer.Connect("localhost");
// Get a reference to the database
// var db = redis.GetDatabase();
var db = redisFixture.Redis.GetDatabase();
db.Execute("FLUSHALL");
// Setup pipeline connection
var pipeline = new Pipeline(db);
// Create metadata labels for time-series.
TimeSeriesLabel label1 = new TimeSeriesLabel("temp", "TLV");
TimeSeriesLabel label2 = new TimeSeriesLabel("temp", "JLM");
var labels1 = new List<TimeSeriesLabel> { label1 };
var labels2 = new List<TimeSeriesLabel> { label2 };
// Create a new time-series.
_ = pipeline.Ts.CreateAsync("temp:TLV", labels: labels1);
_ = pipeline.Ts.CreateAsync("temp:JLM", labels: labels2);
// Adding multiple sequence of time-series data.
List<(string, TimeStamp, double)> sequence1 =
new()
{
("temp:TLV", 1000, 30),
("temp:TLV", 1010, 35),
("temp:TLV", 1020, 9999),
("temp:TLV", 1030, 40)
};
List<(string, TimeStamp, double)> sequence2 =
new()
{
("temp:JLM", 1005, 30),
("temp:JLM", 1015, 35),
("temp:JLM", 1025, 9999),
("temp:JLM", 1035, 40)
};
// Adding multiple samples to multiple series.
_ = pipeline.Ts.MAddAsync(sequence1);
_ = pipeline.Ts.MAddAsync(sequence2);
// Execute the pipeline
pipeline.Execute();
// Get a reference to the database and for time-series commands
var ts = db.TS();
// Get only the location label for each last sample, use SELECTED_LABELS.
var response = await ts.MGetAsync(new List<string> { "temp=JLM" },
selectedLabels: new List<string> { "location" });
// Assert the response
Assert.Equal(1, response.Count);
Assert.Equal("temp:JLM", response[0].key);
}
[SkipIfRedis(Is.OSSCluster, Is.Enterprise)]
public void TransactionExample()
{
// Connect to the Redis server
// var redis = ConnectionMultiplexer.Connect("localhost");
// Get a reference to the database
// var db = redis.GetDatabase();
var db = redisFixture.Redis.GetDatabase();
db.Execute("FLUSHALL");
// Setup transaction with IDatabase
var tran = new Transaction(db);
// Add account details with Json.Set to transaction
_ = tran.Json.SetAsync("accdetails:Jeeva", "$", new { name = "Jeeva", totalAmount = 1000, bankName = "City" });
_ = tran.Json.SetAsync("accdetails:Shachar", "$",
new { name = "Shachar", totalAmount = 1000, bankName = "City" });
// Get the Json response
var getShachar = tran.Json.GetAsync("accdetails:Shachar");
var getJeeva = tran.Json.GetAsync("accdetails:Jeeva");
// Debit 200 from Jeeva
_ = tran.Json.NumIncrbyAsync("accdetails:Jeeva", "$.totalAmount", -200);
// Credit 200 from Shachar
_ = tran.Json.NumIncrbyAsync("accdetails:Shachar", "$.totalAmount", 200);
// Get total amount for both Jeeva = 800 & Shachar = 1200
var totalAmtOfJeeva = tran.Json.GetAsync("accdetails:Jeeva", path: "$.totalAmount");
var totalAmtOfShachar = tran.Json.GetAsync("accdetails:Shachar", path: "$.totalAmount");
// Execute the transaction
var condition = tran.ExecuteAsync();
// Assert
Assert.True(condition.Result);
Assert.NotEmpty(getJeeva.Result.ToString());
Assert.NotEmpty(getShachar.Result.ToString());
Assert.Equal("[800]", totalAmtOfJeeva.Result.ToString());
Assert.Equal("[1200]", totalAmtOfShachar.Result.ToString());
}
[SkipIfRedis(Is.OSSCluster)]
public void TestJsonConvert()
{
// ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
// IDatabase db = redis.GetDatabase();
var db = redisFixture.Redis.GetDatabase();
db.Execute("FLUSHALL");
ISearchCommands ft = db.FT();
IJsonCommands json = db.JSON();
ft.Create("test", new FTCreateParams().On(IndexDataType.JSON).Prefix("doc:"),
new Schema().AddTagField(new FieldName("$.name", "name")));
for (int i = 0; i < 10; i++)
{
json.Set("doc:" + i, "$", "{\"name\":\"foo\"}");
}
var res = ft.Search("test", new Query("@name:{foo}"));
var docs = res.ToJson();
Assert.Equal(10, docs.Count());
}
#if CI_RUN_TESTS
#if NET481
[Fact]
public void TestRedisCloudConnection_net481()
{
var root = Path.GetFullPath(Directory.GetCurrentDirectory());
var redisCaPath = Path.GetFullPath(Path.Combine(root, "redis_ca.pem"));
var redisUserCrtPath = Path.GetFullPath(Path.Combine(root, "redis_user.crt"));
var redisUserPrivateKeyPath = Path.GetFullPath(Path.Combine(root, "redis_user_private.key"));
var password = Environment.GetEnvironmentVariable("PASSWORD") ?? throw new Exception("PASSWORD is not set.");
var endpoint = Environment.GetEnvironmentVariable("ENDPOINT") ?? throw new Exception("ENDPOINT is not set.");
// Load the Redis credentials
var redisUserCertificate = new X509Certificate2(File.ReadAllBytes(redisUserCrtPath));
var redisCaCertificate = new X509Certificate2(File.ReadAllBytes(redisCaPath));
var rsa = RSA.Create();
var redisUserPrivateKeyText = File.ReadAllText(redisUserPrivateKeyPath).Trim();
rsa.ImportParameters(ImportPrivateKey(redisUserPrivateKeyText));
var clientCert = redisUserCertificate.CopyWithPrivateKey(rsa);
// Connect to Redis Cloud
var redisConfiguration = new ConfigurationOptions
{
EndPoints = { endpoint },
Ssl = true,
Password = password
};
redisConfiguration.CertificateSelection +=
(_, _, _, _, _) => new X509Certificate2(clientCert.Export(X509ContentType.Pfx));
redisConfiguration.CertificateValidation += (_, cert, _, errors) =>
{
if (errors == SslPolicyErrors.None)
{
return true;
}
var privateChain = new X509Chain();
privateChain.ChainPolicy = new X509ChainPolicy { RevocationMode = X509RevocationMode.NoCheck };
X509Certificate2 cert2 = new X509Certificate2(cert!);
privateChain.ChainPolicy.ExtraStore.Add(redisCaCertificate);
privateChain.Build(cert2);
bool isValid = true;
// we're establishing the trust chain so if the only complaint is that that the root CA is untrusted, and the root CA root
// matches our certificate, we know it's ok
foreach (X509ChainStatus chainStatus in privateChain.ChainStatus.Where(x =>
x.Status != X509ChainStatusFlags.UntrustedRoot))
{
if (chainStatus.Status != X509ChainStatusFlags.NoError)
{
isValid = false;
break;
}
}
return isValid;
};
var redis = ConnectionMultiplexer.Connect(redisConfiguration);
var db = redis.GetDatabase();
db.Ping();
}
public static RSAParameters ImportPrivateKey(string pem)
{
using var sr = new StringReader(pem);
PemReader pr = new PemReader(sr);
RSAParameters rp = new RSAParameters();
while (sr.Peek() != -1)
{
var privKey = pr.ReadObject() as AsymmetricCipherKeyPair;
if (privKey != null)
{
var pkParamaters = (RsaPrivateCrtKeyParameters)privKey.Private;
rp.Modulus = pkParamaters.Modulus.ToByteArrayUnsigned();
rp.Exponent = pkParamaters.PublicExponent.ToByteArrayUnsigned();
rp.P = pkParamaters.P.ToByteArrayUnsigned();
rp.Q = pkParamaters.Q.ToByteArrayUnsigned();
rp.D = ConvertRSAParametersField(pkParamaters.Exponent, rp.Modulus.Length);
rp.DP = ConvertRSAParametersField(pkParamaters.DP, rp.P.Length);
rp.DQ = ConvertRSAParametersField(pkParamaters.DQ, rp.Q.Length);
rp.InverseQ = ConvertRSAParametersField(pkParamaters.QInv, rp.Q.Length);
}
else
{
throw new ArgumentException("Pem is malformed and could not be parsed");
}
}
pr.ReadObject();
return rp;
}
private static byte[] ConvertRSAParametersField(BigInteger n, int size)
{
byte[] bs = n.ToByteArrayUnsigned();
if (bs.Length == size)
return bs;
if (bs.Length > size)
throw new ArgumentException("Specified size too small", "size");
byte[] padded = new byte[size];
Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);
return padded;
}
#endif
#if NET6_0_OR_GREATER
[Fact]
public void TestRedisCloudConnection()
{
var root = Path.GetFullPath(Directory.GetCurrentDirectory());
var redisCaPath = Path.GetFullPath(Path.Combine(root, "redis_ca.pem"));
var redisUserCrtPath = Path.GetFullPath(Path.Combine(root, "redis_user.crt"));
var redisUserPrivateKeyPath = Path.GetFullPath(Path.Combine(root, "redis_user_private.key"));
var password = Environment.GetEnvironmentVariable("PASSWORD") ?? throw new Exception("PASSWORD is not set.");
var endpoint = Environment.GetEnvironmentVariable("ENDPOINT") ?? throw new Exception("ENDPOINT is not set.");
// Load the Redis credentials
var redisUserCertificate = new X509Certificate2(File.ReadAllBytes(redisUserCrtPath));
var redisCaCertificate = new X509Certificate2(File.ReadAllBytes(redisCaPath));
var rsa = RSA.Create();
var redisUserPrivateKeyText = File.ReadAllText(redisUserPrivateKeyPath);
var pemFileData = File.ReadAllLines(redisUserPrivateKeyPath).Where(x => !x.StartsWith("-"));
var binaryEncoding = Convert.FromBase64String(string.Join(null, pemFileData));
rsa.ImportRSAPrivateKey(binaryEncoding, out _);
redisUserCertificate.CopyWithPrivateKey(rsa);
rsa.ImportFromPem(redisUserPrivateKeyText.ToCharArray());
var clientCert = redisUserCertificate.CopyWithPrivateKey(rsa);
// Connect to Redis Cloud
var redisConfiguration = new ConfigurationOptions
{
EndPoints = { endpoint },
Ssl = true,
Password = password
};
redisConfiguration.CertificateSelection += (_, _, _, _, _) => clientCert;
redisConfiguration.CertificateValidation += (_, cert, _, errors) =>
{
if (errors == SslPolicyErrors.None)
{
return true;
}
var privateChain = new X509Chain();
privateChain.ChainPolicy = new X509ChainPolicy { RevocationMode = X509RevocationMode.NoCheck };
X509Certificate2 cert2 = new X509Certificate2(cert!);
privateChain.ChainPolicy.ExtraStore.Add(redisCaCertificate);
privateChain.Build(cert2);
bool isValid = true;
// we're establishing the trust chain so if the only complaint is that that the root CA is untrusted, and the root CA root
// matches our certificate, we know it's ok
foreach (X509ChainStatus chainStatus in privateChain.ChainStatus.Where(x =>
x.Status != X509ChainStatusFlags.UntrustedRoot))
{
if (chainStatus.Status != X509ChainStatusFlags.NoError)
{
isValid = false;
break;
}
}
return isValid;
};
var redis = ConnectionMultiplexer.Connect(redisConfiguration);
var db = redis.GetDatabase();
db.Ping();
}
[Fact]
public void TestRedisCloudConnection_DotnetCore3()
{
// Replace this with your own Redis Cloud credentials
var root = Path.GetFullPath(Directory.GetCurrentDirectory());
var redisCaPath = Path.GetFullPath(Path.Combine(root, "redis_ca.pem"));
var redisUserCrtPath = Path.GetFullPath(Path.Combine(root, "redis_user.crt"));
var redisUserPrivateKeyPath = Path.GetFullPath(Path.Combine(root, "redis_user_private.key"));
var password = Environment.GetEnvironmentVariable("PASSWORD") ?? throw new Exception("PASSWORD is not set.");
var endpoint = Environment.GetEnvironmentVariable("ENDPOINT") ?? throw new Exception("ENDPOINT is not set.");
// Load the Redis credentials
var redisUserCertificate = new X509Certificate2(File.ReadAllBytes(redisUserCrtPath));
var redisCaCertificate = new X509Certificate2(File.ReadAllBytes(redisCaPath));
var rsa = RSA.Create();
var redisUserPrivateKeyText = File.ReadAllText(redisUserPrivateKeyPath);
var pemFileData = File.ReadAllLines(redisUserPrivateKeyPath).Where(x => !x.StartsWith("-"));
var binaryEncoding = Convert.FromBase64String(string.Join(null, pemFileData));
rsa.ImportRSAPrivateKey(binaryEncoding, out _);
redisUserCertificate.CopyWithPrivateKey(rsa);
rsa.ImportFromPem(redisUserPrivateKeyText.ToCharArray());
var clientCert = redisUserCertificate.CopyWithPrivateKey(rsa);
var sslOptions = new SslClientAuthenticationOptions
{
CertificateRevocationCheckMode = X509RevocationMode.NoCheck,
LocalCertificateSelectionCallback = (_, _, _, _, _) => clientCert,
RemoteCertificateValidationCallback = (_, cert, _, errors) =>
{
if (errors == SslPolicyErrors.None)
{
return true;
}
var privateChain = new X509Chain();
privateChain.ChainPolicy = new X509ChainPolicy { RevocationMode = X509RevocationMode.NoCheck };
X509Certificate2 cert2 = new X509Certificate2(cert!);
privateChain.ChainPolicy.ExtraStore.Add(redisCaCertificate);
privateChain.Build(cert2);
bool isValid = true;
// we're establishing the trust chain so if the only complaint is that that the root CA is untrusted, and the root CA root
// matches our certificate, we know it's ok
foreach (X509ChainStatus chainStatus in privateChain.ChainStatus.Where(x=>x.Status != X509ChainStatusFlags.UntrustedRoot))
{
if (chainStatus.Status != X509ChainStatusFlags.NoError)
{
isValid = false;
break;
}
}
return isValid;
},
TargetHost = endpoint
};
// Connect to Redis Cloud
var redisConfiguration = new ConfigurationOptions
{
EndPoints = { endpoint },
Ssl = true,
SslHost = sslOptions.TargetHost,
SslClientAuthenticationOptions = host => sslOptions,
Password = password
};
var redis = ConnectionMultiplexer.Connect(redisConfiguration);
var db = redis.GetDatabase();
db.Ping();
db.StringSet("testKey", "testValue");
var value = db.StringGet("testKey");
Assert.Equal("testValue", value);
}
#endif
#endif
[Fact]
public void BasicJsonExamplesTest()
{
// ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
// IDatabase db = redis.GetDatabase();
var db = redisFixture.Redis.GetDatabase();
db.Execute("FLUSHALL");
IJsonCommands json = db.JSON();
// Insert a simple KVP as a JSON object:
Assert.True(json.Set("ex1:1", "$", "\"val\""));
// Insert a single-property JSON object:
Assert.True(json.Set("ex1:2", "$", new { field1 = "val1" }));
// Insert a JSON object with multiple properties:
Assert.True(json.Set("ex1:3", "$", new
{
field1 = "val1",
field2 = "val2"
}));
// Insert a JSON object with multiple properties of different data types:
Assert.True(json.Set("ex1:4", "$", new
{
field1 = "val1",
field2 = "val2",
field3 = true,
field4 = (string?)null
}));
// Insert a JSON object that contains an array:
Assert.True(json.Set("ex1:5", "$", new
{
arr1 = new[] { "val1", "val2", "val3" }
}));
// Insert a JSON object that contains a nested object:
Assert.True(json.Set("ex1:6", "$", new
{
obj1 = new
{
str1 = "val1",
num2 = 2
}
}));
// Insert a JSON object with a mixture of property data types:
Assert.True(json.Set("ex1:7", "$", new
{
str1 = "val1",
str2 = "val2",
arr1 = new[] { 1, 2, 3, 4 },
obj1 = new
{
num1 = 1,
arr2 = new[] { "val1", "val2", "val3" }
}
}));
// Set and fetch a simple JSON KVP:
json.Set("ex2:1", "$", "\"val\"");
var res = json.Get(key: "ex2:1",
path: "$",
indent: "\t",
newLine: "\n"
);
Assert.Equal("[\n\t\"val\"\n]", res.ToString());
// Set and fetch a single property from a JSON object:
json.Set("ex2:2", "$", new
{
field1 = "val1"
});
res = json.Get(key: "ex2:2",
path: "$.field1",
indent: "\t",
newLine: "\n"
);
Assert.Equal("[\n\t\"val1\"\n]", res.ToString());
// Fetch multiple properties:
json.Set("ex2:3", "$", new
{
field1 = "val1",
field2 = "val2"
});
// sleep
Thread.Sleep(2000);
res = json.Get(key: "ex2:3",
paths: new[] { "$.field1", "$.field2" },
indent: "\t",
newLine: "\n"
);
var actualJson = res.ToString();
var expectedJson1 = "{\n\t\"$.field1\":[\n\t\t\"val1\"\n\t],\n\t\"$.field2\":[\n\t\t\"val2\"\n\t]\n}";
var expectedJson2 = "{\n\t\"$.field2\":[\n\t\t\"val2\"\n\t],\n\t\"$.field1\":[\n\t\t\"val1\"\n\t]\n}";
Assert.True(actualJson == expectedJson1 || actualJson == expectedJson2);
// Fetch a property nested in another JSON object:
json.Set("ex2:4", "$", new
{
obj1 = new
{
str1 = "val1",
num2 = 2
}
});
res = json.Get(key: "ex2:4",
path: "$.obj1.num2",
indent: "\t",
newLine: "\n"
);
Assert.Equal("[\n\t2\n]", res.ToString());
// Fetch properties within an array and utilize array subscripting:
json.Set("ex2:5", "$", new
{
str1 = "val1",
str2 = "val2",
arr1 = new[] { 1, 2, 3, 4 },
obj1 = new
{
num1 = 1,
arr2 = new[] { "val1", "val2", "val3" }
}
});
res = json.Get(key: "ex2:5",
path: "$.obj1.arr2",
indent: "\t",
newLine: "\n"
);
Assert.Equal("[\n\t[\n\t\t\"val1\",\n\t\t\"val2\",\n\t\t\"val3\"\n\t]\n]", res.ToString());
res = json.Get(key: "ex2:5",
path: "$.arr1[1]",
indent: "\t",
newLine: "\n"
);
Assert.Equal("[\n\t2\n]", res.ToString());
res = json.Get(key: "ex2:5",
path: "$.obj1.arr2[0:2]",
indent: "\t",
newLine: "\n"
);
Assert.Equal("[\n\t\"val1\",\n\t\"val2\"\n]", res.ToString());
res = json.Get(key: "ex2:5",
path: "$.arr1[-2:]",
indent: "\t",
newLine: "\n"
);
Assert.Equal("[\n\t3,\n\t4\n]", res.ToString());
// Update an entire JSON object:
json.Set("ex3:1", "$", new { field1 = "val1" });
json.Set("ex3:1", "$", new { foo = "bar" });
res = json.Get(key: "ex3:1",
indent: "\t",
newLine: "\n"
);
Assert.Equal("{\n\t\"foo\":\"bar\"\n}", res.ToString());
// Update a single property within an object:
json.Set("ex3:2", "$", new
{
field1 = "val1",
field2 = "val2"
});
json.Set("ex3:2", "$.field1", "\"foo\"");
res = json.Get(key: "ex3:2",
indent: "\t",
newLine: "\n"
);
Assert.Equal("{\n\t\"field1\":\"foo\",\n\t\"field2\":\"val2\"\n}", res.ToString());
// Update a property in an embedded JSON object:
json.Set("ex3:3", "$", new
{
obj1 = new
{
str1 = "val1",
num2 = 2
}
});
json.Set("ex3:3", "$.obj1.num2", 3);
res = json.Get(key: "ex3:3",
indent: "\t",
newLine: "\n"
);
Assert.Equal("{\n\t\"obj1\":{\n\t\t\"str1\":\"val1\",\n\t\t\"num2\":3\n\t}\n}", res.ToString());
// Update an item in an array via index:
json.Set("ex3:4", "$", new
{
arr1 = new[] { "val1", "val2", "val3" }
});
json.Set("ex3:4", "$.arr1[0]", "\"foo\"");
res = json.Get(key: "ex3:4",
indent: "\t",
newLine: "\n"
);
Assert.Equal("{\n\t\"arr1\":[\n\t\t\"foo\",\n\t\t\"val2\",\n\t\t\"val3\"\n\t]\n}", res.ToString());
// Delete entire object/key:
json.Set("ex4:1", "$", new { field1 = "val1" });
json.Del("ex4:1");
res = json.Get(key: "ex4:1",
indent: "\t",
newLine: "\n"
);
Assert.Equal("", res.ToString());
// Delete a single property from an object:
json.Set("ex4:2", "$", new
{
field1 = "val1",
field2 = "val2"
});
json.Del("ex4:2", "$.field1");
res = json.Get(key: "ex4:2",
indent: "\t",
newLine: "\n"
);
Assert.Equal("{\n\t\"field2\":\"val2\"\n}", res.ToString());
// Delete a property from an embedded object:
json.Set("ex4:3", "$", new
{
obj1 = new
{
str1 = "val1",
num2 = 2
}
});
json.Del("ex4:3", "$.obj1.num2");
res = json.Get(key: "ex4:3",
indent: "\t",
newLine: "\n"
);
Assert.Equal("{\n\t\"obj1\":{\n\t\t\"str1\":\"val1\"\n\t}\n}", res.ToString());
// Delete a single item from an array:
json.Set("ex4:4", "$", new
{
arr1 = new[] { "val1", "val2", "val3" }
});
json.Del("ex4:4", "$.arr1[0]");
res = json.Get(key: "ex4:4",
indent: "\t",
newLine: "\n"
);
Assert.Equal("{\n\t\"arr1\":[\n\t\t\"val2\",\n\t\t\"val3\"\n\t]\n}", res.ToString());
}
[Fact]
public void AdvancedJsonExamplesTest()
{
// ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
// IDatabase db = redis.GetDatabase();
var db = redisFixture.Redis.GetDatabase();
db.Execute("FLUSHALL");
IJsonCommands json = db.JSON();
json.Set("warehouse:1", "$", new
{
city = "Boston",
location = "42.361145, -71.057083",
inventory = new[]
{
new
{
id = 15970,
gender = "Men",
season = new[] { "Fall", "Winter" },
description = "Turtle Check Men Navy Blue Shirt",
price = 34.95
},
new
{
id = 59263,
gender = "Women",
season = new[] { "Fall", "Winter", "Spring", "Summer" },
description = "Titan Women Silver Watch",
price = 129.99
},
new
{
id = 46885,
gender = "Boys",
season = new[] { "Fall" },
description = "Ben 10 Boys Navy Blue Slippers",
price = 45.99
}
}
});
// Fetch all properties of an array:
var res = json.Get(key: "warehouse:1",
path: "$.inventory[*]",
indent: "\t",
newLine: "\n"
);
var expected =
"[\n\t{\n\t\t\"id\":15970,\n\t\t\"gender\":\"Men\",\n\t\t\"season\":[\n\t\t\t\"Fall\",\n\t\t\t\"Winter\"\n\t\t],\n\t\t\"description\":\"Turtle Check Men Navy Blue Shirt\",\n\t\t\"price\":34.95\n\t},\n\t{\n\t\t\"id\":59263,\n\t\t\"gender\":\"Women\",\n\t\t\"season\":[\n\t\t\t\"Fall\",\n\t\t\t\"Winter\",\n\t\t\t\"Spring\",\n\t\t\t\"Summer\"\n\t\t],\n\t\t\"description\":\"Titan Women Silver Watch\",\n\t\t\"price\":129.99\n\t},\n\t{\n\t\t\"id\":46885,\n\t\t\"gender\":\"Boys\",\n\t\t\"season\":[\n\t\t\t\"Fall\"\n\t\t],\n\t\t\"description\":\"Ben 10 Boys Navy Blue Slippers\",\n\t\t\"price\":45.99\n\t}\n]";
Assert.Equal(expected, res.ToString()); // TODO: fine nicer way to compare the two JSON strings
// Fetch all values of a field within an array:
res = json.Get(
key: "warehouse:1",
path: "$.inventory[*].price",
indent: "\t",
newLine: "\n"
);
expected = "[\n\t34.95,\n\t129.99,\n\t45.99\n]";
Assert.Equal(expected, res.ToString());
// Fetch all items within an array where a text field matches a given value:
res = json.Get(
key: "warehouse:1",
path: "$.inventory[?(@.description==\"Turtle Check Men Navy Blue Shirt\")]",
indent: "\t",
newLine: "\n"
);
expected =
"[\n\t{\n\t\t\"id\":15970,\n\t\t\"gender\":\"Men\",\n\t\t\"season\":[\n\t\t\t\"Fall\",\n\t\t\t\"Winter\"\n\t\t],\n\t\t\"description\":\"Turtle Check Men Navy Blue Shirt\",\n\t\t\"price\":34.95\n\t}\n]";
Assert.Equal(expected, res.ToString());
// Fetch all items within an array where a numeric field is less than a given value:
res = json.Get(key: "warehouse:1",
path: "$.inventory[?(@.price<100)]",
indent: "\t",
newLine: "\n"
);
expected =
"[\n\t{\n\t\t\"id\":15970,\n\t\t\"gender\":\"Men\",\n\t\t\"season\":[\n\t\t\t\"Fall\",\n\t\t\t\"Winter\"\n\t\t],\n\t\t\"description\":\"Turtle Check Men Navy Blue Shirt\",\n\t\t\"price\":34.95\n\t},\n\t{\n\t\t\"id\":46885,\n\t\t\"gender\":\"Boys\",\n\t\t\"season\":[\n\t\t\t\"Fall\"\n\t\t],\n\t\t\"description\":\"Ben 10 Boys Navy Blue Slippers\",\n\t\t\"price\":45.99\n\t}\n]";
Assert.Equal(expected, res.ToString());
// Fetch all items within an array where a numeric field is less than a given value:
res = json.Get(key: "warehouse:1",
path: "$.inventory[?(@.id>=20000)]",
indent: "\t",
newLine: "\n"
);
expected =
"[\n\t{\n\t\t\"id\":59263,\n\t\t\"gender\":\"Women\",\n\t\t\"season\":[\n\t\t\t\"Fall\",\n\t\t\t\"Winter\",\n\t\t\t\"Spring\",\n\t\t\t\"Summer\"\n\t\t],\n\t\t\"description\":\"Titan Women Silver Watch\",\n\t\t\"price\":129.99\n\t},\n\t{\n\t\t\"id\":46885,\n\t\t\"gender\":\"Boys\",\n\t\t\"season\":[\n\t\t\t\"Fall\"\n\t\t],\n\t\t\"description\":\"Ben 10 Boys Navy Blue Slippers\",\n\t\t\"price\":45.99\n\t}\n]";
Assert.Equal(expected, res.ToString());
// Fetch all items within an array where a numeric field is less than a given value:
res = json.Get(key: "warehouse:1",
path: "$.inventory[?(@.gender==\"Men\"&&@.price>20)]",
indent: "\t",
newLine: "\n"
);
expected =
"[\n\t{\n\t\t\"id\":15970,\n\t\t\"gender\":\"Men\",\n\t\t\"season\":[\n\t\t\t\"Fall\",\n\t\t\t\"Winter\"\n\t\t],\n\t\t\"description\":\"Turtle Check Men Navy Blue Shirt\",\n\t\t\"price\":34.95\n\t}\n]";
Assert.Equal(expected, res.ToString());
// Fetch all items within an array that meet at least one relational operation.
// In this case, return only the ids of those items:
res = json.Get(key: "warehouse:1",
path: "$.inventory[?(@.price<100||@.gender==\"Women\")].id",
indent: "\t",
newLine: "\n"
);
expected = "[\n\t15970,\n\t59263,\n\t46885\n]";
Assert.Equal(expected, res.ToString());
// Fetch all items within an array that match a given regex pattern.
res = json.Get(key: "warehouse:1",
path: "$.inventory[?(@.description =~ \"Blue\")]",
indent: "\t",
newLine: "\n"
);
expected =
"[\n\t{\n\t\t\"id\":15970,\n\t\t\"gender\":\"Men\",\n\t\t\"season\":[\n\t\t\t\"Fall\",\n\t\t\t\"Winter\"\n\t\t],\n\t\t\"description\":\"Turtle Check Men Navy Blue Shirt\",\n\t\t\"price\":34.95\n\t},\n\t{\n\t\t\"id\":46885,\n\t\t\"gender\":\"Boys\",\n\t\t\"season\":[\n\t\t\t\"Fall\"\n\t\t],\n\t\t\"description\":\"Ben 10 Boys Navy Blue Slippers\",\n\t\t\"price\":45.99\n\t}\n]";
Assert.Equal(expected, res.ToString());
// Fetch all items within an array where a field contains a term, case insensitive
res = json.Get(key: "warehouse:1",
path: "$.inventory[?(@.description =~ \"(?i)watch\")]",
indent: "\t",
newLine: "\n"
);
expected =
"[\n\t{\n\t\t\"id\":59263,\n\t\t\"gender\":\"Women\",\n\t\t\"season\":[\n\t\t\t\"Fall\",\n\t\t\t\"Winter\",\n\t\t\t\"Spring\",\n\t\t\t\"Summer\"\n\t\t],\n\t\t\"description\":\"Titan Women Silver Watch\",\n\t\t\"price\":129.99\n\t}\n]";
Assert.Equal(expected, res.ToString());
// Fetch all items within an array where a field begins with a given expression
res = json.Get(key: "warehouse:1",
path: "$.inventory[?(@.description =~ \"^T\")]",
indent: "\t",
newLine: "\n"
);
expected =
"[\n\t{\n\t\t\"id\":15970,\n\t\t\"gender\":\"Men\",\n\t\t\"season\":[\n\t\t\t\"Fall\",\n\t\t\t\"Winter\"\n\t\t],\n\t\t\"description\":\"Turtle Check Men Navy Blue Shirt\",\n\t\t\"price\":34.95\n\t},\n\t{\n\t\t\"id\":59263,\n\t\t\"gender\":\"Women\",\n\t\t\"season\":[\n\t\t\t\"Fall\",\n\t\t\t\"Winter\",\n\t\t\t\"Spring\",\n\t\t\t\"Summer\"\n\t\t],\n\t\t\"description\":\"Titan Women Silver Watch\",\n\t\t\"price\":129.99\n\t}\n]";
Assert.Equal(expected, res.ToString());
}
[SkipIfRedis(Is.OSSCluster)]
public void BasicQueryOperationsTest()
{
// ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
// IDatabase db = redis.GetDatabase();
var db = redisFixture.Redis.GetDatabase();
db.Execute("FLUSHALL");
IJsonCommands json = db.JSON();
ISearchCommands ft = db.FT();
json.Set("product:15970", "$", new
{
id = 15970,
gender = "Men",
season = new[] { "Fall", "Winter" },
description = "Turtle Check Men Navy Blue Shirt",
price = 34.95,
city = "Boston",
coords = "-71.057083, 42.361145"
});
json.Set("product:59263", "$", new
{
id = 59263,
gender = "Women",
season = new[] { "Fall", "Winter", "Spring", "Summer" },
description = "Titan Women Silver Watch",
price = 129.99,
city = "Dallas",
coords = "-96.808891, 32.779167"
});
json.Set("product:46885", "$", new
{