-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
DigitalTwinsClient.cs
2884 lines (2697 loc) · 158 KB
/
DigitalTwinsClient.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Core.Serialization;
using static Azure.DigitalTwins.Core.StreamHelper;
namespace Azure.DigitalTwins.Core
{
/// <summary>
/// The Digital Twins Service Client contains methods to retrieve digital twin information, like models, components, and relationships.
/// </summary>
public class DigitalTwinsClient
{
private const bool IncludeModelDefinition = true;
// Vanity representation for azure digital twin app Id "0b07f429-9f4b-4714-9392-cc5e8e80c8b0" in the public cloud
// and shared by other clouds.
private const string AdtDefaultAppId = "https://digitaltwins.azure.net";
private const string DefaultPermissionConsent = "/.default";
private static readonly string[] s_adtDefaultScopes = new[] { AdtDefaultAppId + DefaultPermissionConsent };
private readonly HttpPipeline _httpPipeline;
private readonly ClientDiagnostics _clientDiagnostics;
private readonly ObjectSerializer _objectSerializer;
private readonly DigitalTwinsRestClient _dtRestClient;
private readonly DigitalTwinModelsRestClient _dtModelsRestClient;
private readonly EventRoutesRestClient _eventRoutesRestClient;
private readonly QueryRestClient _queryClient;
/// <summary>
/// Creates a new instance of the <see cref="DigitalTwinsClient"/> class.
/// </summary>
/// <param name='endpoint'>The Azure digital twins service instance URI to connect to.</param>
/// <param name="credential">The <see cref="TokenCredential"/> implementation which will be used to request for the authentication token.</param>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </remarks>
/// <example>
/// <code snippet="Snippet:DigitalTwinsSampleCreateServiceClientWithClientSecret" language="csharp">
/// // DefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.
/// // It attempts to use multiple credential types in an order until it finds a working credential.
/// TokenCredential tokenCredential = new DefaultAzureCredential();
///
/// var client = new DigitalTwinsClient(
/// new Uri(adtEndpoint),
/// tokenCredential);
/// </code>
/// </example>
public DigitalTwinsClient(Uri endpoint, TokenCredential credential)
: this(endpoint, credential, new DigitalTwinsClientOptions())
{
}
/// <summary>
/// Creates a new instance of the <see cref="DigitalTwinsClient"/> class, with options.
/// </summary>
/// <param name='endpoint'>The Azure digital twins service instance URI to connect to.</param>
/// <param name="credential">The <see cref="TokenCredential"/> implementation which will be used to request for the authentication token.</param>
/// <param name="options">Options that allow configuration of requests sent to the digital twins service.</param>
/// <remarks>
/// <para>
/// The options parameter provides an opportunity to override default behavior, including specifying API version,
/// overriding <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/Pipeline.md">transport</see>,
/// enabling <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/Diagnostics.md">diagnostics</see>,
/// and controlling <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/Configuration.md">retry strategy</see>.
/// </para>
/// <para>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </para>
/// </remarks>
public DigitalTwinsClient(Uri endpoint, TokenCredential credential, DigitalTwinsClientOptions options)
{
Argument.AssertNotNull(options, nameof(options));
_clientDiagnostics = new ClientDiagnostics(options);
_objectSerializer = options.Serializer ?? new JsonObjectSerializer();
options.AddPolicy(new BearerTokenAuthenticationPolicy(credential, GetAuthorizationScopes()), HttpPipelinePosition.PerCall);
_httpPipeline = HttpPipelineBuilder.Build(options);
string versionString = options.GetVersionString();
_dtRestClient = new DigitalTwinsRestClient(_clientDiagnostics, _httpPipeline, endpoint, versionString);
_dtModelsRestClient = new DigitalTwinModelsRestClient(_clientDiagnostics, _httpPipeline, endpoint, versionString);
_eventRoutesRestClient = new EventRoutesRestClient(_clientDiagnostics, _httpPipeline, endpoint, versionString);
_queryClient = new QueryRestClient(_clientDiagnostics, _httpPipeline, endpoint, versionString);
}
/// <summary>
/// Creates a new instance of the <see cref="DigitalTwinsClient"/> class, provided for unit testing purposes only.
/// </summary>
protected DigitalTwinsClient()
{
// This constructor only exists for mocking purposes in unit tests. It should not be used otherwise.
}
/// <summary>
/// Gets a digital twin asynchronously.
/// </summary>
/// <remarks>
/// <para>
/// A strongly typed object type such as <see cref="BasicDigitalTwin"/> can be used as a generic type for <typeparamref name="T"/>
/// to indicate what type is used to deserialize the response value.
/// It may also be deserialized into custom digital twin types that extend the <see cref="BasicDigitalTwin"/> with additional
/// strongly typed properties provided that you know the definition of the retrieved digital twin prior to deserialization.
/// </para>
/// <para>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </para>
/// </remarks>
/// <param name="digitalTwinId">The Id of the digital twin.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The deserialized application/json digital twin and the HTTP response <see cref="Response{T}"/>.</returns>
/// <typeparam name="T">The type to deserialize the digital twin to.</typeparam>
/// <exception cref="RequestFailedException">
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> is <c>null</c>.
/// </exception>
/// <example>
/// This sample demonstrates getting and deserializing a digital twin into a custom data type.
///
/// <code snippet="Snippet:DigitalTwinsSampleGetCustomDigitalTwin" language="csharp">
/// Response<CustomDigitalTwin> getCustomDtResponse = await client.GetDigitalTwinAsync<CustomDigitalTwin>(customDtId);
/// CustomDigitalTwin customDt = getCustomDtResponse.Value;
/// Console.WriteLine($"Retrieved and deserialized digital twin {customDt.Id}:\n\t" +
/// $"ETag: {customDt.ETag}\n\t" +
/// $"ModelId: {customDt.Metadata.ModelId}\n\t" +
/// $"Prop1: [{customDt.Prop1}] last updated on {customDt.Metadata.Prop1.LastUpdatedOn}\n\t" +
/// $"Prop2: [{customDt.Prop2}] last updated on {customDt.Metadata.Prop2.LastUpdatedOn}\n\t" +
/// $"ComponentProp1: [{customDt.Component1.ComponentProp1}] last updated {customDt.Component1.Metadata.ComponentProp1.LastUpdatedOn}\n\t" +
/// $"ComponentProp2: [{customDt.Component1.ComponentProp2}] last updated {customDt.Component1.Metadata.ComponentProp2.LastUpdatedOn}");
/// </code>
/// </example>
public virtual async Task<Response<T>> GetDigitalTwinAsync<T>(string digitalTwinId, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(GetDigitalTwin)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.Start();
try
{
// Get the digital twin as a stream object
Response<Stream> digitalTwinStream = await _dtRestClient
.GetByIdAsync(digitalTwinId, null, cancellationToken)
.ConfigureAwait(false);
// Deserialize the stream into the specified type
T deserializedDigitalTwin = (T)await _objectSerializer
.DeserializeAsync(digitalTwinStream, typeof(T), cancellationToken)
.ConfigureAwait(false);
return Response.FromValue<T>(deserializedDigitalTwin, digitalTwinStream.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets a digital twin synchronously.
/// </summary>
/// <remarks>
/// <para>
/// A strongly typed object type such as <see cref="BasicDigitalTwin"/> can be used as a generic type for <typeparamref name="T"/>
/// to indicate what type is used to deserialize the response value.
/// It may also be deserialized into custom digital twin types that extend the <see cref="BasicDigitalTwin"/> with additional
/// strongly typed properties provided that you know the definition of the retrieved digital twin prior to deserialization.
/// </para>
/// <para>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </para>
/// </remarks>
/// <param name="digitalTwinId">The Id of the digital twin.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The deserialized application/json digital twin and the HTTP response <see cref="Response{T}"/>.</returns>
/// <typeparam name="T">The type to deserialize the digital twin to.</typeparam>
/// <exception cref="RequestFailedException">
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> is <c>null</c>.
/// </exception>
public virtual Response<T> GetDigitalTwin<T>(string digitalTwinId, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(GetDigitalTwin)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.Start();
try
{
// Get the digital twin as a stream object
Response<Stream> digitalTwinStream = _dtRestClient.GetById(digitalTwinId, null, cancellationToken);
// Deserialize the stream into the specified type
T deserializedDigitalTwin = (T)_objectSerializer.Deserialize(digitalTwinStream, typeof(T), cancellationToken);
return Response.FromValue<T>(deserializedDigitalTwin, digitalTwinStream.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Creates a digital twin asynchronously. If the provided digital twin Id is already in use, then this will attempt to replace the existing digital twin
/// with the provided digital twin..
/// </summary>
/// <param name="digitalTwinId">The Id of the digital twin.</param>
/// <param name="digitalTwin">The application/json digital twin to create.</param>
/// <param name="ifNoneMatch">
/// If-None-Match header that makes the request method conditional on a
/// recipient cache or origin server either not having any current
/// representation of the target resource. For more information about
/// this property, see <see href="https://tools.ietf.org/html/rfc7232#section-3.2">RFC 7232</see>.
/// Acceptable values are null or <c>"*"</c>. If ifNonMatch option is null
/// the service will replace the existing entity with the new entity.
/// If ifNoneMatch option is <c>"*"</c> (or <see cref="ETag.All"/>) the
/// service will reject the request if the entity already exists.
/// An optional ETag to only make the request if the value does not
/// match on the service.
/// </param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The created application/json digital twin and the HTTP response <see cref="Response{T}"/>.</returns>
/// <typeparam name="T">The type to deserialize the digital twin to.</typeparam>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="RequestFailedException">
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> or <paramref name="digitalTwin"/> is <c>null</c>.
/// </exception>
/// <example>
/// <code snippet="Snippet:DigitalTwinsSampleCreateCustomTwin" language="csharp">
/// var customTwin = new CustomDigitalTwin
/// {
/// Id = customDtId,
/// Metadata = { ModelId = modelId },
/// Prop1 = "Prop1 val",
/// Prop2 = 987,
/// Component1 = new MyCustomComponent
/// {
/// ComponentProp1 = "Component prop1 val",
/// ComponentProp2 = 123,
/// },
/// };
/// Response<CustomDigitalTwin> createCustomDigitalTwinResponse = await client.CreateOrReplaceDigitalTwinAsync(customDtId, customTwin);
/// Console.WriteLine($"Created digital twin '{createCustomDigitalTwinResponse.Value.Id}'.");
/// </code>
/// </example>
public virtual async Task<Response<T>> CreateOrReplaceDigitalTwinAsync<T>(
string digitalTwinId,
T digitalTwin,
ETag? ifNoneMatch = null,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(CreateOrReplaceDigitalTwin)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.Start();
try
{
// Serialize the digital twin object and write it to a stream
using MemoryStream memoryStream = await WriteToStreamAsync<T>(digitalTwin, _objectSerializer, cancellationToken)
.ConfigureAwait(false);
// Get the response of the digital twin as a stream object
CreateOrReplaceDigitalTwinOptions options = ifNoneMatch == null
? null
: new CreateOrReplaceDigitalTwinOptions { IfNoneMatch = ifNoneMatch.Value.ToString() };
Response<Stream> digitalTwinStream = await _dtRestClient
.AddAsync(digitalTwinId, memoryStream, options, cancellationToken)
.ConfigureAwait(false);
// Deserialize the stream into the specified type
T deserializedDigitalTwin = (T)await _objectSerializer
.DeserializeAsync(digitalTwinStream, typeof(T), cancellationToken)
.ConfigureAwait(false);
return Response.FromValue<T>(deserializedDigitalTwin, digitalTwinStream.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Creates a digital twin synchronously. If the provided digital twin Id is already in use, then this will attempt to replace the existing digital twin
/// with the provided digital twin.
/// </summary>
/// <param name="digitalTwinId">The Id of the digital twin.</param>
/// <param name="digitalTwin">The application/json digital twin to create.</param>
/// <param name="ifNoneMatch">
/// If-None-Match header that makes the request method conditional on a
/// recipient cache or origin server either not having any current
/// representation of the target resource. For more information about
/// this property, see <see href="https://tools.ietf.org/html/rfc7232#section-3.2">RFC 7232</see>.
/// Acceptable values are null or <c>"*"</c>. If ifNonMatch option is null
/// the service will replace the existing entity with the new entity.
/// If ifNoneMatch option is <c>"*"</c> (or <see cref="ETag.All"/>) the
/// service will reject the request if the entity already exists.
/// An optional ETag to only make the request if the value does not
/// match on the service.
/// </param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The created application/json digital twin and the HTTP response <see cref="Response{T}"/>.</returns>
/// <typeparam name="T">The type to deserialize the digital twin to.</typeparam>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="RequestFailedException">
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> or <paramref name="digitalTwin"/> is <c>null</c>.
/// </exception>
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
public virtual Response<T> CreateOrReplaceDigitalTwin<T>(
string digitalTwinId,
T digitalTwin,
ETag? ifNoneMatch = null,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(CreateOrReplaceDigitalTwin)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.Start();
try
{
// Serialize the digital twin object and write it to a stream
using MemoryStream memoryStream = WriteToStream<T>(digitalTwin, _objectSerializer, cancellationToken);
// Get the response of the digital twin as a stream object
CreateOrReplaceDigitalTwinOptions options = ifNoneMatch == null
? null
: new CreateOrReplaceDigitalTwinOptions { IfNoneMatch = ifNoneMatch.Value.ToString() };
Response<Stream> digitalTwinStream = _dtRestClient.Add(digitalTwinId, memoryStream, options, cancellationToken);
// Deserialize the stream into the specified type
T deserializedDigitalTwin = (T)_objectSerializer.Deserialize(digitalTwinStream, typeof(T), cancellationToken);
return Response.FromValue<T>(deserializedDigitalTwin, digitalTwinStream.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Deletes a digital twin asynchronously.
/// </summary>
/// <param name="digitalTwinId">The Id of the digital twin to delete.</param>
/// <param name="ifMatch">Optional. Only perform the operation if the entity's ETag matches this optional ETag or * (<see cref="ETag.All"/>) is provided.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The HTTP response <see cref="Response"/>.</returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="RequestFailedException">
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// To delete a digital twin, any relationships referencing it must be deleted first.
/// </remarks>
/// <example>
/// <code snippet="Snippet:DigitalTwinsSampleDeleteTwin" language="csharp">
/// await client.DeleteDigitalTwinAsync(digitalTwinId);
/// Console.WriteLine($"Deleted digital twin '{digitalTwinId}'.");
/// </code>
/// </example>
public virtual async Task<Response> DeleteDigitalTwinAsync(string digitalTwinId, ETag? ifMatch = null, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(DeleteDigitalTwin)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.Start();
try
{
DeleteDigitalTwinOptions options = ifMatch == null
? null
: new DeleteDigitalTwinOptions { IfMatch = ifMatch.Value.ToString() };
return await _dtRestClient.DeleteAsync(digitalTwinId, options, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Deletes a digital twin synchronously.
/// </summary>
/// <param name="digitalTwinId">The Id of the digital twin to delete.</param>
/// <param name="ifMatch">Optional. Only perform the operation if the entity's ETag matches this optional ETag or * (<see cref="ETag.All"/>) is provided.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The HTTP response <see cref="Response"/>.</returns>
/// <remarks>
/// <para>
/// To delete a digital twin, any relationships referencing it must be deleted first.
/// </para>
/// <para>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </para>
/// </remarks>
/// <exception cref="RequestFailedException">
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> is <c>null</c>.
/// </exception>
public virtual Response DeleteDigitalTwin(string digitalTwinId, ETag? ifMatch = null, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(DeleteDigitalTwin)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.Start();
try
{
DeleteDigitalTwinOptions options = ifMatch == null
? null
: new DeleteDigitalTwinOptions { IfMatch = ifMatch.Value.ToString() };
return _dtRestClient.Delete(digitalTwinId, options, cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Updates a digital twin asynchronously.
/// </summary>
/// <param name="digitalTwinId">The Id of the digital twin to update.</param>
/// <param name="jsonPatchDocument">The application/json-patch+json operations to be performed on the specified digital twin.</param>
/// <param name="ifMatch">Optional. Only perform the operation if the entity's ETag matches this optional ETag or * (<see cref="ETag.All"/>) is provided.</param>
/// <param name="cancellationToken">The cancellationToken.</param>
/// <returns>The HTTP response <see cref="Response{T}"/>. This response object includes an HTTP header that gives you the updated ETag for this resource.</returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="RequestFailedException">
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> or <paramref name="jsonPatchDocument"/> is <c>null</c>.
/// </exception>
/// <seealso cref="UpdateDigitalTwin(string, JsonPatchDocument, ETag?, CancellationToken)"/>
public virtual async Task<Response> UpdateDigitalTwinAsync(string digitalTwinId, JsonPatchDocument jsonPatchDocument, ETag? ifMatch = null, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(UpdateDigitalTwin)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.Start();
try
{
Argument.AssertNotNull(jsonPatchDocument, nameof(jsonPatchDocument));
UpdateDigitalTwinOptions options = ifMatch == null
? null
: new UpdateDigitalTwinOptions { IfMatch = ifMatch.Value.ToString() };
return await _dtRestClient
.UpdateAsync(digitalTwinId, jsonPatchDocument.ToString(), options, cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Updates a digital twin synchronously.
/// </summary>
/// <param name="digitalTwinId">The Id of the digital twin to update.</param>
/// <param name="jsonPatchDocument">The application/json-patch+json operations to be performed on the specified digital twin.</param>
/// <param name="ifMatch">Optional. Only perform the operation if the entity's ETag matches this optional ETag or * (<see cref="ETag.All"/>) is provided.</param>
/// <param name="cancellationToken">The cancellationToken.</param>
/// <returns>The HTTP response <see cref="Response{T}"/>. This response object includes an HTTP header that gives you the updated ETag for this resource.</returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="RequestFailedException">
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> or <paramref name="jsonPatchDocument"/> is <c>null</c>.
/// </exception>
/// <seealso cref="UpdateDigitalTwinAsync(string, JsonPatchDocument, ETag?, CancellationToken)"/>
public virtual Response UpdateDigitalTwin(string digitalTwinId, JsonPatchDocument jsonPatchDocument, ETag? ifMatch = null, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(UpdateDigitalTwin)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.Start();
try
{
Argument.AssertNotNull(jsonPatchDocument, nameof(jsonPatchDocument));
UpdateDigitalTwinOptions options = ifMatch == null
? null
: new UpdateDigitalTwinOptions { IfMatch = ifMatch.Value.ToString() };
return _dtRestClient.Update(digitalTwinId, jsonPatchDocument.ToString(), options, cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets a component on a digital twin asynchronously.
/// </summary>
/// <param name="digitalTwinId">The Id of the digital twin.</param>
/// <param name="componentName">The component being retrieved.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The deserialized object representation of the component corresponding to the provided componentName and the HTTP response <see cref="Response{T}"/>.</returns>
/// <typeparam name="T">The type to deserialize the component to.</typeparam>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="RequestFailedException">
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> or <paramref name="componentName"/> is <c>null</c>.
/// </exception>
/// <example>
/// <code snippet="Snippet:DigitalTwinsSampleGetComponent" language="csharp">
/// await client.GetComponentAsync<MyCustomComponent>(basicDtId, SamplesConstants.ComponentName);
/// Console.WriteLine($"Retrieved component for digital twin '{basicDtId}'.");
/// </code>
/// </example>
/// <seealso cref="GetComponent(string, string, CancellationToken)"/>
public virtual async Task<Response<T>> GetComponentAsync<T>(string digitalTwinId, string componentName, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(GetComponent)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.Start();
try
{
// Get the component as a stream object
Response<Stream> componentStream = await _dtRestClient
.GetComponentAsync(digitalTwinId, componentName, null, cancellationToken)
.ConfigureAwait(false);
// Deserialize the stream into the specified type
T deserializedComponent = (T)await _objectSerializer
.DeserializeAsync(componentStream, typeof(T), cancellationToken)
.ConfigureAwait(false);
return Response.FromValue<T>(deserializedComponent, componentStream.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets a component on a digital twin synchronously.
/// </summary>
/// <param name="digitalTwinId">The Id of the digital twin.</param>
/// <param name="componentName">The component being retrieved.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The deserialized object representation of the component corresponding to the provided componentName and the HTTP response <see cref="Response{T}"/>.</returns>
/// <typeparam name="T">The type to deserialize the component to.</typeparam>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="RequestFailedException">
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> or <paramref name="componentName"/> is <c>null</c>.
/// </exception>
/// <seealso cref="GetComponentAsync(string, string, CancellationToken)"/>
public virtual Response<T> GetComponent<T>(string digitalTwinId, string componentName, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(GetComponent)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.AddAttribute(nameof(componentName), componentName);
scope.Start();
try
{
// Get the component as a stream object
Response<Stream> componentStream = _dtRestClient.GetComponent(digitalTwinId, componentName, null, cancellationToken);
// Deserialize the stream into the specified type
T deserializedComponent = (T)_objectSerializer.Deserialize(componentStream, typeof(T), cancellationToken);
return Response.FromValue<T>(deserializedComponent, componentStream.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Updates properties of a component on a digital twin asynchronously.
/// </summary>
/// <param name="digitalTwinId">The Id of the digital twin.</param>
/// <param name="componentName">The component being modified.</param>
/// <param name="jsonPatchDocument">The application/json-patch+json operations to be performed on the specified digital twin's component.</param>
/// <param name="ifMatch">Optional. Only perform the operation if the entity's ETag matches this optional ETag or * (<see cref="ETag.All"/>) is provided.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The HTTP response <see cref="Response{T}"/>. This response object includes an HTTP header that gives you the updated ETag for this resource.</returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="RequestFailedException">
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
/// <example>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> or <paramref name="componentName"/> is <c>null</c>.
/// </exception>
/// <code snippet="Snippet:DigitalTwinsSampleUpdateComponent" language="csharp">
/// // Update Component1 by replacing the property ComponentProp1 value,
/// // using an optional utility to build the payload.
/// var componentJsonPatchDocument = new JsonPatchDocument();
/// componentJsonPatchDocument.AppendReplace("/ComponentProp1", "Some new value");
/// await client.UpdateComponentAsync(basicDtId, "Component1", componentJsonPatchDocument);
/// Console.WriteLine($"Updated component for digital twin '{basicDtId}'.");
/// </code>
/// </example>
/// <seealso cref="UpdateComponent(string, string, JsonPatchDocument, ETag?, CancellationToken)"/>
public virtual async Task<Response> UpdateComponentAsync(
string digitalTwinId,
string componentName,
JsonPatchDocument jsonPatchDocument,
ETag? ifMatch = null,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(UpdateComponent)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.AddAttribute(nameof(componentName), componentName);
scope.Start();
try
{
Argument.AssertNotNull(jsonPatchDocument, nameof(jsonPatchDocument));
UpdateComponentOptions options = ifMatch == null
? null
: new UpdateComponentOptions { IfMatch = ifMatch.Value.ToString() };
return await _dtRestClient
.UpdateComponentAsync(
digitalTwinId,
componentName,
jsonPatchDocument.ToString(),
options,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Updates properties of a component on a digital twin synchronously.
/// </summary>
/// <param name="digitalTwinId">The Id of the digital twin.</param>
/// <param name="componentName">The component being modified.</param>
/// <param name="jsonPatchDocument">The application/json-patch+json operations to be performed on the specified digital twin's component.</param>
/// <param name="ifMatch">Optional. Only perform the operation if the entity's ETag matches this optional ETag or * (<see cref="ETag.All"/>) is provided.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The HTTP response <see cref="Response{T}"/>. This response object includes an HTTP header that gives you the updated ETag for this resource.</returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="RequestFailedException">
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> or <paramref name="componentName"/> is <c>null</c>.
/// </exception>
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
/// <seealso cref="UpdateComponentAsync(string, string, JsonPatchDocument, ETag?, CancellationToken)"/>
public virtual Response UpdateComponent(
string digitalTwinId,
string componentName,
JsonPatchDocument jsonPatchDocument,
ETag? ifMatch = null,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(UpdateComponent)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.AddAttribute(nameof(componentName), componentName);
scope.Start();
try
{
Argument.AssertNotNull(jsonPatchDocument, nameof(jsonPatchDocument));
UpdateComponentOptions options = ifMatch == null
? null
: new UpdateComponentOptions { IfMatch = ifMatch.Value.ToString() };
return _dtRestClient.UpdateComponent(digitalTwinId, componentName, jsonPatchDocument.ToString(), options, cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets all the relationships on a digital twin by iterating through a collection asynchronously.
/// </summary>
/// <param name="digitalTwinId">The Id of the source digital twin.</param>
/// <param name="relationshipName">The name of a relationship to filter to. If null, all relationships for the digital twin will be returned.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The pageable list <see cref="AsyncPageable{T}"/> of application/json relationships belonging to the specified digital twin and the HTTP response.</returns>
/// <typeparam name="T">The type to deserialize the relationship to.</typeparam>
/// <remarks>
/// <para>
/// Relationships that are returned as part of the pageable list can always be deserialized into an instance of <see cref="BasicRelationship"/>.
/// You may also deserialize the relationship into custom type that extend the <see cref="BasicRelationship"/>.
/// </para>
/// <para>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </para>
/// </remarks>
/// <exception cref="RequestFailedException">
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> is <c>null</c>.
/// </exception>
/// <example>
/// This sample demonstrates iterating over outgoing relationships and deserializing relationship strings into BasicRelationship objects.
/// <code snippet="Snippet:DigitalTwinsSampleGetAllRelationships" language="csharp">
/// AsyncPageable<BasicRelationship> relationships = client.GetRelationshipsAsync<BasicRelationship>("buildingTwinId");
/// await foreach (BasicRelationship relationship in relationships)
/// {
/// Console.WriteLine($"Retrieved relationship '{relationship.Id}' with source {relationship.SourceId}' and " +
/// $"target {relationship.TargetId}.\n\t" +
/// $"Prop1: {relationship.Properties["Prop1"]}\n\t" +
/// $"Prop2: {relationship.Properties["Prop2"]}");
/// }
/// </code>
/// </example>
/// <seealso cref="GetRelationships(string, string, CancellationToken)"/>
public virtual AsyncPageable<T> GetRelationshipsAsync<T>(
string digitalTwinId,
string relationshipName = null,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(GetRelationships)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.AddAttribute(nameof(relationshipName), relationshipName);
scope.Start();
try
{
if (digitalTwinId == null)
{
throw new ArgumentNullException(nameof(digitalTwinId));
}
async Task<Page<T>> FirstPageFunc(int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(GetRelationships)}");
scope.Start();
try
{
Response<RelationshipCollection<T>> response = await _dtRestClient
.ListRelationshipsAsync<T>(digitalTwinId, relationshipName, null, _objectSerializer, cancellationToken)
.ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
async Task<Page<T>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(GetRelationships)}");
scope.Start();
try
{
Response<RelationshipCollection<T>> response = await _dtRestClient
.ListRelationshipsNextPageAsync<T>(nextLink, digitalTwinId, relationshipName, null, _objectSerializer, cancellationToken)
.ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets all the relationships on a digital twin by iterating through a collection synchronously.
/// </summary>
/// <param name="digitalTwinId">The Id of the source digital twin.</param>
/// <param name="relationshipName">The name of a relationship to filter to. If null, all relationships for the digital twin will be returned.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The pageable list <see cref="Pageable{T}"/> of application/json relationships belonging to the specified digital twin and the HTTP response.</returns>
/// <typeparam name="T">The type to deserialize the relationship to.</typeparam>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="RequestFailedException">
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> is <c>null</c>.
/// </exception>
/// <seealso cref="GetRelationshipsAsync(string, string, CancellationToken)"/>
public virtual Pageable<T> GetRelationships<T>(string digitalTwinId, string relationshipName = null, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(GetRelationships)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.AddAttribute(nameof(relationshipName), relationshipName);
scope.Start();
try
{
if (digitalTwinId == null)
{
throw new ArgumentNullException(nameof(digitalTwinId));
}
Page<T> FirstPageFunc(int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(GetRelationships)}");
scope.Start();
try
{
Response<RelationshipCollection<T>> response = _dtRestClient
.ListRelationships<T>(digitalTwinId, relationshipName, null, _objectSerializer, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
Page<T> NextPageFunc(string nextLink, int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(GetRelationships)}");
scope.Start();
try
{
Response<RelationshipCollection<T>> response = _dtRestClient
.ListRelationshipsNextPage<T>(nextLink, digitalTwinId, relationshipName, null, _objectSerializer, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets all the relationships referencing a digital twin as a target by iterating through a collection asynchronously.
/// </summary>
/// <param name="digitalTwinId">The Id of the target digital twin.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The pageable list <see cref="AsyncPageable{T}"/> of application/json relationships directed towards the specified digital twin and the HTTP response.</returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="RequestFailedException">
/// The exception that captures the errors from the service. Check the <see cref="RequestFailedException.ErrorCode"/> and <see cref="RequestFailedException.Status"/> properties for more details.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="digitalTwinId"/> is <c>null</c>.
/// </exception>
/// <example>
/// <code snippet="Snippet:DigitalTwinsSampleGetIncomingRelationships" language="csharp">
/// AsyncPageable<IncomingRelationship> incomingRelationships = client.GetIncomingRelationshipsAsync("buildingTwinId");
///
/// await foreach (IncomingRelationship incomingRelationship in incomingRelationships)
/// {
/// Console.WriteLine($"Found an incoming relationship '{incomingRelationship.RelationshipId}' from '{incomingRelationship.SourceId}'.");
/// }
/// </code>
/// </example>
/// <seealso cref="GetIncomingRelationships(string, CancellationToken)"/>
public virtual AsyncPageable<IncomingRelationship> GetIncomingRelationshipsAsync(string digitalTwinId, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(GetIncomingRelationships)}");
scope.AddAttribute(nameof(digitalTwinId), digitalTwinId);
scope.Start();
try
{
async Task<Page<IncomingRelationship>> FirstPageFunc(int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(GetIncomingRelationships)}");
scope.Start();
try
{
Response<IncomingRelationshipCollection> response = await _dtRestClient
.ListIncomingRelationshipsAsync(digitalTwinId, null, cancellationToken)
.ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
async Task<Page<IncomingRelationship>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(DigitalTwinsClient)}.{nameof(GetIncomingRelationships)}");
scope.Start();
try
{
Response<IncomingRelationshipCollection> response = await _dtRestClient
.ListIncomingRelationshipsNextPageAsync(nextLink, digitalTwinId, null, cancellationToken)
.ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets all the relationships referencing a digital twin as a target by iterating through a collection synchronously.
/// </summary>
/// <param name="digitalTwinId">The Id of the target digital twin.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The pageable list <see cref="Pageable{T}"/> of application/json relationships directed towards the specified digital twin and the HTTP response.</returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
/// </remarks>