Ejemplo n.º 1
0
        async public void GetModels(DigitalTwinsClient client)
        {
            // ------------------ GET MODELS ---------------------
            // <GetModels>
            // 'client' is a valid DigitalTwinsClient object

            // Get a single model, metadata and data
            Response <DigitalTwinsModelData> md1 = await client.GetModelAsync("<model-Id>");

            DigitalTwinsModelData model1 = md1.Value;

            // Get a list of the metadata of all available models; print their IDs
            AsyncPageable <DigitalTwinsModelData> md2 = client.GetModelsAsync();

            await foreach (DigitalTwinsModelData md in md2)
            {
                Console.WriteLine($"Type ID: {md.Id}");
            }

            // Get models and metadata for a model ID, including all dependencies (models that it inherits from, components it references)
            AsyncPageable <DigitalTwinsModelData> md3 = client.GetModelsAsync(new GetModelsOptions {
                IncludeModelDefinition = true
            });
            // </GetModels>
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets all the models within the ADT service instance.
        /// </summary>
        public async Task GetAllModelsAsync()
        {
            PrintHeader("LISTING MODELS");
            try
            {
                // Get all the twin types

                #region Snippet:DigitalTwinsSampleGetModels

                AsyncPageable <DigitalTwinsModelData> allModels = client.GetModelsAsync();
                await foreach (DigitalTwinsModelData model in allModels)
                {
                    Console.WriteLine($"Retrieved model '{model.Id}', " +
                                      $"display name '{model.DisplayName["en"]}', " +
                                      $"uploaded on '{model.UploadedOn}', " +
                                      $"and decommissioned '{model.Decommissioned}'");
                }

                #endregion Snippet:DigitalTwinsSampleGetModels
            }
            catch (RequestFailedException ex)
            {
                FatalError($"Failed to get all the models due to:\n{ex}");
            }
        }
Ejemplo n.º 3
0
        static async Task Main(string[] args)
        {
            DigitalTwinsClient client;

            try
            {
                var credential = new InteractiveBrowserCredential(tenantId, clientId);

                // Open a browser window and allow user to select which account to authenticate with
                // If you omit this, the browser will only be launched to authenticate the user once,
                // then will silently acquire access tokens through the users refresh token as long as it's valid.
                // So if you are switching between AAD accounts, keep this uncommented.
                var auth_result = credential.Authenticate();
                Console.WriteLine($"Sucessfully authenticated as: {auth_result.Username}");

                client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential);

                AsyncPageable <ModelData> modelList = client.GetModelsAsync(null, true);

                await foreach (ModelData md in modelList)
                {
                    Console.WriteLine($"Id: {md.Id}");
                }

                Console.WriteLine("Done");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Authentication or client creation error: {e.Message}");
                Environment.Exit(0);
            }
        }
Ejemplo n.º 4
0
        static async Task Main(string[] args)
        {
            DigitalTwinsClient client;

            try
            {
                var credential = new ClientSecretCredential(tenantId, clientId, secret);

                client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential);

                AsyncPageable <ModelData> modelList = client.GetModelsAsync(null, true);

                await foreach (ModelData md in modelList)
                {
                    Console.WriteLine($"Id: {md.Id}");
                }

                Console.WriteLine("Done");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Authentication or client creation error: {e.Message}");
                Environment.Exit(0);
            }
        }
