-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathProgram.cs
More file actions
2601 lines (2160 loc) · 100 KB
/
Program.cs
File metadata and controls
2601 lines (2160 loc) · 100 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
//
// Program.cs
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using Couchbase.Lite;
using Couchbase.Lite.DI;
using Couchbase.Lite.Enterprise.Query;
using Couchbase.Lite.Logging;
using Couchbase.Lite.P2P;
using Couchbase.Lite.Query;
using Couchbase.Lite.Sync;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.NetworkInformation;
using System.Security;
using System.Security.Cryptography.X509Certificates;
namespace api_walkthrough
{
class Hotel
{
public string Id { get; set; }
public string Name { get; set; }
}
class Program
{
private static readonly Database _Database = null;
private static readonly Replicator _Replicator = null;
private static readonly URLEndpointListener _listener = null;
public void GettingStarted()
{
// tag::getting-started[]
// using System;
// using Couchbase.Lite;
// using Couchbase.Lite.Query;
// using Couchbase.Lite.Sync;
// Get the database (and create it if it doesn't exist)
var database = new Database("mydb");
var collection = database.GetDefaultCollection();
// Create a new document (i.e. a record) in the database
var id = default(string);
using var createdDoc = new MutableDocument();
createdDoc.SetFloat("version", 2.0f)
.SetString("type", "SDK");
// Save it to the database
collection.Save(createdDoc);
id = createdDoc.Id;
// Update a document
using var doc = collection.GetDocument(id);
using var mutableDoc = doc.ToMutable();
createdDoc.SetString("language", "C#");
collection.Save(createdDoc);
using var docAgain = collection.GetDocument(id);
Console.WriteLine($"Document ID :: {docAgain.Id}");
Console.WriteLine($"Learning {docAgain.GetString("language")}");
// Create a query to fetch documents of type SDK
// i.e. SELECT * FROM database WHERE type = "SDK"
using var query = QueryBuilder.Select(SelectResult.All())
.From(DataSource.Collection(collection))
.Where(Expression.Property("type").EqualTo(Expression.String("SDK")));
// Run the query
var result = query.Execute();
Console.WriteLine($"Number of rows :: {result.AllResults().Count}");
// Create replicator to push and pull changes to and from the cloud
var targetEndpoint = new URLEndpoint(new Uri("ws://localhost:4984/getting-started-db"));
var replConfig = new ReplicatorConfiguration(targetEndpoint);
replConfig.AddCollection(database.GetDefaultCollection());
// Add authentication
replConfig.Authenticator = new BasicAuthenticator("john", "pass");
// Create replicator (make sure to add an instance or static variable
// named _Replicator)
var replicator = new Replicator(replConfig);
replicator.AddChangeListener((sender, args) =>
{
if (args.Status.Error != null) {
Console.WriteLine($"Error :: {args.Status.Error}");
}
});
replicator.Start();
// Later, stop and dispose the replicator *before* closing/disposing the database
// end::getting-started[]
}
private static void TestReplicatorConflictResolver()
{
var collection = _Database.GetDefaultCollection();
// tag::replication-conflict-resolver[]
var target = new URLEndpoint(new Uri("ws://localhost:4984/mydatabase"));
var replConfig = new ReplicatorConfiguration(target);
replConfig.AddCollection(collection, new CollectionConfiguration()
{
ConflictResolver = new LocalWinConflictResolver()
});
var replicator = new Replicator(replConfig);
replicator.Start();
// end::replication-conflict-resolver[]
}
private static void TestSaveWithConflictHandler()
{
var collection = _Database.GetDefaultCollection();
// tag::update-document-with-conflict-handler[]
using var doc = collection.GetDocument("xyz");
using var mutableDoc = doc.ToMutable();
mutableDoc.SetString("name", "apples");
collection.Save(mutableDoc, (updated, current) =>
{
var currentDict = current.ToDictionary();
var newDict = updated.ToDictionary();
var result = newDict.Concat(currentDict)
.GroupBy(kv => kv.Key)
.ToDictionary(g => g.Key, g => g.First().Value);
updated.SetData(result);
return true;
});
// end::update-document-with-conflict-handler[]
}
private static bool IsValidCredential(string name, SecureString password) { return true; } // helper
private static void TestInitListener()
{
var database = new Database("other-database");
var collection = database.GetDefaultCollection();
#warning init-urllistener Unused?
// tag::init-urllistener[]
var endpointConfig = new URLEndpointListenerConfiguration(new[] { collection });
endpointConfig.TlsIdentity = null; // Use with anonymous self-signed cert
endpointConfig.Authenticator = new ListenerPasswordAuthenticator((sender, username, password) =>
{
if (IsValidCredential(username, password)) {
return true;
}
return false;
});
var listener = new URLEndpointListener(endpointConfig);
// end::init-urllistener[]
}
private static void TestListenerStart()
{
var listener = _listener;
#warning start-urllistener Unused?
// tag::start-urllistener[]
// CouchbaseLiteException will be thrown when the listener cannot be started. The most common error
// would be that the configured port has already been used.
listener.Start();
// end::start-urllistener[]
}
private static void TestListenerStop()
{
var listener = _listener;
#warning stop-urllistener Unused?
// tag::stop-urllistener[]
listener.Stop();
// end::stop-urllistener[]
}
private static void TestCreateSelfSignedCert()
{
X509Store store =
new X509Store(StoreName.My);
// The identity will be stored in the secure
// storage using the given label.
DateTimeOffset fiveMinToExpireCert = DateTimeOffset.UtcNow.AddMinutes(5);
// tag::create-self-signed-cert[]
// tag::listener-config-tls-id-SelfSigned[]
var identity = TLSIdentity.CreateIdentity(true, /* isServer */
new Dictionary<string, string>() { { Certificate.CommonNameAttribute, "Couchbase Inc" } },
// The common name attribute is required
// when creating a CSR. If it is not presented
// in the cert, an exception is thrown.
fiveMinToExpireCert,
// If the expiration date is not specified,
// the certs expiration will be 365 days
store,
"CBL-Server-Cert",
null); // The key label to get cert in certificate map.
// If null, the same default directory
// for a Couchbase Lite db is used for map.
// end::listener-config-tls-id-SelfSigned[]
// end::create-self-signed-cert[]
}
private static void TestImportTLSIdentity()
{
X509Store store = new X509Store(StoreName.My); // The identity will be stored in the secure storage using the given label
byte[] data = File.ReadAllBytes("C:\\client.p12"); // PKCS12 data containing private key, public key, and certificates
// tag::import-tls-identity[]
// tag::listener-config-tls-id-caCert[]
var identity = TLSIdentity.ImportIdentity(store,
data,
"123", // The password that is needed to access the certificate data
"CBL-Client-Cert",
null); // The key label to get cert in certificate map.
// If null, the same default directory
// for a Couchbase Lite db is used for map.
// end::listener-config-tls-id-caCert[]
// end::import-tls-identity[]
}
private static void TestClientCertAuthenticatorRootCerts()
{
var otherDatabase = new Database("other-database");
var collection = otherDatabase.GetDefaultCollection();
X509Store store = new X509Store(StoreName.My);
#warning client-cert-authenticator-root-certs unused?
// tag::client-cert-authenticator-root-certs[]
byte[] caData, clientData;
clientData = File.ReadAllBytes("C:\\client.p12"); // PKCS12 data containing private key, public key, and certificates
caData = File.ReadAllBytes("C:\\client-ca.der");
// Root certs
var rootCert = new X509Certificate2(caData);
var auth = new ListenerCertificateAuthenticator(new X509Certificate2Collection(rootCert));
// Create URL Endpoint Listener
var listenerConfig = new URLEndpointListenerConfiguration(new[] { collection });
listenerConfig.DisableTLS = false; //The default value is false which means that the TLS will be enabled by default.
listenerConfig.Authenticator = auth;
var listener = new URLEndpointListener(listenerConfig);
listener.Start();
// Client identity
var identity = TLSIdentity.ImportIdentity(store,
clientData,
"123",
"CBL-Client-Cert",
null);
// Replicator -- Client
var database = new Database("client-database");
var builder = new UriBuilder(
"wss",
"localhost",
listener.Port,
$"/{listener.Config.Collections.First().Name}"
);
var url = builder.Uri;
var target = new URLEndpoint(url);
var config = new ReplicatorConfiguration(target);
config.AddCollection(database.GetDefaultCollection());
config.ReplicatorType = ReplicatorType.PushAndPull;
config.Continuous = false;
config.Authenticator = new ClientCertificateAuthenticator(identity);
config.AcceptOnlySelfSignedServerCertificate = true;
config.PinnedServerCertificate = _listener.TlsIdentity.Certs[0];
var replicator = new Replicator(config);
replicator.Start(); // Dispose after stop
// Stop listener after replicator is stopped
listener.Stop();
// end::client-cert-authenticator-root-certs[]
}
private static void TestClientCertAuthenticator()
{
var otherDatabase = new Database("other-database");
var collection = otherDatabase.GetDefaultCollection();
X509Store store = new X509Store(StoreName.My);
#warning client-cert-authenticator unused?
// tag::client-cert-authenticator[]
// Create Listener Certificate Authenticator
var auth = new ListenerCertificateAuthenticator((sender, cert) =>
{
if (cert.Count != 1) {
return false;
}
return cert[0].SubjectName.Name?.Replace("CN=", "") == "couchbase";
});
// Create URL Endpoint Listener
var listenerConfig = new URLEndpointListenerConfiguration(new[] { collection });
listenerConfig.DisableTLS = false; //The default value is false which means that the TLS will be enabled by default.
listenerConfig.Authenticator = auth;
var listener = new URLEndpointListener(listenerConfig);
listener.Start();
// User Identity
var identity = TLSIdentity.CreateIdentity(false,
new Dictionary<string, string>() { { Certificate.CommonNameAttribute, "couchbase" } },
null,
store,
"ClientCertLabel",
null);
// Replicator -- Client
var database = new Database("client-database");
var builder = new UriBuilder(
"wss",
"localhost",
listener.Port,
$"/{listener.Config.Collections.First().Name}"
);
var url = builder.Uri;
var target = new URLEndpoint(url);
var config = new ReplicatorConfiguration(target);
config.AddCollection(database.GetDefaultCollection());
config.ReplicatorType = ReplicatorType.PushAndPull;
config.Continuous = false;
config.Authenticator = new ClientCertificateAuthenticator(identity);
config.AcceptOnlySelfSignedServerCertificate = false;
config.PinnedServerCertificate = _listener.TlsIdentity.Certs[0];
var replicator = new Replicator(config);
replicator.Start(); // Dispose after stopped
// Stop listener after replicator is stopped
listener.Stop();
// end::client-cert-authenticator[]
}
public void IdentityWithLabel()
{
X509Store store = null;
byte[] clientData = null;
var replConfig = new ReplicatorConfiguration(null);
// tag::p2p-tlsid-tlsidentity-with-label[]
// Client identity
var identity =
TLSIdentity.ImportIdentity(store,
clientData,
"123",
"CBL-Client-Cert",
null); // <.>
replConfig.Authenticator =
new ClientCertificateAuthenticator(identity); // <.>
// end::p2p-tlsid-tlsidentity-with-label[]
}
public void UseEncryption()
{
// Enterprise edition only
// tag::database-encryption[]
// Create a new, or open an existing database with encryption enabled
var config = new DatabaseConfiguration
{
// Or, derive a key yourself and pass a byte array of the proper size
EncryptionKey = new EncryptionKey("password")
};
using var database = new Database("seekrit", config);
// Change the encryption key (or add encryption if the DB is unencrypted)
database.ChangeEncryptionKey(new EncryptionKey("betterpassw0rd"));
// Remove encryption
database.ChangeEncryptionKey(null);
// end::database-encryption[]
}
private static void ResetReplicatorCheckpoint()
{
var url = new Uri("ws://localhost:4984/db");
var target = new URLEndpoint(url);
var config = new ReplicatorConfiguration(target);
bool resetCheckpointRequired_Example = true;
config.AddCollection(_Database.GetDefaultCollection());
var replicator = new Replicator(config);
// tag::replication-reset-checkpoint[]
// replicator is a Replicator instance
if (resetCheckpointRequired_Example) {
replicator.Start(true); // <.>
} else {
replicator.Start(false);
}
// Stop and dispose replicator later
// end::replication-reset-checkpoint[]
}
private static void Read1xAttachment()
{
using var doc = new MutableDocument();
// tag::1x-attachment[]
var attachments = doc.GetDictionary("_attachments");
var avatar = attachments.GetBlob("avatar");
var content = avatar?.Content;
// end::1x-attachment[]
}
private static void CreateNewDatabase()
{
// tag::new-database[]
var database = new Database("my-database");
// end::new-database[]
}
private static void CloseDatabase()
{
var database = _Database;
// tag::close-database[]
database.Close();
// end::close-database[]
}
private static void DatabaseFullsync()
{
var config = new DatabaseConfiguration();
// tag::database-fullsync[]
// this enables fullsync
config.FullSync = true;
// end::database-fullsync[]
}
private static void CreateCollection()
{
// tag::scopes-manage-create-collection[]
var collectionWithDefaultScope = _Database.CreateCollection("colA");
var collection = _Database.CreateCollection("colA", "scopeA"); // Scope with named scopeA will be created if it's not existed. There is no public API to create a Scope.
// end::scopes-manage-create-collection[]
}
private static void DeleteCollection()
{
// tag::scopes-manage-drop-collection[]
_Database.DeleteCollection("colA", "scopeA"); // Scope with named scopeA will be deleted if there is no collections in the scope after the last collection is deleted via this API. There is no public API to remove a Scope.
// end::scopes-manage-drop-collection[]
}
private static void ListCollectionsAndScopes()
{
// tag::scopes-manage-list[]
// Get Scopes
var scopes = _Database.GetScopes();
// Get Collections of a Scope named scopeA
var scopeA = _Database.GetScope("scopeA");
var collectionsInScopeA = scopeA.GetCollections();
// end::scopes-manage-list[]
}
private static void ChangeLogging()
{
// tag::logging[]
// This sets the overall level of console logging
Database.Log.Console.Level = LogLevel.Verbose;
// This flag can enable and disable specific domains
Database.Log.Console.Domains = LogDomain.Couchbase | LogDomain.Database;
// end::logging[]
}
private static void LoadPrebuilt()
{
// tag::prebuilt-database[]
// Note: Getting the path to a database is platform-specific. For .NET Core / .NET Framework this
// can be a simple filesystem path. For UWP, you will need to get the path from your assets. For
// iOS you need to get the path from the main bundle. For Android you need to extract it from your
// assets to a temporary directory and then pass that path.
var path = Path.Combine(Environment.CurrentDirectory, "travel-sample.cblite2" + Path.DirectorySeparatorChar);
if (!Database.Exists("travel-sample", null)) {
Database.Copy(path, "travel-sample", null);
}
// end::prebuilt-database[]
}
private static void QueryDeletedDocuments()
{
var collection = _Database.GetDefaultCollection();
// tag::query-deleted-documents[]
// Query documents that have been deleted
var query = QueryBuilder
.Select(SelectResult.Expression(Meta.ID))
.From(DataSource.Collection(collection))
.Where(Meta.IsDeleted);
// end::query-deleted-documents[]
}
private static void CreateDocument()
{
var collection = _Database.GetDefaultCollection();
// tag::initializer[]
using var mutableDoc = new MutableDocument("xyz");
mutableDoc.SetString("type", "task")
.SetString("owner", "todo")
.SetDate("createdAt", DateTimeOffset.UtcNow);
collection.Save(mutableDoc);
// end::initializer[]
}
private static void UpdateDocument()
{
var collection = _Database.GetDefaultCollection();
// tag::update-document[]
using var doc = collection.GetDocument("xyz");
using var mutableDoc = doc.ToMutable();
mutableDoc.SetString("name", "apples");
collection.Save(mutableDoc);
// end::update-document[]
}
private static void UseTypedAccessors()
{
using var mutableDoc = new MutableDocument();
// tag::date-getter[]
mutableDoc.SetValue("createdAt", DateTimeOffset.UtcNow);
var date = mutableDoc.GetDate("createdAt");
// end::date-getter[]
Console.WriteLine(date);
}
private static void DoBatchOperation()
{
var database = _Database;
var collection = database.GetDefaultCollection();
// tag::batch[]
database.InBatch(() =>
{
for (var i = 0; i < 10; i++) {
using var mutableDoc = new MutableDocument();
mutableDoc.SetString("type", "user");
mutableDoc.SetString("name", $"user {i}");
mutableDoc.SetBoolean("admin", false);
collection.Save(mutableDoc);
Console.WriteLine($"Saved user document {mutableDoc.GetString("name")}");
}
});
// end::batch[]
}
private static void DatabaseChangeListener()
{
var collection = _Database.GetDefaultCollection();
// tag::document-listener[]
collection.AddDocumentChangeListener("user.john", (sender, args) =>
{
using var doc = collection.GetDocument(args.DocumentID);
Console.WriteLine($"Status :: {doc.GetString("verified_account")}");
});
// end::document-listener[]
}
private static void DocumentExpiration()
{
var collection = _Database.GetDefaultCollection();
// tag::document-expiration[]
// Purge the document one day from now
var ttl = DateTimeOffset.UtcNow.AddDays(1);
collection.SetDocumentExpiration("doc123", ttl);
// Reset expiration
collection.SetDocumentExpiration("doc1", null);
// Query documents that will be expired in less than five minutes
var fiveMinutesFromNow = DateTimeOffset.UtcNow.AddMinutes(5).ToUnixTimeMilliseconds();
using var query = QueryBuilder
.Select(SelectResult.Expression(Meta.ID))
.From(DataSource.Collection(collection))
.Where(Meta.Expiration.LessThan(Expression.Double(fiveMinutesFromNow)));
// end::document-expiration[]
}
private static void UseBlob()
{
var collection = _Database.GetDefaultCollection();
using var newTask = new MutableDocument();
// tag::blob[]
// Note: Reading the data is implementation dependent, as with prebuilt databases
var image = File.ReadAllBytes("avatar.jpg"); // <.>
var blob = new Blob("image/jpeg", image); // <.>
newTask.SetBlob("avatar", blob); // <.>
collection.Save(newTask);
// end::blob[]
}
public void CreateIndex()
{
var collection = _Database.GetDefaultCollection();
// tag::query-index[]
// tag::scopes-manage-index-collection[]
string[] indexProperties = new string[] { "type", "name" };
var config = new ValueIndexConfiguration(indexProperties);
collection.CreateIndex("TypeNameIndex", config);
// end::scopes-manage-index-collection[]
// end::query-index[]
}
public void CreateIndex_Querybuilder()
{
var collection = _Database.GetDefaultCollection();
// tag::query-index_Querybuilder[]
// For value types, this is optional but provides performance enhancements
var index = IndexBuilder.ValueIndex(
ValueIndexItem.Expression(Expression.Property("type")),
ValueIndexItem.Expression(Expression.Property("name"))); // <.>
collection.CreateIndex("TypeNameIndex", index);
// end::query-index_Querybuilder[]
}
private static void SelectMeta()
{
var collection = _Database.GetDefaultCollection();
#warning query-select-meta unused?
// tag::query-select-meta[]
// tag::query-select-props[]
using var query = QueryBuilder.Select(
SelectResult.Expression(Meta.ID),
SelectResult.Property("type"),
SelectResult.Property("name"))
.From(DataSource.Collection(collection));
foreach (var result in query.Execute()) {
Console.WriteLine($"Document ID :: {result.GetString("id")}");
Console.WriteLine($"Document Name :: {result.GetString("name")}");
}
// end::query-select-props[]
// end::query-select-meta[]
}
private static void SelectAll()
{
var collection = _Database.GetDefaultCollection();
{
// tag::query-select-all[]
using var query = QueryBuilder.Select(SelectResult.All())
.From(DataSource.Collection(collection));
// end::query-select-all[]
}
{
// tag::live-query[]
var query = QueryBuilder
.Select(SelectResult.All())
.From(DataSource.Collection(collection)); // <.>
// Adds a query change listener.
// Changes will be posted on the main queue.
var token = query.AddChangeListener((sender, args) => // <.>
{
var allResult = args.Results.AllResults();
foreach (var result in allResult) {
Console.WriteLine(result.Keys);
/* Update UI */
}
});
// end::live-query[]
// tag::stop-live-query[]
query.RemoveChangeListener(token);
query.Dispose();
// end::stop-live-query[]
}
}
private static void SelectWhere()
{
var collection = _Database.GetDefaultCollection();
// tag::query-where[]
using var query = QueryBuilder.Select(SelectResult.All())
.From(DataSource.Collection(collection))
.Where(Expression.Property("type").EqualTo(Expression.String("hotel")))
.Limit(Expression.Int(10));
foreach (var result in query.Execute()) {
var dict = result.GetDictionary(collection.Name);
Console.WriteLine($"Document Name :: {dict?.GetString("name")}");
}
// end::query-where[]
}
private static void UseCollectionContains()
{
var collection = _Database.GetDefaultCollection();
// tag::query-collection-operator-contains[]
using var query = QueryBuilder.Select(
SelectResult.Expression(Meta.ID),
SelectResult.Property("name"),
SelectResult.Property("public_likes"))
.From(DataSource.Collection(collection))
.Where(Expression.Property("type").EqualTo(Expression.String("hotel"))
.And(ArrayFunction.Contains(Expression.Property("public_likes"),
Expression.String("Armani Langworth"))));
foreach (var result in query.Execute()) {
var publicLikes = result.GetArray("public_likes");
var jsonString = JsonConvert.SerializeObject(publicLikes);
Console.WriteLine($"Public Likes :: {jsonString}");
}
// end::query-collection-operator-contains[]
}
private static void UseCollectionIn()
{
var collection = _Database.GetDefaultCollection();
// tag::query-collection-operator-in[]
var values = new IExpression[]
{ Expression.Property("first"), Expression.Property("last"), Expression.Property("username") };
using var query = QueryBuilder.Select(
SelectResult.All())
.From(DataSource.Collection(collection))
.Where(Expression.String("Armani").In(values));
foreach (var result in query.Execute()) {
var body = result.GetDictionary(0);
var jsonString = JsonConvert.SerializeObject(body);
Console.WriteLine($"In results :: {jsonString}");
}
// end::query-collection-operator-in[]
}
private static void SelectLike()
{
var collection = _Database.GetDefaultCollection();
// tag::query-like-operator[]
using var query = QueryBuilder.Select(
SelectResult.Expression(Meta.ID),
SelectResult.Property("name"))
.From(DataSource.Collection(collection))
.Where(Expression.Property("type").EqualTo(Expression.String("landmark"))
.And(Function.Lower(Expression.Property("name")).Like(Expression.String("Royal Engineers Museum"))))
.Limit(Expression.Int(10));
foreach (var result in query.Execute()) {
Console.WriteLine($"Name Property :: {result.GetString("name")}");
}
// end::query-like-operator[]
}
private static void SelectWildcardLike()
{
var collection = _Database.GetDefaultCollection();
// tag::query-like-operator-wildcard-match[]
using var query = QueryBuilder.Select(
SelectResult.Expression(Meta.ID),
SelectResult.Property("name"))
.From(DataSource.Collection(collection))
.Where(Expression.Property("type").EqualTo(Expression.String("landmark"))
.And(Function.Lower(Expression.Property("name")).Like(Expression.String("Eng%e%"))))
.Limit(Expression.Int(10));
foreach (var result in query.Execute()) {
Console.WriteLine($"Name Property :: {result.GetString("name")}");
}
// end::query-like-operator-wildcard-match[]
}
private static void SelectWildcardCharacterLike()
{
var collection = _Database.GetDefaultCollection();
// tag::query-like-operator-wildcard-character-match[]
using var query = QueryBuilder.Select(
SelectResult.Expression(Meta.ID),
SelectResult.Property("name"))
.From(DataSource.Collection(collection))
.Where(Expression.Property("type").EqualTo(Expression.String("landmark"))
.And(Expression.Property("name").Like(Expression.String("Royal Eng____rs Museum"))))
.Limit(Expression.Int(10));
foreach (var result in query.Execute()) {
Console.WriteLine($"Name Property :: {result.GetString("name")}");
}
// end::query-like-operator-wildcard-character-match[]
}
private static void SelectRegex()
{
var collection = _Database.GetDefaultCollection();
// tag::query-regex-operator[]
using var query = QueryBuilder.Select(
SelectResult.Expression(Meta.ID),
SelectResult.Property("name"))
.From(DataSource.Collection(collection))
.Where(Expression.Property("type").EqualTo(Expression.String("landmark"))
.And(Expression.Property("name").Regex(Expression.String("\\bEng.*e\\b"))))
.Limit(Expression.Int(10));
foreach (var result in query.Execute()) {
Console.WriteLine($"Name Property :: {result.GetString("name")}");
}
// end::query-regex-operator[]
}
private static void SelectJoin()
{
var collection = _Database.GetDefaultCollection();
var collection2 = _Database.GetDefaultCollection();
// tag::query-join[]
using var query = QueryBuilder.Select(
SelectResult.Expression(Expression.Property("name").From("airline")),
SelectResult.Expression(Expression.Property("callsign").From("airline")),
SelectResult.Expression(Expression.Property("destinationairport").From("route")),
SelectResult.Expression(Expression.Property("stops").From("route")),
SelectResult.Expression(Expression.Property("airline").From("route")))
.From(DataSource.Collection(collection).As("airline"))
.Join(Join.InnerJoin(DataSource.Collection(collection2).As("route"))
.On(Meta.ID.From("airline").EqualTo(Expression.Property("airlineid").From("route"))))
.Where(Expression.Property("type").From("route").EqualTo(Expression.String("route"))
.And(Expression.Property("type").From("airline").EqualTo(Expression.String("airline")))
.And(Expression.Property("sourceairport").From("route").EqualTo(Expression.String("RIX"))));
foreach (var result in query.Execute()) {
Console.WriteLine($"Name Property :: {result.GetString("name")}");
}
// end::query-join[]
}
private static void GroupBy()
{
var collection = _Database.GetDefaultCollection();
// tag::query-groupby[]
using var query = QueryBuilder.Select(
SelectResult.Expression(Function.Count(Expression.All())),
SelectResult.Property("country"),
SelectResult.Property("tz"))
.From(DataSource.Collection(collection))
.Where(Expression.Property("type").EqualTo(Expression.String("airport"))
.And(Expression.Property("geo.alt").GreaterThanOrEqualTo(Expression.Int(300))))
.GroupBy(Expression.Property("country"), Expression.Property("tz"));
foreach (var result in query.Execute()) {
Console.WriteLine(
$"There are {result.GetInt("$1")} airports in the {result.GetString("tz")} timezone located in {result.GetString("country")} and above 300 ft");
}
// end::query-groupby[]
}
private static void OrderBy()
{
var collection = _Database.GetDefaultCollection();
// tag::query-orderby[]
using var query = QueryBuilder.Select(
SelectResult.Expression(Meta.ID),
SelectResult.Property("title"))
.From(DataSource.Collection(collection))
.Where(Expression.Property("type").EqualTo(Expression.String("hotel")))
.OrderBy(Ordering.Property("title").Ascending())
.Limit(Expression.Int(10));
foreach (var result in query.Execute()) {
Console.WriteLine($"Title :: {result.GetString("title")}");
}
// end::query-orderby[]
}
private static void TestExplainStatement()
{
var collection = _Database.GetDefaultCollection();
{
// tag::query-explain-all[]
using var query =
QueryBuilder
.Select(SelectResult.All())
.From(DataSource.Collection(collection))
.Where(Expression.Property("type").EqualTo(Expression.String("hotel")))
.GroupBy(Expression.Property("country"))
.OrderBy(Ordering.Property("title").Ascending()); // <.>
Console.WriteLine(query.Explain()); // <.>
// end::query-explain-all[]
}
{
// tag::query-explain-like[]
using var query =
QueryBuilder
.Select(SelectResult.All())
.From(DataSource.Collection(collection))
.Where(Expression.Property("type").Like(Expression.String("%hotel%"))
.And(Function.Lower(Expression.Property("name")).Like(Expression.String("%royal%")))); // <.>
Console.WriteLine(query.Explain());
// end::query-explain-like[]
}
{
// tag::query-explain-nopfx[]
using var query =
QueryBuilder
.Select(SelectResult.All())
.From(DataSource.Collection(collection))
.Where(Expression.Property("type").Like(Expression.String("hotel%"))
.And(Function.Lower(Expression.Property("name")).Like(Expression.String("%royal%")))); // <.>
Console.WriteLine(query.Explain());
// end::query-explain-nopfx[]
}
{
// tag::query-explain-function[]
using var query =
QueryBuilder
.Select(SelectResult.All())
.From(DataSource.Collection(collection))
.Where(Function.Lower(Expression.Property("type")).EqualTo(Expression.String("hotel"))); // <.>
Console.WriteLine(query.Explain());
// end::query-explain-function[]
}
{
// tag::query-explain-nofunction[]
using var query =
QueryBuilder
.Select(SelectResult.All())
.From(DataSource.Collection(collection))
.Where(Expression.Property("type").EqualTo(Expression.String("hotel"))); // <.>
Console.WriteLine(query.Explain());
// end::query-explain-nofunction[]
}
}
public void CreateFullTextIndex()
{
var collection = _Database.GetDefaultCollection();
// tag::fts-index[]
string[] indexProperties = new string[] { "overview", "name" };
var config = new FullTextIndexConfiguration(indexProperties);
collection.CreateIndex("overviewFTSIndex", config);
// end::fts-index[]
}
public void FullTextSearch()
{
var collection = _Database.GetDefaultCollection();
// tag::fts-query[]
var query = collection.CreateQuery("SELECT * FROM _ WHERE MATCH(overviewFTSIndex, 'Michigan') ORDER BY RANK(overviewFTSIndex)");
foreach (var result in query.Execute()) {
Console.WriteLine($"Document id {result.GetString(0)}");