Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding some basic samples for autogenerated SDKv2 for TypeSript language #1895

Merged
merged 13 commits into from
Nov 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions sdk/typescript/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
SUBSCRIPTION_ID=<SUBSCRIPTION_ID>
RESOURCEGROUP_NAME=<RG_NAME>
WORKSPACE_NAME=<WORKSPACE_NAME>
LOCATION_NAME=eastus

# Used to authenticate using Azure AD as a service principal for role-based authentication.
#
# See the documentation for `EnvironmentCredential` at the following link:
# https://docs.microsoft.com/javascript/api/@azure/identity/environmentcredential
# AZURE_TENANT_ID=<AD tenant id or name>
# AZURE_CLIENT_ID=<ID of the user/service principal to authenticate as>
# AZURE_CLIENT_SECRET=<client secret used to authenticate to Azure AD>
109 changes: 109 additions & 0 deletions sdk/typescript/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# AzureMachineLearningWorkspaces client library for JavaScript

This package contains an isomorphic SDK (runs both in Node.js and in browsers) for AzureMachineLearningWorkspaces client.

These APIs allow end users to operate on Azure Machine Learning Workspace resources.

[Source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/machinelearning/arm-machinelearning) |
[Package (NPM)](https://www.npmjs.com/package/@azure/arm-machinelearning) |
[API reference documentation](https://docs.microsoft.com/javascript/api/@azure/arm-machinelearning) |
[Samples](https://github.com/Azure-Samples/azure-samples-js-management)

## Getting started

### Currently supported environments

- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule)
- Latest versions of Safari, Chrome, Edge and Firefox.

See our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) for more details.

### Prerequisites

- An [Azure subscription][azure_sub].

### Install the `@azure/arm-machinelearning` package

Install the AzureMachineLearningWorkspaces client library for JavaScript with `npm`:

```bash
npm install @azure/arm-machinelearning
```

### Create and authenticate a `AzureMachineLearningWorkspaces`

To create a client object to access the AzureMachineLearningWorkspaces API, you will need the `endpoint` of your AzureMachineLearningWorkspaces resource and a `credential`. The AzureMachineLearningWorkspaces client can use Azure Active Directory credentials to authenticate.
You can find the endpoint for your AzureMachineLearningWorkspaces resource in the [Azure Portal][azure_portal].

You can authenticate with Azure Active Directory using a credential from the [@azure/identity][azure_identity] library or [an existing AAD Token](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-with-a-pre-fetched-access-token).

To use the [DefaultAzureCredential][defaultazurecredential] provider shown below, or other credential providers provided with the Azure SDK, please install the `@azure/identity` package:

```bash
npm install @azure/identity
```

You will also need to **register a new AAD application and grant access to AzureMachineLearningWorkspaces** by assigning the suitable role to your service principal (note: roles such as `"Owner"` will not grant the necessary permissions).
Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET`.

For more information about how to create an Azure AD Application check out [this guide](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal).

```javascript
const { AzureMachineLearningWorkspaces } = require("@azure/arm-machinelearning");
const { DefaultAzureCredential } = require("@azure/identity");
// For client-side applications running in the browser, use InteractiveBrowserCredential instead of DefaultAzureCredential. See https://aka.ms/azsdk/js/identity/examples for more details.

const subscriptionId = "00000000-0000-0000-0000-000000000000";
const client = new AzureMachineLearningWorkspaces(new DefaultAzureCredential(), subscriptionId);

// For client-side applications running in the browser, use this code instead:
// const credential = new InteractiveBrowserCredential({
// tenantId: "<YOUR_TENANT_ID>",
// clientId: "<YOUR_CLIENT_ID>"
// });
// const client = new AzureMachineLearningWorkspaces(credential, subscriptionId);
```


### JavaScript Bundle
To use this client library in the browser, first you need to use a bundler. For details on how to do this, please refer to our [bundling documentation](https://aka.ms/AzureSDKBundling).

## Key concepts

### AzureMachineLearningWorkspaces

`AzureMachineLearningWorkspaces` is the primary interface for developers using the AzureMachineLearningWorkspaces client library. Explore the methods on this client object to understand the different features of the AzureMachineLearningWorkspaces service that you can access.

## Troubleshooting

### Logging

Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the `AZURE_LOG_LEVEL` environment variable to `info`. Alternatively, logging can be enabled at runtime by calling `setLogLevel` in the `@azure/logger`:

```javascript
const { setLogLevel } = require("@azure/logger");
setLogLevel("info");
```

For more detailed instructions on how to enable logs, you can look at the [@azure/logger package docs](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/logger).

## Next steps

Please take a look at the [samples](https://github.com/Azure-Samples/azure-samples-js-management) directory for detailed examples on how to use this library.

## Contributing

If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code.

## Related projects

- [Microsoft Azure SDK for JavaScript](https://github.com/Azure/azure-sdk-for-js)

![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fmachinelearning%2Farm-machinelearning%2FREADME.png)

[azure_cli]: https://docs.microsoft.com/cli/azure
[azure_sub]: https://azure.microsoft.com/free/
[azure_sub]: https://azure.microsoft.com/free/
[azure_portal]: https://portal.azure.com
[azure_identity]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity
[defaultazurecredential]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#defaultazurecredential
44 changes: 44 additions & 0 deletions sdk/typescript/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
{
"name": "@azure-samples/machinelearning-ts",
"private": true,
"version": "1.0.0",
"description": "Azure machinelearning client library samples for TypeScript",
"engines": {
"node": ">=14.0.0"
},
"scripts": {
"build": "tsc",
"prebuild": "rimraf dist/"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Azure/azure-sdk-for-js.git",
"directory": "sdk/machinelearning/arm-machinelearning"
},
"keywords": [
"node",
"azure",
"typescript",
"browser",
"cloud",
"isomorphic",
"machinelearning"
],
"author": "Microsoft Corporation",
"license": "MIT",
"bugs": {
"url": "https://github.com/Azure/azure-sdk-for-js/issues"
},
"homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/machinelearning/arm-machinelearning",
"dependencies": {
"@azure/arm-machinelearning": "file:../azure-arm-machinelearning-2.1.0/package",
"@azure/identity": "^2.1.0-beta.2",
"@azure/keyvault-secrets": "latest",
"dotenv": "latest"
},
"devDependencies": {
"@types/node": "^14.0.0",
"typescript": "~4.8.0",
"rimraf": "latest"
}
}
120 changes: 120 additions & 0 deletions sdk/typescript/src/resources/compute/computeCreateOrUpdate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

/**
* @summary Gets computes in specified workspace.
*/
import {
ComputeResource
} from "@azure/arm-machinelearning";
// import { DefaultAzureCredential } from "@azure/identity";
import { client, getEnvironmentVariable } from "../../utils";

// Load the .env file if it exists
import * as dotenv from "dotenv";
dotenv.config();

// const subscriptionId = getEnvironmentVariable("SUBSCRIPTION_ID");
const resourceGroupName = getEnvironmentVariable("RESOURCEGROUP_NAME");
const workspaceName = getEnvironmentVariable("WORKSPACE_NAME");
const azureLocation = getEnvironmentVariable("LOCATION_NAME");

/**
* This sample demonstrates how to Creates or updates compute. This call will overwrite a compute if it exists. This is a nonrecoverable operation. If your intent is to create a new compute, do a GET first to verify that it does not exist yet.
*
* @summary Creates or updates compute. This call will overwrite a compute if it exists. This is a nonrecoverable operation. If your intent is to create a new compute, do a GET first to verify that it does not exist yet.
* x-ms-original-file: specification/machinelearningservices/resource-manager/Microsoft.MachineLearningServices/stable/2022-10-01/examples/Compute/createOrUpdate/BasicAmlCompute.json
*/
async function createAmlCompute() {
const computeName = "compute1234";
const vmSize = "Standard_DS3_v2";
const parameters: ComputeResource = {
location: azureLocation,
properties: {
computeType: "AmlCompute",
properties: {
enableNodePublicIp: true,
isolatedNetwork: false,
osType: "Linux",
// remoteLoginPortPublicAccess: "NotSpecified",
scaleSettings: {
maxNodeCount: 3,
minNodeCount: 0,
nodeIdleTimeBeforeScaleDown: "PT5M"
},
vmPriority: "Dedicated",
vmSize: vmSize
}
}
};
// const credential = new DefaultAzureCredential();
// const client = new AzureMachineLearningWorkspaces(credential, subscriptionId);
try {
console.log("Creating an AmlCompute ...");
let amlComputeOperationsResponse = await client.computeOperations.beginCreateOrUpdateAndWait(
resourceGroupName,
workspaceName,
computeName,
parameters
);
console.log(amlComputeOperationsResponse);
console.log(`Created AmlCompute ${amlComputeOperationsResponse.name} successfully`);
} catch (err: any) {
console.log(
`errorMessage - ${err.message}\n`
);
}
}


/**
* This sample demonstrates how to Creates or updates compute. This call will overwrite a compute if it exists. This is a nonrecoverable operation. If your intent is to create a new compute, do a GET first to verify that it does not exist yet.
*
* @summary Creates or updates compute. This call will overwrite a compute if it exists. This is a nonrecoverable operation. If your intent is to create a new compute, do a GET first to verify that it does not exist yet.
* x-ms-original-file: specification/machinelearningservices/resource-manager/Microsoft.MachineLearningServices/stable/2022-10-01/examples/Compute/createOrUpdate/BasicAKSCompute.json
*/
async function createAksCompute() {
const computeName = "akscompute123";
const parameters: ComputeResource = {
location: azureLocation,
properties: { computeType: "AKS" }
};
// const credential = new DefaultAzureCredential();
// const client = new AzureMachineLearningWorkspaces(credential, subscriptionId);
try {
console.log("Creating an AksCompute ...");
const aksComputeOperationsResponse = await client.computeOperations.beginCreateOrUpdateAndWait(
resourceGroupName,
workspaceName,
computeName,
parameters
);
console.log(aksComputeOperationsResponse);
console.log(`Created AksCompute ${aksComputeOperationsResponse.name} successfully`);
} catch (err: any) {
console.log(
`errorMessage - ${err.message}\n`
);
}
}

// getComputes().catch(console.error);

export async function main(): Promise<void> {
// This sample uses DefaultAzureCredential, which supports a number of authentication mechanisms.
// See https://docs.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest for more information
// about DefaultAzureCredential and the other credentials that are available for use.
//console.log("Creating an AML Compute");
await createAmlCompute();
//console.log("Creating an AKS Compute");
await createAksCompute();
}

main().catch((error: any) => {
console.error("An error occurred:", error);
console.log("error code: ", error.code);
console.log("error message: ", error.message);
console.log("error stack: ", error.stack);
process.exit(1);
});
57 changes: 57 additions & 0 deletions sdk/typescript/src/resources/compute/computeList.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

/**
* @summary Gets computes in specified workspace.
*/
import { client, getEnvironmentVariable } from "../../utils";

// Load the .env file if it exists
import * as dotenv from "dotenv";
dotenv.config();

/**
* This sample demonstrates how to Gets computes in specified workspace.
*
* @summary Gets computes in specified workspace.
* x-ms-original-file: specification/machinelearningservices/resource-manager/Microsoft.MachineLearningServices/stable/2022-10-01/examples/Compute/list.json
*/
async function getComputes() {
// const subscriptionId = getEnvironmentVariable("SUBSCRIPTION_ID");
const resourceGroupName = getEnvironmentVariable("RESOURCEGROUP_NAME");
const workspaceName = getEnvironmentVariable("WORKSPACE_NAME");

for await (let computeItem of client.computeOperations.list(
resourceGroupName,
workspaceName
)){
console.log(computeItem);
}
const resArray = new Array();
for await (let item of client.computeOperations.list(
resourceGroupName,
workspaceName
)) {
resArray.push(item);
}
console.log(resArray);
}

// getComputes().catch(console.error);

export async function main(): Promise<void> {
// This sample uses DefaultAzureCredential, which supports a number of authentication mechanisms.
// See https://docs.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest for more information
// about DefaultAzureCredential and the other credentials that are available for use.
console.log("Listing the Compute");
await getComputes();
}

main().catch((error) => {
console.error("An error occurred:", error);
console.log("error code: ", error.code);
console.log("error message: ", error.message);
console.log("error stack: ", error.stack);
process.exit(1);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

/**
* @summary Lists all the available machine learning workspaces under the specified subscription.
*/
import { client, getEnvironmentVariable } from "../../utils";

/**
* This sample demonstrates how to Lists all the available machine learning workspaces under the specified subscription.
*
* @summary Lists all the available machine learning workspaces under the specified subscription.
* x-ms-original-file: specification/machinelearningservices/resource-manager/Microsoft.MachineLearningServices/stable/2022-10-01/examples/Workspace/listBySubscription.json
*/
async function getWorkspacesBySubscription() {
const resArray = new Array();
for await (let item of client.workspaces.listBySubscription()) {
resArray.push(item);
}
console.log(resArray);
}

// getWorkspacesBySubscription().catch(console.error);

export async function main(): Promise<void> {
// This sample uses DefaultAzureCredential, which supports a number of authentication mechanisms.
// See https://docs.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest for more information
// about DefaultAzureCredential and the other credentials that are available for use.
console.log("Listing the workspaces");
await getWorkspacesBySubscription();
}

main().catch((error) => {
console.error("An error occurred:", error);
console.log("error code: ", error.code);
console.log("error message: ", error.message);
console.log("error stack: ", error.stack);
process.exit(1);
});
Loading