Ejemplo n.º 5
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            //string clientId = "5c694aad-e4ed-43a3-95cc-3d45af6685e5";
            //string tenantId = "72f988bf-86f1-41af-91ab-2d7cd011db47";
            string adtInstanceUrl = "https://digital-twin-demo-jc.api.wcus.digitaltwins.azure.net";
            var    credOpts       = new DefaultAzureCredentialOptions()
            {
                ExcludeSharedTokenCacheCredential = true,
                ExcludeVisualStudioCodeCredential = true
            };
            var cred = new DefaultAzureCredential(credOpts);
            DigitalTwinsClient client = new DigitalTwinsClient(new Uri(adtInstanceUrl), cred);

            //var credentials = new InteractiveBrowserCredential(tenantId, clientId);
            // DigitalTwinsClient client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credentials);
            Console.WriteLine($"Service client created – ready to go");
            Console.WriteLine();
            Console.WriteLine($"Upload a model");

            var    typeList = new List <string>();
            string dtdl     = File.ReadAllText("SampleModel.json");

            typeList.Add(dtdl);
            // Upload the model to the service
            await client.CreateModelsAsync(typeList);

            // Read a list of models back from the service
            AsyncPageable <ModelData> modelDataList = client.GetModelsAsync();

            await foreach (ModelData md in modelDataList)
            {
                Console.WriteLine($"Type name: {md.DisplayName}: {md.Id}");
            }
        }
        public async Task ParseDemoAsync(DigitalTwinsClient client)
        {
            try
            {
                AsyncPageable <DigitalTwinsModelData> mdata = client.GetModelsAsync(new GetModelsOptions {
                    IncludeModelDefinition = true
                });
                var models = new List <string>();
                await foreach (DigitalTwinsModelData md in mdata)
                {
                    models.Add(md.DtdlModel);
                }
                var parser = new ModelParser();
                IReadOnlyDictionary <Dtmi, DTEntityInfo> dtdlOM = await parser.ParseAsync(models);

                var interfaces = new List <DTInterfaceInfo>();
                IEnumerable <DTInterfaceInfo> ifenum =
                    from entity in dtdlOM.Values
                    where entity.EntityKind == DTEntityKind.Interface
                    select entity as DTInterfaceInfo;
                interfaces.AddRange(ifenum);
                foreach (DTInterfaceInfo dtif in interfaces)
                {
                    PrintInterfaceContent(dtif, dtdlOM);
                }
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine($"Failed due to {ex}");
                throw;
            }
        }
Ejemplo n.º 7
0
        public async Task Models_Lifecycle()
        {
            DigitalTwinsClient client = GetClient();

            string buildingModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.BuildingModelId).ConfigureAwait(false);

            string floorModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.FloorModelId).ConfigureAwait(false);

            string hvacModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.HvacModelId).ConfigureAwait(false);

            string wardModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.WardModelId).ConfigureAwait(false);

            try
            {
                string modelBuilding = TestAssetsHelper.GetBuildingModelPayload(buildingModelId, hvacModelId, floorModelId);
                string modelHvac     = TestAssetsHelper.GetHvacModelPayload(hvacModelId, floorModelId);
                string modelWard     = TestAssetsHelper.GetWardModelPayload(wardModelId);

                // CREATE models
                var modelsList = new List <string> {
                    modelBuilding, modelHvac, modelWard
                };
                await CreateAndListModelsAsync(client, modelsList).ConfigureAwait(false);

                // GET one created model
                Response <DigitalTwinsModelData> buildingModel = await client.GetModelAsync(buildingModelId).ConfigureAwait(false);

                Console.WriteLine($"Got {buildingModelId} as {buildingModel.Value.DtdlModel}");

                // LIST all models
                AsyncPageable <DigitalTwinsModelData> models = client.GetModelsAsync();
                await foreach (DigitalTwinsModelData model in models)
                {
                    Console.WriteLine($"{model.Id}");
                }

                // DECOMMISSION a model
                await client.DecommissionModelAsync(buildingModelId).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Assert.Fail($"Failure in executing a step in the test case: {ex.Message}.");
            }
            finally
            {
                // Test DELETE all models.
                try
                {
                    await client.DeleteModelAsync(buildingModelId).ConfigureAwait(false);

                    await client.DeleteModelAsync(hvacModelId).ConfigureAwait(false);

                    await client.DeleteModelAsync(wardModelId).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Assert.Fail($"Test clean up failed: {ex.Message}");
                }
            }
        }
