您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

使用 AutoRest 创建 Azure 数字孪生的自定义 SdkCreate custom SDKs for Azure Digital Twins using AutoRest

目前,用于与 Azure 数字孪生 Api 交互的已发布数据平面 SDK 仅适用于 .NET (c #)。Right now, the only published data plane SDK for interacting with the Azure Digital Twins APIs is for .NET (C#). 你可以阅读有关 .NET SDK 和 Api 的一般信息,请参阅操作方法:使用 Azure 数字孪生 api 和 sdkYou can read about the .NET SDK, and the APIs in general, in How-to: Use the Azure Digital Twins APIs and SDKs. 如果你使用的是另一种语言,本文将演示如何使用 AutoRest 按你选择的语言生成自己的数据平面 SDK。If you are working in another language, this article will show you how to generate your own data plane SDK in the language of your choice, using AutoRest.

备注

如果需要,还可以使用 AutoRest 生成控制平面 SDK。You can also use AutoRest to generate a control plane SDK if you would like. 为此,请使用控制平面 Swagger (OpenAPI)文件而不是数据平面来完成本文中的步骤。To do this, complete the steps in this article using the control plane Swagger (OpenAPI) file instead of the data plane one.

设置计算机Set up your machine

若要生成 SDK,你将需要:To generate an SDK, you will need:

  • AutoRest,版本2.0.4413 (目前不支持版本3)AutoRest, version 2.0.4413 (version 3 isn't currently supported)
  • 作为 AutoRest 的先决条件Node.jsNode.js as a pre-requisite to AutoRest
  • digitaltwins.js的 Azure 数字孪生数据平面 Swagger (OpenAPI)文件及其随附的示例文件夹。The Azure Digital Twins data plane Swagger (OpenAPI) file entitled digitaltwins.json, and its accompanying folder of examples. 将 Swagger 文件及其示例的文件夹下载到本地计算机。Download the Swagger file and its folder of examples to your local machine.

一旦你的计算机配备了上述列表中的所有内容,你就可以使用 AutoRest 创建该 SDK。Once your machine is equipped with everything from the list above, you're ready to use AutoRest to create the SDK.

创建具有 AutoRest 的 SDKCreate the SDK with AutoRest

如果已安装 Node.js,则可以运行以下命令,确保已安装正确版本的 AutoRest:If you have Node.js installed, you can run this command to make sure you have the right version of AutoRest installed:

npm install -g autorest@2.0.4413

若要在 Azure 数字孪生 Swagger 文件中运行 AutoRest,请执行以下步骤:To run AutoRest against the Azure Digital Twins Swagger file, follow these steps:

  1. 将 Azure 数字孪生 Swagger 文件及其随附的示例文件夹复制到工作目录。Copy the Azure Digital Twins Swagger file and its accompanying folder of examples into a working directory.
  2. 使用命令提示符窗口切换到该工作目录。Use a command prompt window to switch to that working directory.
  3. 在以下命令中运行 AutoRest。Run AutoRest with the following command. <language> 占位符替换为你选择的语言: --python--java--go 等。Replace the <language> placeholder with your language of choice: --python, --java, --go, and so on. (可在AUTOREST 自述文件中找到完整的选项列表。)(You can find the full list of options in the AutoRest README.)
autorest --input-file=adtApiSwagger.json --<language> --output-folder=ADTApi --add-credentials --azure-arm --namespace=ADTApi

因此,你将在工作目录中看到一个名为ADTApi的新文件夹。As a result, you'll see a new folder named ADTApi in your working directory. 生成的 SDK 文件将具有命名空间ADTApiThe generated SDK files will have the namespace ADTApi. 您将继续使用该命名空间,这篇文章中的其他用法示例。You'll continue to use that namespace through the rest of the usage examples in this article.

AutoRest 支持多种语言代码生成器。AutoRest supports a wide range of language code generators.

将 SDK 添加到 Visual Studio 项目Add the SDK to a Visual Studio project

可以将 AutoRest 生成的文件直接包括到 .NET 解决方案中。You can include the files generated by AutoRest directly into a .NET solution. 不过,您可能需要在多个不同的项目(客户端应用程序、Azure Functions 的应用程序等)中包括 Azure 数字孪生 SDK。However, it's likely that you'll want to include the Azure Digital Twins SDK in several separate projects (your client apps, Azure Functions apps, and so on). 出于此原因,从生成的文件生成一个单独的项目(.NET 类库)可能会很有用。For this reason, it can be useful to build a separate project (a .NET class library) from the generated files. 然后,可以将此类库项目作为项目引用包含到多个解决方案中。Then, you can include this class library project into several solutions as a project reference.

本部分提供有关如何将 SDK 构建为类库的说明,它是其自己的项目,可以包含在其他项目中。This section gives instructions on how to build the SDK as a class library, which is its own project and can be included into other projects. 这些步骤依赖于Visual Studio (可从此处安装最新版本)。These steps rely on Visual Studio (you can install the latest version from here).

下面是相关步骤:Here are the steps:

  1. 为类库创建新的 Visual Studio 解决方案Create a new Visual Studio solution for a class library
  2. 使用ADTApi作为项目名称Use ADTApi as the project name
  3. 在 "解决方案资源管理器" 中,右键选择生成的解决方案的ADTApi项目,然后选择 "添加 > 现有项 ... "In Solutions Explorer, right-select the ADTApi project of the generated solution and choose Add > Existing Item...
  4. 找到生成 SDK 的文件夹,然后选择根级别的文件Find the folder where you generated the SDK, and select the files at the root level
  5. 按 "确定"Press "Ok"
  6. 将文件夹添加到项目(在解决方案资源管理器中右键选择项目,然后选择 "添加 >" 新建文件夹")Add a folder to the project (right-select the project in Solution Explorer, and choose Add > New Folder)
  7. 命名文件夹模型Name the folder Models
  8. 右键选择解决方案资源管理器中的 "模型" 文件夹,然后选择 "添加 > 现有项 ... "Right-select the Models folder in Solutions Explorer and select Add > Existing Item...
  9. 选择生成的 SDK 的 "模型" 文件夹中的文件,并按 "确定"Select the files in the Models folder of the generated SDK and press "Ok"

若要成功生成 SDK,你的项目将需要以下参考:To build the SDK successfully, your project will need these references:

  • Microsoft.Rest.ClientRuntime
  • Microsoft.Rest.ClientRuntime.Azure

若要添加这些工具,请打开 " > Nuget 包管理器 > 管理解决方案的 NuGet 包..."。To add these, open Tools > NuGet Package Manager > Manage NuGet Packages for Solution....

  1. 在面板中,确保选中 "浏览" 选项卡In the panel, make sure the Browse tab is selected
  2. 搜索Microsoft. RestSearch for Microsoft.Rest
  3. 选择 ClientRuntimeClientRuntime.Azure 包,并将其添加到解决方案Select the ClientRuntime and ClientRuntime.Azure packages, and add them to your solution

你现在可以生成项目,并将其作为项目引用包含在你编写的任何 Azure 数字孪生应用程序中。You can now build the project, and include it as a project reference in any Azure Digital Twins application you write.

生成的 Sdk 一般准则General guidelines for generated SDKs

本部分包含有关使用生成的 SDK 的常规信息和指南。This section contains general information about and guidelines for using the generated SDK.

同步和异步调用Synchronous and asynchronous calls

所有 SDK 函数都提供同步和异步版本。All SDK functions come in synchronous and asynchronous versions.

类型化和非类型化数据Typed and untyped data

REST API 调用通常返回强类型对象。REST API calls generally return strongly typed objects. 不过,由于 Azure 数字孪生允许用户定义孪生的自定义类型,因此无法为许多 Azure 数字孪生调用预定义静态返回数据。However, because Azure Digital Twins lets users define their own custom types for twins, there is no way to pre-define static return data for many Azure Digital Twins calls. 相反,Api 将返回强类型化包装器类型(如果适用),并且自定义类型的 "输入数据类型" 是在 Json.NET 对象中(在 API 签名中出现数据类型 "对象" 的情况下使用)。Instead, the APIs return strongly typed wrapper types where applicable, and the custom-typed twin data is in Json.NET objects (used wherever the data type "object" appears in the API signatures). 您可以在代码中适当地强制转换这些对象。You can cast these objects appropriately in your code.

错误处理。Error handling

当 SDK 中发生错误(包括 HTTP 错误,如404)时,SDK 将引发异常。Whenever an error occurs in the SDK (including HTTP errors such as 404), the SDK will throw an exception. 出于此原因,请务必将 try/catch 块内的所有 API 调用封装。For this reason, it's important to encapsulate all API calls within try/catch blocks.

下面是一个代码片段,它尝试添加一个克隆,并在此过程中捕获任何错误:Here is a code snippet that tries to add a twin and catches any errors in this process:

try
{
    await client.DigitalTwins.AddAsync(id, initData);
    Console.WriteLine($"Created a twin successfully: {id}");
}
catch (ErrorResponseException e)
{
    Console.WriteLine($"*** Error creating twin {id}: {e.Response.StatusCode}"); 
}

分页Paging

AutoRest 为 SDK 生成两种类型的分页模式:AutoRest generates two types of paging patterns for the SDK:

  • 一个用于除查询 API 之外的所有 ApiOne for all APIs except the Query API
  • 一个用于查询 APIOne for the Query API

在非查询分页模式下,每次调用都有两个版本:In the non-query paging pattern, there are two versions of each call:

  • 用于初始调用的版本(例如 DigitalTwins.ListEdges()A version to make the initial call (such as DigitalTwins.ListEdges())
  • 用于获取以下页面的版本。A version to get the following pages. 这些调用的后缀为 "Next" (如 DigitalTwins.ListEdgesNext()These calls have a suffix of "Next" (like DigitalTwins.ListEdgesNext())

以下代码片段演示了如何从 Azure 数字孪生检索传出关系的分页列表:Here is a code snippet showing how to retrieve a paged list of outgoing relationships from Azure Digital Twins:

try
{
    // List to hold the results in
    List<object> relList = new List<object>();
    // Enumerate the IPage object returned to get the results
    // ListAsync will throw if an error occurs
    IPage<object> relPage = await client.DigitalTwins.ListEdgesAsync(id);
    relList.AddRange(relPage);
    // If there are more pages, the NextPageLink in the page is set
    while (relPage.NextPageLink != null)
    {
        // Get more pages...
        relPage = await client.DigitalTwins.ListEdgesNextAsync(relPage.NextPageLink);
        relList.AddRange(relPage);
    }
    Console.WriteLine($"Found {relList.Count} relationships on {id}");
    // Do something with each object found
    // As relationships are custom types, they are JSON.Net types
    foreach (JObject r in relList)
    {
        string relId = r.Value<string>("$edgeId");
        string relName = r.Value<string>("$relationship");
        Console.WriteLine($"Found relationship {relId} from {id}");
    }
}
catch (ErrorResponseException e)
{
    Console.WriteLine($"*** Error retrieving relationships on {id}: {e.Response.StatusCode}");
}

第二种模式仅为查询 API 生成。The second pattern is only generated for the Query API. 它显式使用 continuationTokenIt uses a continuationToken explicitly.

下面是此模式的示例:Here is an example with this pattern:

string query = "SELECT * FROM digitaltwins";
string conToken = null; // continuation token from the query
int page = 0;
try
{
    // Repeat the query while there are pages
    do
    {
        QuerySpecification spec = new QuerySpecification(query, conToken);
        QueryResult qr = await client.Query.QueryTwinsAsync(spec);
        page++;
        Console.WriteLine($"== Query results page {page}:");
        if (qr.Items != null)
        {
            // Query returns are JObjects
            foreach(JObject o in qr.Items)
            {
                string twinId = o.Value<string>("$dtId");
                Console.WriteLine($"  Found {twinId}");
            }
        }
        Console.WriteLine($"== End query results page {page}");
        conToken = qr.ContinuationToken;
    } while (conToken != null);
} catch (ErrorResponseException e)
{
    Console.WriteLine($"*** Error in twin query: ${e.Response.StatusCode}");
}

后续步骤Next steps

逐步完成创建可使用 SDK 的客户端应用的步骤:Walk through the steps to create a client app where you can use your SDK: