diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/README.md b/sdk/resourcemanager/Azure.ResourceManager.Core/README.md index d3ec87665ccd..e53c85cca7ec 100644 --- a/sdk/resourcemanager/Azure.ResourceManager.Core/README.md +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/README.md @@ -1,6 +1,11 @@ # Azure ResourceManager Core client library for .NET -This package follows the [new Azure SDK guidelines](https://azure.github.io/azure-sdk/general_introduction.html) which provide a number of core capabilities that are shared amongst all Azure SDKs, including the intuitive Azure Identity library, an HTTP Pipeline with custom policies, error-handling, distributed tracing, and much more. +This package follows the [new Azure SDK guidelines](https://azure.github.io/azure-sdk/general_introduction.html), which provide core capabilities that are shared amongst all Azure SDKs, including: + +- The intuitive Azure Identity library. +- An HTTP pipeline with custom policies. +- Error handling. +- Distributed tracing. ## Getting started @@ -13,47 +18,140 @@ Install-Package Azure.ResourceManager.Core -Version 1.0.0-beta.1 ``` ### Prerequisites +Set up a way to authenticate to Azure with Azure Identity. + +Some options are: +- Through the [Azure CLI Login](https://docs.microsoft.com/cli/azure/authenticate-azure-cli). +- Via [Visual Studio](https://docs.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#authenticating-via-visual-studio). +- Setting [Environment Variables]<--(docs/AuthUsingEnvironmentVariables.md)-->. -* You must have an [Azure subscription](https://azure.microsoft.com/free/) +More information and different authentication approaches using Azure Identity can be found in [this document](https://docs.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet). ### Authenticate the Client -To create an authenticated client and start interacting with Azure resources, please see the [quickstart guide here](https://github.com/Azure/azure-sdk-for-net/blob/master/doc/mgmt_preview_quickstart.md) +The default option to create an authenticated client is to use `DefaultAzureCredential`. Since all management APIs go through the same endpoint, in order to interact with resources, only one top-level `ArmClient` has to be created. + +To authenticate to Azure and create an `ArmClient`, do the following: + +```csharp +using Azure.Identity; +using Azure.ResourceManager.Core; +using System; + +// code omitted for brevity + +var armClient = new ArmClient(new DefaultAzureCredential()); +``` + +Additional documentation for the `Azure.Identity.DefaultAzureCredential` class can be found in [this document](https://docs.microsoft.com/dotnet/api/azure.identity.defaultazurecredential). ## Key concepts +### Understanding Azure Resource Hierarchy + +To reduce both the number of clients needed to perform common tasks and the amount of redundant parameters that each of those clients take, we have introduced an object hierarchy in the SDK that mimics the object hierarchy in Azure. Each resource client in the SDK has methods to access the resource clients of its children that is already scoped to the proper subscription and resource group. + +To accomplish this, we're introducing 4 standard types for all resources in Azure: + +#### **[Resource]Data** +This represents the data that makes up a given resource. Typically, this is the response data from a service call such as HTTP GET and provides details about the underlying resource. Previously, this was represented by a **Model** class. + +#### **[Resource]Operations** + +This represents a service client that's scoped to a particular resource. You can directly execute all operations on that client without needing to pass in scope parameters such as subscription ID or resource name. -Key concepts of the Azure .NET SDK can be found [here](https://azure.github.io/azure-sdk/dotnet_introduction.html) +#### **[Resource]Container** -## Documentation +This represents the operations you can perform on a collection of resources belonging to a specific parent resource. +This mainly consists of List or Create operations. For most things, the parent will be a **ResourceGroup**. However, each parent / child relationship is represented this way. For example, a **Subnet** is a child of a **VirtualNetwork** and a **ResourceGroup** is a child of a **Subscription**. -Documentation is available to help you learn how to use this package +#### **[Resource]** -- [Quickstart](https://github.com/Azure/azure-sdk-for-net/blob/master/doc/mgmt_preview_quickstart.md) -- [API References](https://docs.microsoft.com/dotnet/api/?view=azure-dotnet) -- [Authentication](https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/identity/Azure.Identity/README.md) +This represents a full resource object which contains a **Data** property exposing the details as a **[Resource]Data** type. +It also has access to all of the operations and like the **[Resource]Operations** object is already scoped +to a specific resource in Azure. ## Examples +### Add a tag to a virtual machine +Imagine that our company requires all virtual machines to be tagged with the owner. We're tasked with writing a program to add the tag to any missing virtual machines in a given resource group. + + ```csharp +// First we construct our armClient +var armClient = new ArmClient(new DefaultAzureCredential()); + +// Next we get a resource group object +// ResourceGroup is a [Resource] object from above +ResourceGroup resourceGroup = await armClient.DefaultSubscription.GetResourceGroups().GetAsync("myRgName"); + +// Next we get the container for the virtual machines +// vmContainer is a [Resource]Container object from above +VirtualMachineContainer vmContainer = resourceGroup.GetVirtualMachines(); + +// Next we loop over all vms in the container +// Each vm is a [Resource] object from above +await foreach(VirtualMachine vm in vmContainer.ListAsync()) +{ + // We access the [Resource]Data properties from vm.Data + if(!vm.Data.Tags.ContainsKey("owner")) + { + // We can also access all [Resource]Operations from vm since it is already scoped for us + await vm.StartAddTag("owner", GetOwner()).WaitForCompletionAsync(); + } +} + ``` + +### Create a resource group +```csharp +// First, initialize the ArmClient and get the default subscription +var armClient = new ArmClient(new DefaultAzureCredential()); +Subscription subscription = armClient.DefaultSubscription; +// Now we get a ResourceGroup container for that subscription +ResourceGroupContainer rgContainer = subscription.GetResourceGroups(); + +// With the container, we can create a new resource group with an specific name +string rgName = "myRgName"; +ResourceGroup resourceGroup = await rgContainer.CreateAsync(rgName); +``` -Code samples for using the management library for .NET can be found in the following locations -- [.NET Management Library Code Samples](https://docs.microsoft.com/samples/browse/?branch=master&languages=csharp&term=managing%20using%20Azure%20.NET%20SDK) +### List all resource groups +```csharp +// First, initialize the ArmClient and get the default subscription +var armClient = new ArmClient(new DefaultAzureCredential()); +Subscription subscription = armClient.DefaultSubscription; + +// Now we get a ResourceGroup container for that subscription +ResourceGroupContainer rgContainer = subscription.GetResourceGroups(); + +// With ListAsync(), we can get a list of the resources in the container +AsyncPageable response = rgContainer.ListAsync(); +await foreach (ResourceGroup rg in response) +{ + Console.WriteLine(rg.Data.Name); +} +``` + +For more detailed examples, take a look at [samples]<--(samples/)--> we have available. ## Troubleshooting -- File an issue via [Github - Issues](https://github.com/Azure/azure-sdk-for-net/issues) -- Check [previous +- If you find a bug or have a suggestion, file an issue via [GitHub issues](https://github.com/Azure/azure-sdk-for-net/issues) and make sure you add the "Preview" label to the issue. +- If you need help, check [previous questions](https://stackoverflow.com/questions/tagged/azure+.net) - or ask new ones on Stack Overflow using azure and .net tags. - - + or ask new ones on StackOverflow using azure and .NET tags. +- If having trouble with authentication, go to [DefaultAzureCredential documentation](https://docs.microsoft.com/dotnet/api/azure.identity.defaultazurecredential?view=azure-dotnet). ## Next steps +### More sample code + +- [Managing Resource Groups]<--(samples/ManagingResourceGroups.md)--> +- [Creating a Virtual Network]<--(samples/CreatingAVirtualNetwork.md)--> +- [.NET Management Library Code Samples](https://docs.microsoft.com/samples/browse/?branch=master&languages=csharp&term=managing%20using%20Azure%20.NET%20SDK) -For more information on Azure SDK, please refer to [this website](https://azure.github.io/azure-sdk/) +### Additional Documentation +For more information on Azure SDK, please refer to [this website](https://azure.github.io/azure-sdk/). ## Contributing -For details on contributing to this repository, see the contributing -guide. +For details on contributing to this repository, see the [contributing +guide]<--(docs/CONTRIBUTING.md)-->. This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring @@ -69,9 +167,3 @@ our CLA. This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact with any additional questions or comments. - - -[style-guide-msft]: https://docs.microsoft.com/style-guide/capitalization -[style-guide-cloud]: https://aka.ms/azsdk/cloud-style-guide - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-net%2Fsdk%2Ftemplate%2FAzure.Template%2FREADME.png) diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/docs/AuthUsingEnvironmentVariables.md b/sdk/resourcemanager/Azure.ResourceManager.Core/docs/AuthUsingEnvironmentVariables.md new file mode 100644 index 000000000000..f4b0fe2bd550 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/docs/AuthUsingEnvironmentVariables.md @@ -0,0 +1,54 @@ +Authenticate to Azure using environment variables +------------- + +You'll need the following values to authenticate to Azure: + +- **Subscription ID** +- **Client ID** +- **Client Secret** +- **Tenant ID** + +## Obtaining the values + +These values can be obtained from the [portal](https://portal.azure.com/) with the following instructions: + +### Get Subscription ID + +1. Log in to your Azure account. +2. Select **Subscriptions** in the left sidebar. +3. Select the subscription to be used. +4. Select **Overview**. +5. Copy the Subscription ID. + +### Get Client ID / Client Secret / Tenant ID + +For information on how to get Client ID, Client Secret, and Tenant ID, see [this +document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal). + +## Setting Environment Variables + +After you obtain the values, set the following environment variables: + +- `AZURE_CLIENT_ID` +- `AZURE_CLIENT_SECRET` +- `AZURE_TENANT_ID` +- `AZURE_SUBSCRIPTION_ID` + +To set the environment variables on your development system: + +### Windows: + +_(Note: Administrator access is required)_ + +1. Open the **Control Panel**. +2. Select **System Security** > **System**. +3. Select **Advanced system settings** on the left. +4. Inside the **System Properties** window, select the **Environment Variables** button. +5. Select the property you'd like to change, then select the **Edit** button. If the property name isn't listed, select the **New** button. + +### Linux-based OS: + + export AZURE_CLIENT_ID="__CLIENT_ID__" + export AZURE_CLIENT_SECRET="__CLIENT_SECRET__" + export AZURE_TENANT_ID="__TENANT_ID__" + export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__" diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/docs/CONTRIBUTING.md b/sdk/resourcemanager/Azure.ResourceManager.Core/docs/CONTRIBUTING.md new file mode 100644 index 000000000000..27ab7576bba7 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/docs/CONTRIBUTING.md @@ -0,0 +1,78 @@ +# Contributing + +Thank you for your interest in contributing to the Azure App Configuration client library. As an open source effort, we're excited to welcome feedback and contributions from the community. A great first step in sharing your thoughts and understanding where help is needed would be to take a look at the [open issues][open_issues]. + +Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit [cla.microsoft.com][cla]. + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +## Code of conduct + +This project has adopted the [Microsoft Open Source Code of Conduct][code_of_conduct]. For more information see the [Code of Conduct FAQ][code_of_conduct_faq] or contact [opencode@microsoft.com][email_opencode] with any additional questions or comments. + +## Getting started + +Before working on a contribution, it would be beneficial to familiarize yourself with the process and guidelines used for the Azure SDKs so that your submission is consistent with the project standards and is ready to be accepted with fewer changes requested. In particular, it is recommended to review: + + - [Azure SDK README][sdk_readme], to learn more about the overall project and processes used. + - [Azure SDK Design Guidelines][sdk_design_guidelines], to understand the general guidelines for the Azure SDK across all languages and platforms. + - [Azure SDK Contributing Guide][sdk_contributing], for information about how to onboard and contribute to the overall Azure SDK ecosystem. + +## Azure SDK Design Guidelines for .NET + +These libraries follow the [Azure SDK Design Guidelines for .NET][sdk_design_guidelines_dotnet] and share a number of core features such as HTTP retries, logging, transport protocols, authentication protocols, etc., so that once you learn how to use these features in one client library, you will know how to use them in other client libraries. You can learn about these shared features in the [Azure.Core README][sdk_dotnet_code_readme]. + +## Public API changes + +To update [`Azure.Data.AppConfiguration.netstandard2.0.cs`][azconfig_api] after making changes to the public API, execute [`./eng/scripts/Export-API.ps1`][azconfig_export_api]. + +## Testing + +### Frameworks + +We use [NUnit 3][nunit] as our testing framework. + +[Azure.Core.TestFramework's testing framework][core_tests] provides a set of reusable primitives that simplify writing tests for new Azure SDK libraries. + +### Sync/Async testing + +We expose all of our APIs with both sync and async variants. To avoid writing each of our tests twice, we automatically rewrite our async API calls into their sync equivalents. Simply write your tests using only async APIs and call `InstrumentClient` on any of our client objects. The test framework will wrap the client with a proxy that forwards everything to the sync overloads. Please note that a number of our helpers will automatically instrument clients they provide you. Visual Studio's test runner will show `*TestClass(True)` for the async variants and `*TestClass(False)` for the sync variants. + +### Recorded tests + +Our testing framework supports recording service requests made during a unit test so they can be replayed later. You can set the `AZURE_TEST_MODE` environment variable to `Playback` to run previously recorded tests, `Record` to record or re-record tests, and `Live` to run tests against the live service. + +Properly supporting recorded tests does require a few extra considerations. All random values should be obtained via `this.Recording.Random` since we use the same seed on test playback to ensure our client code generates the same "random" values each time. You can't share any state between tests or rely on ordering because you don't know the order they'll be recorded or replayed. Any sensitive values are redacted via the [`ConfigurationRecordedTestSanitizer`][tests_sanitized]. + +### Running tests + +The easiest way to run the tests is via Visual Studio's unit test runner. + +You can also run tests via the command line using `dotnet test`, but that will run tests for all supported platforms simultaneously and intermingle their output. You can run the tests for just one platform with `dotnet test -f netcoreapp2.1` or `dotnet test -f net461`. + +The recorded tests are run automatically on every pull request. Live tests are run nightly. Contributors with write access can ask Azure DevOps to run the live tests against a pull request by commenting `/azp run net - appconfiguration - tests` in the PR. + +### Samples + +Our samples are structured as unit tests so we can easily verify they're up to date and working correctly. These tests aren't recorded and make minimal use of test infrastructure to keep them easy to read. + +## Development history + +For additional insight and context, the development, release, and issue history for the Azure Event Hubs client library is available in read-only form, in its previous location, the [Azure App Configuration .NET repository](https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/appconfiguration). + + +[azconfig_root]: ../../sdk/appconfiguration +[azconfig_api]: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/appconfiguration/Azure.Data.AppConfiguration/api/Azure.Data.AppConfiguration.netstandard2.0.cs +[azconfig_export_api]: https://github.com/Azure/azure-sdk-for-net/blob/master/eng/scripts/Export-API.ps1 +[cla]: https://cla.microsoft.com +[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ +[code_of_conduct_faq]: https://opensource.microsoft.com/codeofconduct/faq/ +[core_tests]: https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/core/Azure.Core.TestFramework +[nunit]: https://github.com/nunit/docs/wiki +[open_issues]: https://github.com/Azure/azure-sdk-for-net/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+label%3AClient+label%3AAzConfig +[sdk_readme]: https://github.com/Azure/azure-sdk +[sdk_contributing]: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/appconfiguration/CONTRIBUTING.md +[sdk_design_guidelines]: https://azure.github.io/azure-sdk/general_introduction.html +[sdk_design_guidelines_dotnet]: https://azure.github.io/azure-sdk/dotnet_introduction.html +[sdk_dotnet_code_readme]: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/core/Azure.Core/README.md +[email_opencode]: mailto:opencode@microsoft.com \ No newline at end of file diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/samples/README.md b/sdk/resourcemanager/Azure.ResourceManager.Core/samples/README.md new file mode 100644 index 000000000000..419fc16e7a9b --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/samples/README.md @@ -0,0 +1,17 @@ +--- +page_type: sample +languages: +- csharp +products: +- azure +- azure-resource-manager +name: Azure.ResourceManager.Core samples for .NET +description: Samples for the Azure.ResourceManager.Core client library +--- + +# Azure.ResourceManager.Core Samples + +- [Hello World - Getting a subscription]<--(Sample1_HelloWorld.md)--> +- [Hello World - Getting a subscription async]<--(Sample1_HelloWorldAsync.md)--> +- [Managing Resource Groups]<--(Sample2_ManagingResourceGroups.md)--> +- [Creating a virtual network]<--(Sample3_CreatingAVirtualNetwork.md)--> diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/samples/Sample1_HelloWorld.md b/sdk/resourcemanager/Azure.ResourceManager.Core/samples/Sample1_HelloWorld.md new file mode 100644 index 000000000000..9aebe8f93851 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/samples/Sample1_HelloWorld.md @@ -0,0 +1,29 @@ +# Example: Getting a subscription + +>Note: Before getting started with the samples, make sure to go trough the [prerequisites]<--(./README.md#Prerequisites)-->. + +The following code shows how to get the default subscription: + +```csharp +var armClient = new ArmClient(new DefaultAzureCredential()); +Subscription subscription = armClient.DefaultSubscription; +Console.WriteLine(subscription.Id); +``` + +It's possible to get a specific subscription as follows: + +```csharp +string subscriptionId = "db1ab6f0-4769-4b27-930e-01e2ef9c123c"; +var armClient = new ArmClient(new DefaultAzureCredential()); +Subscription subscription = armClient.GetSubscriptions().Get(subscriptionId); +Console.WriteLine("Got subscription: " + subscription.Data.DisplayName); +``` + +From here, it is possible to get the resource groups from the retrieved subscription: + +```csharp +ResourceGroupContainer rgContainer = subscription.GetResourceGroups(); +``` + +## Next stepts +Take a look at the [Managing Resource Groups]<--(Sample2_ManagingResourceGroups.md)--> samples. diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/samples/Sample1_HelloWorldAsync.md b/sdk/resourcemanager/Azure.ResourceManager.Core/samples/Sample1_HelloWorldAsync.md new file mode 100644 index 000000000000..b9a13670f81a --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/samples/Sample1_HelloWorldAsync.md @@ -0,0 +1,31 @@ +# Example: Getting a subscription + +>Note: Before getting started with the samples, go through the [prerequisites]<--(./README.md#Prerequisites)-->. + +The following code shows how to get the default subscription: + +```csharp +var armClient = new ArmClient(new DefaultAzureCredential()); +Subscription subscription = armClient.DefaultSubscription; +Console.WriteLine(subscription.Id); +``` + +It's possible to get a specific subscription as follows: + +```csharp +string subscriptionId = "db1ab6f0-4769-4b27-930e-01e2ef9c123c"; +var armClient = new ArmClient(new DefaultAzureCredential()); +Subscription subscription = armClient.GetSubscriptions().GetAsync(subscriptionId); +Console.WriteLine(subscription.Id); +``` + +With the `Async` suffix on methods that perform API calls, it's possible to differentiate the asynchronous and synchronous variants of any method. + +From here, it is possible to get the resource groups from the retrieved subscription: + +```csharp +ResourceGroupContainer rgContainer = subscription.GetResourceGroups(); +``` + +## Next stepts +Take a look at the [Managing Resource Groups]<--(Sample2_ManagingResourceGroups.md)--> samples. diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/samples/Sample2_ManagingResourceGroups.md b/sdk/resourcemanager/Azure.ResourceManager.Core/samples/Sample2_ManagingResourceGroups.md new file mode 100644 index 000000000000..1f5122b1a421 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/samples/Sample2_ManagingResourceGroups.md @@ -0,0 +1,69 @@ +Example: Managing Resource Groups +-------------------------------------- + +When you first create your ARM client, choose the subscription you're going to work in. There's a convenient `DefaultSubscription` property that returns the default subscription configured for your user: + +```csharp +var armClient = new ArmClient(new DefaultAzureCredential()); +Subscription subscription = armClient.DefaultSubscription; +``` + +This is a scoped operations object, and any operations you perform will be done under that subscription. From this object, you have access to all children via container objects. Or you can access individual children by ID. + +```csharp +var armClient = new ArmClient(new DefaultAzureCredential()); +Subscription subscription = armClient.DefaultSubscription; +ResourceGroupContainer rgContainer = subscription.GetResourceGroups(); + +// code omitted for brevity + +string rgName = "myRgName"; +ResourceGroup resourceGroup = await rgContainer.GetAsync(rgName); +``` + +Using the container object, we can perform collection-level operations such as list all of the resource groups or create new ones under our subscription. + +***Create a resource group*** + +```csharp +var armClient = new ArmClient(new DefaultAzureCredential()); +Subscription subscription = armClient.DefaultSubscription; +ResourceGroupContainer rgContainer = subscription.GetResourceGroups(); + +LocationData location = LocationData.WestUS2; +string rgName = "myRgName"; +ResourceGroup resourceGroup = await rgContainer.Construct(location).CreateAsync(rgName); +``` + +***List all resource groups*** + +```csharp +var armClient = new ArmClient(new DefaultAzureCredential()); +Subscription subscription = armClient.DefaultSubscription; +ResourceGroupContainer rgContainer = subscription.GetResourceGroups(); +AsyncPageable response = rgContainer.ListAsync(); +await foreach (ResourceGroup rg in response) +{ + Console.WriteLine(rg.Data.Name); +} +``` + +Using the operation object we can perform entity-level operations, such as updating or deleting existing resource groups. + +***Update a resource group*** + +```csharp +var armClient = new ArmClient(new DefaultAzureCredential()); +Subscription subscription = armClient.DefaultSubscription; +ResourceGroup resourceGroup = await subscription.GetResourceGroups().GetAsync(rgName); +resourceGroup = await rgOperation.StartAddTag("key", "value").WaitForCompletionAsync(); +``` + +***Delete a resource group*** + +```csharp +var armClient = new ArmClient(new DefaultAzureCredential()); +Subscription subscription = armClient.DefaultSubscription; +ResourceGroup resourceGroup = await subscription.GetResourceGroups().GetAsync(rgName); +await resourceGroup.DeleteAsync(); +``` diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/samples/Sample3_CreatingAVirtualNetwork.md b/sdk/resourcemanager/Azure.ResourceManager.Core/samples/Sample3_CreatingAVirtualNetwork.md new file mode 100644 index 000000000000..6ca85153b819 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/samples/Sample3_CreatingAVirtualNetwork.md @@ -0,0 +1,30 @@ +Example: Creating a Virtual Network +-------------------------------------- + +In this example, we'll create a virtual network. Since the SDK follows the resource hierarchy in Azure, we'll need to do this inside of a resource group. Start by creating a new resource group, like we did above: + +```csharp +var armClient = new ArmClient(new DefaultAzureCredential()); +ResourceGroupContainer rgContainer = armClient.DefaultSubscription.GetResourceGroups(); +ResourceGroup resourceGroup = await rgContainer.Construct(LocationData.WestUS2).CreateAsync(rg); +``` + +Now that we have a resource group, we'll create our virtual network. To do this, we will use a helper method on the container object called `Construct`. The helper method allows us to create the request object and then send that to the `Create` method. + +```csharp +VirtualNetworkContainer vnetContainer = resourceGroup.GetVirtualNetworks(); +VirtualNetwork virtualNetwork = await vnetContainer + .Construct("10.0.0.0/16", location) + .CreateAsync("myVnetName"); +``` + +Now that we have a virtual network, we must create at least one subnet in order to add any virtual machines. +Following the hierarchy in Azure, subnets belong to a virtual network, so that's where we'll get our `SubnetContainer` instance. After that, we'll again use the `Construct` helper method to create our subnet. + +```csharp +string subnetName = "mySubnetName"; +SubnetContainer subnetContainer = virtualNetwork.GetSubnets(); +Subnet subnet = await subnetContainer + .Construct("10.0.0.0/24") + .CreateAsync(subnetName); +```