Ejemplo n.º 8
0
        // This method is used as a helper method to accommodate for the lag on the service side between creating a new
        // model and creating a digital twin that implements this model. The work around is to list the model(s) after
        // creating them in order to accommodate for that lag. Once service side investigates and comes up with a solution,
        // there is no need to list the models after creating them.
        protected async Task CreateAndListModelsAsync(DigitalTwinsClient client, List <string> lists)
        {
            await client.CreateModelsAsync(lists).ConfigureAwait(false);

            // list the models
            AsyncPageable <DigitalTwinsModelData> models = client.GetModelsAsync();

            await foreach (DigitalTwinsModelData model in models)
            {
                Console.WriteLine($"{model.Id}");
            }
        }
        public override async Task GlobalCleanupAsync()
        {
            // Global cleanup code that runs once at the end of test execution.
            await base.GlobalCleanupAsync();

            // List all the models and delete all of them.
            AsyncPageable <DigitalTwinsModelData> allModels = _digitalTwinsClient.GetModelsAsync();

            await foreach (DigitalTwinsModelData model in allModels)
            {
                await _digitalTwinsClient.DeleteModelAsync(model.Id).ConfigureAwait(false);
            }
        }
        public static async Task ListModels(DigitalTwinsClient client)
        {
            string[] dependenciesFor = null;

            try
            {
                AsyncPageable <ModelData> results = client.GetModelsAsync(dependenciesFor, false);
                await foreach (ModelData md in results)
                {
                    Console.WriteLine(md.Id);
                }
            }
            catch (RequestFailedException e)
            {
                Console.WriteLine($"Response {e.Status}: {e.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Gets all the models within the ADT service instance.
        /// </summary>
        public async Task GetAllModelsAsync()
        {
            PrintHeader("LISTING MODELS");
            try
            {
                // Get all the twin types

                #region Snippet:DigitalTwinsSampleGetModels

                AsyncPageable <ModelData> allModels = client.GetModelsAsync();
                await foreach (ModelData model in allModels)
                {
                    Console.WriteLine($"Model Id: {model.Id}, display name: {model.DisplayName["en"]}, upload time: {model.UploadTime}, is decommissioned: {model.Decommissioned}");
                }

                #endregion Snippet:DigitalTwinsSampleGetModels
            }
            catch (RequestFailedException ex)
            {
                FatalError($"Failed to get all the models due to:\n{ex}");
            }
        }
Ejemplo n.º 12
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            DigitalTwinsClient        client;
            AsyncPageable <ModelData> modelList;

            try
            {
                ManagedIdentityCredential cred = new ManagedIdentityCredential(adtAppId);

                DigitalTwinsClientOptions opts = new DigitalTwinsClientOptions {
                    Transport = new HttpClientTransport(httpClient)
                };

                client = new DigitalTwinsClient(new Uri(adtInstanceUrl), cred, opts);

                modelList = client.GetModelsAsync(null, true);

                await foreach (ModelData md in modelList)
                {
                    log.LogInformation($"Id: {md.Id}");
                }

                log.LogInformation("Done");
            }
            catch (Exception e)
            {
                log.LogCritical($"Authentication or client creation error: {e.Message}");
                return(new BadRequestObjectResult(e.Message));
            }

            return(new OkObjectResult(modelList));
        }
        /// <summary>
        /// Create a temporary component model, twin model and digital twin instance.
        /// Publish a telemetry message and a component telemetry message to the digital twin instance.
        /// </summary>
        public async Task RunSamplesAsync(DigitalTwinsClient client)
        {
            PrintHeader("PUBLISH TELEMETRY MESSAGE SAMPLE");

            // For the purpose of this example we will create temporary models using a random model Ids.
            // We will also create temporary twin instances to publish the telemetry to.

            string componentModelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryComponentModelPrefix, client);

            string modelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryModelPrefix, client);

            string twinId = await GetUniqueTwinIdAsync(SamplesConstants.TemporaryTwinPrefix, client);

            string newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
                                              .Replace(SamplesConstants.ComponentId, componentModelId);

            string newModelPayload = SamplesConstants.TemporaryModelWithComponentPayload
                                     .Replace(SamplesConstants.ModelId, modelId)
                                     .Replace(SamplesConstants.ComponentId, componentModelId);

            // Then we create the models.
            await client
            .CreateModelsAsync(new[] { newComponentModelPayload, newModelPayload });

            // Get the models we just created
            AsyncPageable <DigitalTwinsModelData> models = client.GetModelsAsync();

            await foreach (DigitalTwinsModelData model in models)
            {
                Console.WriteLine($"Successfully created model '{model.Id}'");
            }

            // Create digital twin with Component payload.
            string twinPayload = SamplesConstants.TemporaryTwinPayload
                                 .Replace(SamplesConstants.ModelId, modelId);

            BasicDigitalTwin basicDigitalTwin = JsonSerializer.Deserialize <BasicDigitalTwin>(twinPayload);

            Response <BasicDigitalTwin> createDigitalTwinResponse = await client.CreateOrReplaceDigitalTwinAsync <BasicDigitalTwin>(twinId, basicDigitalTwin);

            Console.WriteLine($"Created digital twin '{createDigitalTwinResponse.Value.Id}'.");

            try
            {
                #region Snippet:DigitalTwinsSamplePublishTelemetry

                // construct your json telemetry payload by hand.
                await client.PublishTelemetryAsync(twinId, Guid.NewGuid().ToString(), "{\"Telemetry1\": 5}");

                Console.WriteLine($"Published telemetry message to twin '{twinId}'.");

                #endregion Snippet:DigitalTwinsSamplePublishTelemetry

                #region Snippet:DigitalTwinsSamplePublishComponentTelemetry

                // construct your json telemetry payload by serializing a dictionary.
                var telemetryPayload = new Dictionary <string, int>
                {
                    { "ComponentTelemetry1", 9 }
                };
                await client.PublishComponentTelemetryAsync(
                    twinId,
                    "Component1",
                    Guid.NewGuid().ToString(),
                    JsonSerializer.Serialize(telemetryPayload));

                Console.WriteLine($"Published component telemetry message to twin '{twinId}'.");

                #endregion Snippet:DigitalTwinsSamplePublishComponentTelemetry
            }
            catch (Exception ex)
            {
                FatalError($"Failed to publish a telemetry message due to: {ex.Message}");
            }

            try
            {
                // Delete the twin.
                await client.DeleteDigitalTwinAsync(twinId);

                // Delete the models.
                await client.DeleteModelAsync(modelId);

                await client.DeleteModelAsync(componentModelId);
            }
            catch (RequestFailedException ex) when(ex.Status == (int)HttpStatusCode.NotFound)
            {
                // Digital twin or models do not exist.
            }
            catch (RequestFailedException ex)
            {
                FatalError($"Failed to delete due to: {ex.Message}");
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Creates a digital twin with Component and upates Component
        /// </summary>
        public async Task RunSamplesAsync(DigitalTwinsClient client)
        {
            PrintHeader("COMPONENT SAMPLE");

            // For the purpose of this example we will create temporary models using a random model Ids.
            // We have to make sure these model Ids are unique within the DT instance.

            string componentModelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryComponentModelPrefix, client);

            string modelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryModelPrefix, client);

            string basicDtId = await GetUniqueTwinIdAsync(SamplesConstants.TemporaryTwinPrefix, client);

            string newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
                                              .Replace(SamplesConstants.ComponentId, componentModelId);

            string newModelPayload = SamplesConstants.TemporaryModelWithComponentPayload
                                     .Replace(SamplesConstants.ModelId, modelId)
                                     .Replace(SamplesConstants.ComponentId, componentModelId);

            // Then we create models
            await client.CreateModelsAsync(
                new[]
            {
                newComponentModelPayload,
                newModelPayload
            });

            // Get the models we just created
            AsyncPageable <DigitalTwinsModelData> models = client.GetModelsAsync();

            await foreach (DigitalTwinsModelData model in models)
            {
                Console.WriteLine($"Created model {model.Id}.");
            }

            #region Snippet:DigitalTwinsSampleCreateBasicTwin

            // Create digital twin with component payload using the BasicDigitalTwin serialization helper

            var basicTwin = new BasicDigitalTwin
            {
                Id = basicDtId,
                // model Id of digital twin
                Metadata = { ModelId = modelId },
                Contents =
                {
                    // digital twin properties
                    { "Prop1",          "Value1"            },
                    { "Prop2",                          987 },
                    // component
                    {
                        "Component1",
                        new BasicDigitalTwinComponent
                        {
                            // component properties
                            Contents =
                            {
                                { "ComponentProp1", "Component value 1" },
                                { "ComponentProp2",                 123 },
                            },
                        }
                    },
                },
            };

            Response <BasicDigitalTwin> createDigitalTwinResponse = await client.CreateOrReplaceDigitalTwinAsync(basicDtId, basicTwin);

            Console.WriteLine($"Created digital twin '{createDigitalTwinResponse.Value.Id}'.");

            #endregion Snippet:DigitalTwinsSampleCreateBasicTwin

            // You can also get a digital twin as a BasicDigitalTwin type.
            // It works well for basic stuff, but as you can see it gets more difficult when delving into
            // more complex properties, like components.

            #region Snippet:DigitalTwinsSampleGetBasicDigitalTwin

            Response <BasicDigitalTwin> getBasicDtResponse = await client.GetDigitalTwinAsync <BasicDigitalTwin>(basicDtId);

            BasicDigitalTwin basicDt = getBasicDtResponse.Value;

            // Must cast Component1 as a JsonElement and get its raw text in order to deserialize it as a dictionary
            string component1RawText = ((JsonElement)basicDt.Contents["Component1"]).GetRawText();
            var    component1        = JsonSerializer.Deserialize <BasicDigitalTwinComponent>(component1RawText);

            Console.WriteLine($"Retrieved and deserialized digital twin {basicDt.Id}:\n\t" +
                              $"ETag: {basicDt.ETag}\n\t" +
                              $"ModelId: {basicDt.Metadata.ModelId}\n\t" +
                              $"Prop1: {basicDt.Contents["Prop1"]} and last updated on {basicDt.Metadata.PropertyMetadata["Prop1"].LastUpdatedOn}\n\t" +
                              $"Prop2: {basicDt.Contents["Prop2"]} and last updated on {basicDt.Metadata.PropertyMetadata["Prop2"].LastUpdatedOn}\n\t" +
                              $"Component1.Prop1: {component1.Contents["ComponentProp1"]} and  last updated on: {component1.Metadata["ComponentProp1"].LastUpdatedOn}\n\t" +
                              $"Component1.Prop2: {component1.Contents["ComponentProp2"]} and last updated on: {component1.Metadata["ComponentProp2"].LastUpdatedOn}");

            #endregion Snippet:DigitalTwinsSampleGetBasicDigitalTwin

            string customDtId = await GetUniqueTwinIdAsync(SamplesConstants.TemporaryTwinPrefix, client);

            // Alternatively, you can create your own custom data types to serialize and deserialize your digital twins.
            // By specifying your properties and types directly, it requires less code or knowledge of the type for
            // interaction.

            #region Snippet:DigitalTwinsSampleCreateCustomTwin

            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}'.");

            #endregion Snippet:DigitalTwinsSampleCreateCustomTwin

            // Getting a digital twin as a custom data type is extremely easy.
            // Custom types provide the best possible experience.

            #region Snippet:DigitalTwinsSampleGetCustomDigitalTwin

            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}");

            #endregion Snippet:DigitalTwinsSampleGetCustomDigitalTwin

            #region Snippet:DigitalTwinsSampleUpdateComponent

            // 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}'.");

            #endregion Snippet:DigitalTwinsSampleUpdateComponent

            // Get Component

            #region Snippet:DigitalTwinsSampleGetComponent

            await client.GetComponentAsync <MyCustomComponent>(basicDtId, SamplesConstants.ComponentName);

            Console.WriteLine($"Retrieved component for digital twin '{basicDtId}'.");

            #endregion Snippet:DigitalTwinsSampleGetComponent

            // Clean up

            try
            {
                await client.DeleteDigitalTwinAsync(basicDtId);

                await client.DeleteDigitalTwinAsync(customDtId);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine($"Failed to delete digital twin due to {ex}");
            }

            try
            {
                await client.DeleteModelAsync(modelId);

                await client.DeleteModelAsync(componentModelId);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine($"Failed to delete models due to {ex}");
            }
        }
        // <Async_signature>
        static async Task Main(string[] args)
        {
            // </Async_signature>
            Console.WriteLine("Hello World!");
            // <Authentication_code>
            string adtInstanceUrl = "https://<your-Azure-Digital-Twins-instance-hostName>";

            var credential = new DefaultAzureCredential();
            var client     = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential);

            Console.WriteLine($"Service client created – ready to go");
            // </Authentication_code>

            // <Model_code>
            Console.WriteLine();
            Console.WriteLine("Upload a model");
            string dtdl   = File.ReadAllText("SampleModel.json");
            var    models = new List <string> {
                dtdl
            };

            // Upload the model to the service
            // <Model_try_catch>
            try
            {
                await client.CreateModelsAsync(models);

                Console.WriteLine("Models uploaded to the instance:");
            }
            catch (RequestFailedException e)
            {
                Console.WriteLine($"Upload model error: {e.Status}: {e.Message}");
            }
            // </Model_try_catch>

            // <Print_model>
            // Read a list of models back from the service
            AsyncPageable <DigitalTwinsModelData> modelDataList = client.GetModelsAsync();

            await foreach (DigitalTwinsModelData md in modelDataList)
            {
                Console.WriteLine($"Model: {md.Id}");
            }
            // </Print_model>
            // </Model_code>

            // <Initialize_twins>
            var twinData = new BasicDigitalTwin();

            twinData.Metadata.ModelId = "dtmi:example:SampleModel;1";
            twinData.Contents.Add("data", $"Hello World!");

            string prefix = "sampleTwin-";

            for (int i = 0; i < 3; i++)
            {
                try
                {
                    twinData.Id = $"{prefix}{i}";
                    await client.CreateOrReplaceDigitalTwinAsync <BasicDigitalTwin>(twinData.Id, twinData);

                    Console.WriteLine($"Created twin: {twinData.Id}");
                }
                catch (RequestFailedException e)
                {
                    Console.WriteLine($"Create twin error: {e.Status}: {e.Message}");
                }
            }
            // </Initialize_twins>

            // <Use_create_relationship>
            // Connect the twins with relationships
            await CreateRelationshipAsync(client, "sampleTwin-0", "sampleTwin-1");
            await CreateRelationshipAsync(client, "sampleTwin-0", "sampleTwin-2");

            // </Use_create_relationship>

            // <Use_list_relationships>
            //List the relationships
            await ListRelationshipsAsync(client, "sampleTwin-0");

            // </Use_list_relationships>

            // <Query_twins>
            // Run a query for all twins
            string query = "SELECT * FROM digitaltwins";
            AsyncPageable <BasicDigitalTwin> queryResult = client.QueryAsync <BasicDigitalTwin>(query);

            await foreach (BasicDigitalTwin twin in queryResult)
            {
                Console.WriteLine(JsonSerializer.Serialize(twin));
                Console.WriteLine("---------------");
            }
            // </Query_twins>
        }
Ejemplo n.º 16
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            string             clientId       = "<clientId>";
            string             tenantId       = "<tenatId>";
            string             adtInstanceUrl = "https://yourinstance";
            var                credentials    = new InteractiveBrowserCredential(tenantId, clientId);
            DigitalTwinsClient client         = new DigitalTwinsClient(new Uri(adtInstanceUrl), credentials);

            Console.WriteLine($"Service client created – ready to go");

            Console.WriteLine();
            Console.WriteLine($"Upload a model");
            var    typeList = new List <string>();
            string dtdl     = File.ReadAllText("Models/SampleModel.json");

            typeList.Add(dtdl);

            // Upload the model to the service
            try {
                await client.CreateModelsAsync(typeList);
            } catch (RequestFailedException rex) {
                Console.WriteLine($"Load model: {rex.Status}:{rex.Message}");
            }
            // Read a list of models back from the service
            AsyncPageable <ModelData> modelDataList = client.GetModelsAsync();

            await foreach (ModelData md in modelDataList)
            {
                Console.WriteLine($"Type name: {md.DisplayName}: {md.Id}");
            }

            // Initialize twin data
            BasicDigitalTwin twinData = new BasicDigitalTwin();

            twinData.Metadata.ModelId = "dtmi:com:contoso:SampleModel;1";
            twinData.CustomProperties.Add("data", $"Hello World!");

            string prefix = "sampleTwin-";

            for (int i = 0; i < 3; i++)
            {
                try {
                    twinData.Id = $"{prefix}{i}";
                    await client.CreateDigitalTwinAsync($"{prefix}{i}", JsonSerializer.Serialize(twinData));

                    Console.WriteLine($"Created twin: {prefix}{i}");
                } catch (RequestFailedException rex) {
                    Console.WriteLine($"Create twin error: {rex.Status}:{rex.Message}");
                }
            }

            // Connect the twins with relationships
            await CreateRelationship(client, "sampleTwin-0", "sampleTwin-1");
            await CreateRelationship(client, "sampleTwin-0", "sampleTwin-2");

            //List the relationships
            await ListRelationships(client, "sampleTwin-0");

            // Run a query
            AsyncPageable <string> result = client.QueryAsync("Select * From DigitalTwins");

            await foreach (string twin in result)
            {
                object jsonObj    = JsonSerializer.Deserialize <object>(twin);
                string prettyTwin = JsonSerializer.Serialize(jsonObj, new JsonSerializerOptions {
                    WriteIndented = true
                });
                Console.WriteLine(prettyTwin);
                Console.WriteLine("---------------");
            }
        }