├── .gitignore
├── CODE_OF_CONDUCT.md
├── LICENSE
├── README.md
├── SECURITY.md
└── samples
├── Samples.sln
├── appconfiguration
└── create-app-configuration
│ ├── CreateAppConfigurationSample.csproj
│ ├── Program.cs
│ └── README.md
├── communication
└── manage-communication
│ ├── ManageCommunication.csproj
│ ├── Program.cs
│ └── README.md
├── compute
├── create-virtual-machine
│ ├── CreateVMSample.csproj
│ ├── Program.cs
│ └── README.md
├── create-virtual-machines-in-parallel
│ ├── CreateVirtualMachinesInParallel.csproj
│ ├── Program.cs
│ └── README.md
├── manage-virtual-machine-extension
│ ├── ManageVMExtension.csproj
│ ├── Program.cs
│ └── README.md
└── manage-virtual-machine
│ ├── ManageVMSample.csproj
│ ├── Program.cs
│ └── README.md
├── eventhub
├── manage-event-hub-events
│ ├── ManageEventHubEvents.csproj
│ ├── Program.cs
│ └── README.md
├── manage-event-hub-geo-disaster-recovery
│ ├── ManageEventHubGeoDisasterRecovery.csproj
│ ├── Program.cs
│ └── README.md
└── manage-event-hub
│ ├── ManageEventHub.csproj
│ ├── Program.cs
│ └── README.md
├── keyvault
└── manage-key-vault
│ ├── ManageKeyVault.csproj
│ ├── Program.cs
│ └── README.md
├── network
├── manage-ip-address
│ ├── ManageIPAddress.csproj
│ ├── Program.cs
│ └── README.md
└── manage-virtual-network
│ ├── ManageVirtualNetwork.csproj
│ ├── Program.cs
│ └── README.md
├── resources
├── deploy-using-arm-template
│ ├── Asset
│ │ ├── ArmTemplate.json
│ │ └── ArmTemplateVM.json
│ ├── DeployUsingARMTemplate.csproj
│ ├── Program.cs
│ └── README.md
├── manage-resource-group
│ ├── ManageResourceGroup.csproj
│ ├── Program.cs
│ └── README.md
└── manage-resource
│ ├── ManageResource.csproj
│ ├── Program.cs
│ └── README.md
├── storage
└── create-storage-account
│ ├── CreateStorageSample.csproj
│ └── Program.cs
└── utilities
├── ResourceNamer.cs
├── Utilities.cs
└── Utilities.csproj
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 | [Ll]ogs/
33 |
34 | # Visual Studio 2015/2017 cache/options directory
35 | .vs/
36 | # Uncomment if you have tasks that create the project's static files in wwwroot
37 | #wwwroot/
38 |
39 | # Visual Studio 2017 auto generated files
40 | Generated\ Files/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUnit
47 | *.VisualState.xml
48 | TestResult.xml
49 | nunit-*.xml
50 |
51 | # Build Results of an ATL Project
52 | [Dd]ebugPS/
53 | [Rr]eleasePS/
54 | dlldata.c
55 |
56 | # Benchmark Results
57 | BenchmarkDotNet.Artifacts/
58 |
59 | # .NET Core
60 | project.lock.json
61 | project.fragment.lock.json
62 | artifacts/
63 |
64 | # StyleCop
65 | StyleCopReport.xml
66 |
67 | # Files built by Visual Studio
68 | *_i.c
69 | *_p.c
70 | *_h.h
71 | *.ilk
72 | *.meta
73 | *.obj
74 | *.iobj
75 | *.pch
76 | *.pdb
77 | *.ipdb
78 | *.pgc
79 | *.pgd
80 | *.rsp
81 | *.sbr
82 | *.tlb
83 | *.tli
84 | *.tlh
85 | *.tmp
86 | *.tmp_proj
87 | *_wpftmp.csproj
88 | *.log
89 | *.vspscc
90 | *.vssscc
91 | .builds
92 | *.pidb
93 | *.svclog
94 | *.scc
95 |
96 | # Chutzpah Test files
97 | _Chutzpah*
98 |
99 | # Visual C++ cache files
100 | ipch/
101 | *.aps
102 | *.ncb
103 | *.opendb
104 | *.opensdf
105 | *.sdf
106 | *.cachefile
107 | *.VC.db
108 | *.VC.VC.opendb
109 |
110 | # Visual Studio profiler
111 | *.psess
112 | *.vsp
113 | *.vspx
114 | *.sap
115 |
116 | # Visual Studio Trace Files
117 | *.e2e
118 |
119 | # TFS 2012 Local Workspace
120 | $tf/
121 |
122 | # Guidance Automation Toolkit
123 | *.gpState
124 |
125 | # ReSharper is a .NET coding add-in
126 | _ReSharper*/
127 | *.[Rr]e[Ss]harper
128 | *.DotSettings.user
129 |
130 | # TeamCity is a build add-in
131 | _TeamCity*
132 |
133 | # DotCover is a Code Coverage Tool
134 | *.dotCover
135 |
136 | # AxoCover is a Code Coverage Tool
137 | .axoCover/*
138 | !.axoCover/settings.json
139 |
140 | # Visual Studio code coverage results
141 | *.coverage
142 | *.coveragexml
143 |
144 | # NCrunch
145 | _NCrunch_*
146 | .*crunch*.local.xml
147 | nCrunchTemp_*
148 |
149 | # MightyMoose
150 | *.mm.*
151 | AutoTest.Net/
152 |
153 | # Web workbench (sass)
154 | .sass-cache/
155 |
156 | # Installshield output folder
157 | [Ee]xpress/
158 |
159 | # DocProject is a documentation generator add-in
160 | DocProject/buildhelp/
161 | DocProject/Help/*.HxT
162 | DocProject/Help/*.HxC
163 | DocProject/Help/*.hhc
164 | DocProject/Help/*.hhk
165 | DocProject/Help/*.hhp
166 | DocProject/Help/Html2
167 | DocProject/Help/html
168 |
169 | # Click-Once directory
170 | publish/
171 |
172 | # Publish Web Output
173 | *.[Pp]ublish.xml
174 | *.azurePubxml
175 | # Note: Comment the next line if you want to checkin your web deploy settings,
176 | # but database connection strings (with potential passwords) will be unencrypted
177 | *.pubxml
178 | *.publishproj
179 |
180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
181 | # checkin your Azure Web App publish settings, but sensitive information contained
182 | # in these scripts will be unencrypted
183 | PublishScripts/
184 |
185 | # NuGet Packages
186 | *.nupkg
187 | # NuGet Symbol Packages
188 | *.snupkg
189 | # The packages folder can be ignored because of Package Restore
190 | **/[Pp]ackages/*
191 | # except build/, which is used as an MSBuild target.
192 | !**/[Pp]ackages/build/
193 | # Uncomment if necessary however generally it will be regenerated when needed
194 | #!**/[Pp]ackages/repositories.config
195 | # NuGet v3's project.json files produces more ignorable files
196 | *.nuget.props
197 | *.nuget.targets
198 |
199 | # Microsoft Azure Build Output
200 | csx/
201 | *.build.csdef
202 |
203 | # Microsoft Azure Emulator
204 | ecf/
205 | rcf/
206 |
207 | # Windows Store app package directories and files
208 | AppPackages/
209 | BundleArtifacts/
210 | Package.StoreAssociation.xml
211 | _pkginfo.txt
212 | *.appx
213 | *.appxbundle
214 | *.appxupload
215 |
216 | # Visual Studio cache files
217 | # files ending in .cache can be ignored
218 | *.[Cc]ache
219 | # but keep track of directories ending in .cache
220 | !?*.[Cc]ache/
221 |
222 | # Others
223 | ClientBin/
224 | ~$*
225 | *~
226 | *.dbmdl
227 | *.dbproj.schemaview
228 | *.jfm
229 | *.pfx
230 | *.publishsettings
231 | orleans.codegen.cs
232 |
233 | # Including strong name files can present a security risk
234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
235 | #*.snk
236 |
237 | # Since there are multiple workflows, uncomment next line to ignore bower_components
238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
239 | #bower_components/
240 |
241 | # RIA/Silverlight projects
242 | Generated_Code/
243 |
244 | # Backup & report files from converting an old project file
245 | # to a newer Visual Studio version. Backup files are not needed,
246 | # because we have git ;-)
247 | _UpgradeReport_Files/
248 | Backup*/
249 | UpgradeLog*.XML
250 | UpgradeLog*.htm
251 | ServiceFabricBackup/
252 | *.rptproj.bak
253 |
254 | # SQL Server files
255 | *.mdf
256 | *.ldf
257 | *.ndf
258 |
259 | # Business Intelligence projects
260 | *.rdl.data
261 | *.bim.layout
262 | *.bim_*.settings
263 | *.rptproj.rsuser
264 | *- [Bb]ackup.rdl
265 | *- [Bb]ackup ([0-9]).rdl
266 | *- [Bb]ackup ([0-9][0-9]).rdl
267 |
268 | # Microsoft Fakes
269 | FakesAssemblies/
270 |
271 | # GhostDoc plugin setting file
272 | *.GhostDoc.xml
273 |
274 | # Node.js Tools for Visual Studio
275 | .ntvs_analysis.dat
276 | node_modules/
277 |
278 | # Visual Studio 6 build log
279 | *.plg
280 |
281 | # Visual Studio 6 workspace options file
282 | *.opt
283 |
284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
285 | *.vbw
286 |
287 | # Visual Studio LightSwitch build output
288 | **/*.HTMLClient/GeneratedArtifacts
289 | **/*.DesktopClient/GeneratedArtifacts
290 | **/*.DesktopClient/ModelManifest.xml
291 | **/*.Server/GeneratedArtifacts
292 | **/*.Server/ModelManifest.xml
293 | _Pvt_Extensions
294 |
295 | # Paket dependency manager
296 | .paket/paket.exe
297 | paket-files/
298 |
299 | # FAKE - F# Make
300 | .fake/
301 |
302 | # CodeRush personal settings
303 | .cr/personal
304 |
305 | # Python Tools for Visual Studio (PTVS)
306 | __pycache__/
307 | *.pyc
308 |
309 | # Cake - Uncomment if you are using it
310 | # tools/**
311 | # !tools/packages.config
312 |
313 | # Tabs Studio
314 | *.tss
315 |
316 | # Telerik's JustMock configuration file
317 | *.jmconfig
318 |
319 | # BizTalk build output
320 | *.btp.cs
321 | *.btm.cs
322 | *.odx.cs
323 | *.xsd.cs
324 |
325 | # OpenCover UI analysis results
326 | OpenCover/
327 |
328 | # Azure Stream Analytics local run output
329 | ASALocalRun/
330 |
331 | # MSBuild Binary and Structured Log
332 | *.binlog
333 |
334 | # NVidia Nsight GPU debugger configuration file
335 | *.nvuser
336 |
337 | # MFractors (Xamarin productivity tool) working folder
338 | .mfractor/
339 |
340 | # Local History for Visual Studio
341 | .localhistory/
342 |
343 | # BeatPulse healthcheck temp database
344 | healthchecksdb
345 |
346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
347 | MigrationBackup/
348 |
349 | # Ionide (cross platform F# VS Code tools) working folder
350 | .ionide/
351 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Microsoft Open Source Code of Conduct
2 |
3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
4 |
5 | Resources:
6 |
7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Microsoft Corporation.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Code Samples of Azure .NET SDK Management Libraries
2 |
3 | This repo contains code samples that demonstrate the usage of management client libraries of Azure .NET SDK.
4 |
5 | To find the code samples for a particular service you are using, please click on the folder that you're
6 | interested in. Each folder name is based on the Azure service, eg. Compute / Network / Storage
7 |
8 | ### Samples:
9 |
10 | - [App Configuration](https://github.com/Azure-Samples/azure-samples-net-management/tree/master/samples/appconfiguration)
11 | - [Communication](https://github.com/Azure-Samples/azure-samples-net-management/tree/master/samples/communication)
12 | - [Compute](https://github.com/Azure-Samples/azure-samples-net-management/tree/master/samples/compute)
13 | - [Event Hub](https://github.com/Azure-Samples/azure-samples-net-management/tree/master/samples/eventhub)
14 | - [Key Vault](https://github.com/Azure-Samples/azure-samples-net-management/tree/master/samples/keyvault/manage-key-vault)
15 | - [Network](https://github.com/Azure-Samples/azure-samples-net-management/tree/master/samples/network)
16 | - [Resources](https://github.com/Azure-Samples/azure-samples-net-management/tree/master/samples/resources)
17 | - [Storage](https://github.com/Azure-Samples/azure-samples-net-management/tree/master/samples/storage)
18 |
19 | ### Other
20 |
21 | - [Utilities](https://github.com/Azure-Samples/azure-samples-net-management/tree/master/samples/utilities)
22 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Security
4 |
5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/).
6 |
7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)), please report it to us as described below.
8 |
9 | ## Reporting Security Issues
10 |
11 | **Please do not report security vulnerabilities through public GitHub issues.**
12 |
13 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report).
14 |
15 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc).
16 |
17 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc).
18 |
19 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
20 |
21 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
22 | * Full paths of source file(s) related to the manifestation of the issue
23 | * The location of the affected source code (tag/branch/commit or direct URL)
24 | * Any special configuration required to reproduce the issue
25 | * Step-by-step instructions to reproduce the issue
26 | * Proof-of-concept or exploit code (if possible)
27 | * Impact of the issue, including how an attacker might exploit the issue
28 |
29 | This information will help us triage your report more quickly.
30 |
31 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs.
32 |
33 | ## Preferred Languages
34 |
35 | We prefer all communications to be in English.
36 |
37 | ## Policy
38 |
39 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd).
40 |
41 |
--------------------------------------------------------------------------------
/samples/appconfiguration/create-app-configuration/CreateAppConfigurationSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/samples/appconfiguration/create-app-configuration/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading.Tasks;
3 |
4 | using Azure.Identity;
5 | using Azure.ResourceManager;
6 | using Azure.ResourceManager.Resources;
7 | using Azure.ResourceManager.AppConfiguration;
8 | using Azure.ResourceManager.AppConfiguration.Models;
9 | using Samples.Utilities;
10 | using Azure.ResourceManager.Network.Models;
11 | using Azure.ResourceManager.Resources.Models;
12 | using Azure;
13 |
14 | namespace CreateAppConfigurationSample
15 | {
16 | public class Program
17 | {
18 | public static async Task Main(string[] args)
19 | {
20 | try
21 | {
22 | // Authenticate
23 | var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
24 | var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
25 | var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
26 | var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
27 | ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
28 | ArmClient client = new ArmClient(credential, subscription);
29 |
30 | await RunSample(client);
31 | }
32 | catch (Exception ex)
33 | {
34 | Utilities.Log(ex);
35 | }
36 | }
37 |
38 | public static async Task RunSample(ArmClient client)
39 | {
40 | string subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
41 | string appConfigName = Utilities.RandomResourceName("appcnfg", 20);
42 | string rgName = Utilities.RandomResourceName("rgNEMV", 24);
43 | string region = "eastus";
44 |
45 | ResourceGroupResource resourceGroup = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, rgName, new ResourceGroupData(region))).Value;
46 |
47 | // Create an App Configuration
48 | Utilities.Log("Creating an App Configuration...");
49 | var collection = resourceGroup.GetAppConfigurationStores();
50 | AppConfigurationStoreData configurationStoreData = new AppConfigurationStoreData(region, new AppConfigurationSku("Standard"))
51 | {
52 | PublicNetworkAccess = AppConfigurationPublicNetworkAccess.Disabled
53 | };
54 | AppConfigurationStoreResource configurationStore = (await collection.CreateOrUpdateAsync(WaitUntil.Completed, appConfigName, configurationStoreData)).Value;
55 |
56 | Utilities.Log("Created App Configuration");
57 | Utilities.PrintAppConfiguration(configurationStore);
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/samples/appconfiguration/create-app-configuration/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code samples will show you how to create an App Configuration using Azure SDK for .NET."
8 | urlFragment: appconfiguration-create-appconfiguration
9 | ---
10 | # Getting started - Creating App Configurations using Azure .NET SDK
11 |
12 | This code sample will show you how to create an App Configuration using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### EventHub
19 | * You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/#dotnet).
20 |
21 | ## Getting Started
22 |
23 | ### Prerequisites
24 |
25 | You will need the following values to authenticate to Azure
26 |
27 | - **Subscription ID**
28 | - **Client ID**
29 | - **Client Secret**
30 | - **Tenant ID**
31 |
32 | These values can be obtained from the portal, here's the instructions:
33 |
34 | ### Get Subscription ID
35 |
36 | 1. Login into your Azure account
37 | 2. Select Subscriptions in the left sidebar
38 | 3. Select whichever subscription is needed
39 | 4. Click on Overview
40 | 5. Copy the Subscription ID
41 |
42 | ### Get Client ID / Client Secret / Tenant ID
43 |
44 | For information on how to get Client ID, Client Secret, and Tenant ID,
45 | please refer to [this
46 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
47 |
48 | ### Setting Environment Variables
49 |
50 | After you obtained the values, you need to set the following values as
51 | your environment variables
52 |
53 | - `AZURE_CLIENT_ID`
54 | - `AZURE_CLIENT_SECRET`
55 | - `AZURE_TENANT_ID`
56 | - `AZURE_SUBSCRIPTION_ID`
57 |
58 | To set the following environment variables on your development system:
59 |
60 | Windows (Note: Administrator access is required)
61 |
62 | 1. Open the Control Panel
63 | 2. Click System Security, then System
64 | 3. Click Advanced system settings on the left
65 | 4. Inside the System Properties window, click the Environment
66 | Variables… button.
67 | 5. Click on the property you would like to change, then click the Edit…
68 | button. If the property name is not listed, then click the New…
69 | button.
70 |
71 | Linux-based OS :
72 |
73 | export AZURE_CLIENT_ID="__CLIENT_ID__"
74 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
75 | export AZURE_TENANT_ID="__TENANT_ID__"
76 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
77 |
78 | ### Installation
79 |
80 | To complete this tutorial:
81 |
82 | * Install .NET Core latest version for [Linux] or [Windows]
83 |
84 | If you don't have an Azure subscription, create a [free account] before you begin.
85 |
86 | ### Quickstart
87 |
88 | 1. Clone the repository on your machine:
89 |
90 | ```bash
91 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
92 | ```
93 |
94 | 2. Switch to the project folder:
95 | ```bash
96 | cd samples/appconfiguration/create-app-configuration
97 | ```
98 |
99 | 3. Run the application with the `dotnet run` command.
100 |
101 | ```console
102 | dotnet run
103 | ```
104 |
105 | ## This sample shows how to create an App Configuration
106 |
107 | ## More information
108 |
109 | The [Azure Compute documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
110 |
111 | This project has adopted the [Microsoft Open Source Code of Conduct].
112 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
113 |
114 |
115 | [Linux]: https://dotnet.microsoft.com/download
116 | [Windows]: https://dotnet.microsoft.com/download
117 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
118 | [Azure Portal]: https://portal.azure.com
119 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
120 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
121 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
122 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
123 |
--------------------------------------------------------------------------------
/samples/communication/manage-communication/ManageCommunication.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/samples/communication/manage-communication/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Reflection.Metadata;
8 | using System.Threading.Tasks;
9 | using System.Xml.Linq;
10 | using Azure;
11 | using Azure.Core;
12 | using Azure.Identity;
13 | using Azure.ResourceManager;
14 | using Azure.ResourceManager.Communication;
15 | using Azure.ResourceManager.Communication.Models;
16 | using Azure.ResourceManager.Resources;
17 | using Azure.ResourceManager.Resources.Models;
18 | using Samples.Utilities;
19 |
20 | namespace ManageCommunication
21 | {
22 | public class Program
23 | {
24 | public static async Task Main(string[] args)
25 | {
26 | try
27 | {
28 | // Authenticate
29 | var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
30 | var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
31 | var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
32 | var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
33 | ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
34 | ArmClient client = new ArmClient(credential, subscription);
35 |
36 | await RunSample(client);
37 | }
38 | catch (Exception ex)
39 | {
40 | Utilities.Log(ex);
41 | }
42 | }
43 |
44 | public static async Task RunSample(ArmClient client)
45 | {
46 | String resourceGroupName = Utilities.RandomResourceName("rg-manage-comm-", 24);
47 | String resourceName = Utilities.RandomResourceName("manage-comm-", 24);
48 | String region = AzureLocation.WestUS;
49 |
50 | ResourceGroupResource resourceGroup = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, resourceGroupName, new ResourceGroupData(region))).Value;
51 | //collection
52 | var collection = resourceGroup.GetCommunicationServiceResources();
53 | await CreateCommunicationServiceAsync(collection, resourceName);
54 | await GetCommunicationServiceAsync(collection, resourceName);
55 | await UpdateCommunicationServiceAsync(collection, resourceName);
56 |
57 | ListCommunicationServiceByCollection(collection);
58 |
59 | await ListKeysAsync(collection, resourceName);
60 | await RegenerateKeyAsync(collection, resourceName);
61 | await RegenerateKeyAsync(collection, resourceName);
62 |
63 | await LinkNotificationHubAsync(collection, resourceName);
64 |
65 | await DeleteCommunicationServiceAsync(collection, resourceName);
66 | }
67 |
68 | private static async Task CreateCommunicationServiceAsync(CommunicationServiceResourceCollection collection, string resourceName)
69 | {
70 | try
71 | {
72 | Utilities.Log("\nCommunicationService Create...");
73 | // Data
74 | var data = new CommunicationServiceResourceData(new AzureLocation("global"))
75 | {
76 | DataLocation = new AzureLocation("UnitedStates")
77 | };
78 |
79 | // Create a resource in the specificed resource group and waits for a response
80 | Utilities.Log("Waiting for acsClient.CommunicationServiceCollection.CreateOrUpdateAsync");
81 | var resource = (await collection.CreateOrUpdateAsync(WaitUntil.Completed, resourceName, data)).Value;
82 |
83 | Utilities.Log("CommunicationServiceResource");
84 | Utilities.PrintCommunicationServiceResource(resource);
85 | }
86 | catch (Exception e)
87 | {
88 | Utilities.Log("CreateCommunicationServiceAsync encountered: " + e.Message);
89 | }
90 | }
91 |
92 | private static async Task GetCommunicationServiceAsync(CommunicationServiceResourceCollection collection, string resourceName)
93 | {
94 | try
95 | {
96 | Utilities.Log("\nCommunicationService Fetch...");
97 |
98 | // Fetch a previously created CommunicationServiceResource
99 | Utilities.Log("Waiting for CommunicationServiceCollection.Get()");
100 | var resource = (await collection.GetAsync(resourceName)).Value;
101 | Utilities.PrintCommunicationServiceResource(resource);
102 | }
103 | catch (Exception e)
104 | {
105 | Utilities.Log("GetCommunicationServiceAsync encountered: " + e.Message);
106 | }
107 | }
108 |
109 | private static async Task UpdateCommunicationServiceAsync(CommunicationServiceResourceCollection collection, string resourceName)
110 | {
111 | try
112 | {
113 | Utilities.Log("\nCommunicationService Update...");
114 |
115 | // Get Resource
116 | var resource = (await collection.GetAsync(resourceName)).Value;
117 | //Update
118 | var updateResource = (await resource.UpdateAsync(new CommunicationServiceResourcePatch()
119 | {
120 | Tags =
121 | {
122 | ["ExampleTagName1"] = "ExampleTagValue1",
123 | ["ExampleTagName2"] = "ExampleTagValue2",
124 | }
125 | })).Value;
126 | Utilities.PrintCommunicationServiceResource(updateResource);
127 | }
128 | catch (Exception e)
129 | {
130 | Utilities.Log("UpdateCommunicationServiceAsync encountered: " + e.Message);
131 | }
132 | }
133 |
134 | private static async Task DeleteCommunicationServiceAsync(CommunicationServiceResourceCollection collection, string resourceName)
135 | {
136 | try
137 | {
138 | Utilities.Log("\nCommunicationService Delete...");
139 |
140 | var resource = (await collection.GetAsync(resourceName)).Value;
141 | await resource.DeleteAsync(WaitUntil.Completed);
142 | }
143 | catch (Exception e)
144 | {
145 | Utilities.Log("DeleteCommunicationServiceAsync encountered: " + e.Message);
146 | }
147 | }
148 |
149 | private static void ListCommunicationServiceByCollection(CommunicationServiceResourceCollection collection)
150 | {
151 | try
152 | {
153 | Utilities.Log("\nCommunicationService List by Collection...");
154 |
155 | // Fetch all Azure Communication Services resources in the subscription
156 | var resources = collection.GetAll();
157 | Utilities.Log("Found number of resources: " + resources.ToArray().Length);
158 |
159 | foreach (var resource in resources)
160 | {
161 | Utilities.PrintCommunicationServiceResource(resource);
162 | }
163 | }
164 | catch (Exception e)
165 | {
166 | Utilities.Log("ListCommunicationServiceByCollection encountered: " + e.Message);
167 | }
168 | }
169 |
170 | private static async Task ListKeysAsync(CommunicationServiceResourceCollection collection, string resourceName)
171 | {
172 | try
173 | {
174 | Utilities.Log("\nCommunicationService List Keys...");
175 |
176 | var resource = (await collection.GetAsync(resourceName)).Value;
177 | var keys = await resource.GetKeysAsync();
178 | Utilities.Log("\tPrimaryKey: " + keys.Value.PrimaryKey);
179 | Utilities.Log("\tSecondaryKey: " + keys.Value.SecondaryKey);
180 | Utilities.Log("\tPrimaryConnectionString: " + keys.Value.PrimaryConnectionString);
181 | Utilities.Log("\tSecondaryConnectionString: " + keys.Value.SecondaryConnectionString);
182 | }
183 | catch (Exception e)
184 | {
185 | Utilities.Log("ListKeysAsync encountered: " + e.Message);
186 | }
187 | }
188 |
189 | private static async Task RegenerateKeyAsync(CommunicationServiceResourceCollection collection, string resourceName)
190 | {
191 | try
192 | {
193 | Utilities.Log("\nCommunicationService Regenerate Keys...");
194 |
195 | var resource = (await collection.GetAsync(resourceName)).Value;
196 | var keys = await resource.GetKeysAsync();
197 | string primaryKey = keys.Value.PrimaryKey;
198 | string secondaryKey = keys.Value.SecondaryKey;
199 | string primaryConnectionString = keys.Value.PrimaryConnectionString;
200 | string secondaryConnectionString = keys.Value.SecondaryConnectionString;
201 | var content = new RegenerateCommunicationServiceKeyContent()
202 | {
203 | KeyType = CommunicationServiceKeyType.Primary
204 | };
205 | var newkeys = await resource.RegenerateKeyAsync(content);
206 |
207 | Utilities.Log("\tPrimaryKey: " + newkeys.Value.PrimaryKey);
208 | Utilities.Log("\tSecondaryKey: " + newkeys.Value.SecondaryKey);
209 | Utilities.Log("\tPrimaryConnectionString: " + newkeys.Value.PrimaryConnectionString);
210 | Utilities.Log("\tSecondaryConnectionString: " + newkeys.Value.SecondaryConnectionString);
211 | }
212 | catch (Exception e)
213 | {
214 | Utilities.Log("RegenerateKeyAsync encountered: " + e.Message);
215 | }
216 | }
217 |
218 | private static async Task LinkNotificationHubAsync(CommunicationServiceResourceCollection collection, string resourceName)
219 | {
220 | try
221 | {
222 | Utilities.Log("\nCommunicationService Link Notification Hub...");
223 | var resource = (await collection.GetAsync(resourceName)).Value;
224 | var notificationHubId = Environment.GetEnvironmentVariable("AZURE_NOTIFICATION_HUB_ID");
225 | var notificationHubConnectionString = Environment.GetEnvironmentVariable("AZURE_NOTIFICATION_HUB_CONNECTION_STRING");
226 |
227 | var parameter = new LinkNotificationHubContent(new ResourceIdentifier(notificationHubId), notificationHubConnectionString);
228 | var hub = await resource.LinkNotificationHubAsync(parameter);
229 | }
230 | catch (Exception e)
231 | {
232 | Utilities.Log("LinkNotificationHubAsync encountered: " + e.Message);
233 | }
234 | }
235 | }
236 | }
237 |
--------------------------------------------------------------------------------
/samples/communication/manage-communication/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code sample will show you how to manage Communication Service resources using Azure SDK for .NET."
8 | urlFragment: communication-manage-communication
9 | ---
10 | # Getting started - Managing Azure Communication Services using Azure .NET SDK
11 |
12 | This code sample will show you how to manage Communication Service resources using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### Communication
19 | * You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/#dotnet).
20 |
21 | ## Getting Started
22 |
23 | ### Prerequisites
24 |
25 | You will need the following values run the sample:
26 |
27 | - **Subscription ID**
28 | - **Client ID**
29 | - **Client Secret**
30 | - **Tenant ID**
31 | - **Notification Hub Resource ID**
32 | - **Notification Hub Connection String**
33 |
34 | These values can be obtained from the portal.
35 |
36 | ### Get Subscription ID
37 |
38 | 1. Login into your Azure account.
39 | 2. Select Subscriptions in the left sidebar.
40 | 3. Select whichever subscription is needed.
41 | 4. Click on Overview.
42 | 5. Copy the Subscription ID.
43 |
44 | ### Get Client ID / Client Secret / Tenant ID
45 |
46 | For information on how to get Client ID, Client Secret, and Tenant ID,
47 | please refer to [this
48 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
49 |
50 | ### Get Notification Hubs Resource ID and Connection String
51 |
52 | 1. Login into your Azure account.
53 | 2. Search for Notification Hubs.
54 | 3. Create a Notificaiton Hub.
55 | 4. On the `Properties` blade, you will find the Notification Hub Resource ID.
56 | 5. On the `Access Policies` blade, you will find the Notification Hub Connection String. The Connection String only needs the Listen permission for this sample.
57 |
58 | ### Setting Environment Variables
59 |
60 | After you obtained the values, you need to set the following values as
61 | your environment variables
62 |
63 | - `AZURE_CLIENT_ID`
64 | - `AZURE_CLIENT_SECRET`
65 | - `AZURE_TENANT_ID`
66 | - `AZURE_SUBSCRIPTION_ID`
67 | - `AZURE_NOTIFICATION_HUB_ID`
68 | - `AZURE_NOTIFICATION_HUB_CONNECTION_STRING`
69 |
70 | To set the following environment variables on your development system:
71 |
72 | Windows (Note: Administrator access is required)
73 |
74 | 1. Open the Control Panel
75 | 2. Click System Security, then System
76 | 3. Click Advanced system settings on the left
77 | 4. Inside the System Properties window, click the Environment
78 | Variables… button.
79 | 5. Click on the property you would like to change, then click the Edit…
80 | button. If the property name is not listed, then click the New…
81 | button.
82 |
83 | Linux-based OS :
84 |
85 | export AZURE_CLIENT_ID="__CLIENT_ID__"
86 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
87 | export AZURE_TENANT_ID="__TENANT_ID__"
88 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
89 | export AZURE_NOTIFICATION_HUBS_ID="__AZURE_NOTIFICATION_HUBS_ID__"
90 | export AZURE_NOTIFICATION_HUBS_CONNECTION_STRING="__AZURE_NOTIFICATION_HUBS_CONNECTION_STRING__"
91 |
92 | ### Installation
93 |
94 | To complete this tutorial:
95 |
96 | * Install .NET Core latest version for [Linux] or [Windows]
97 |
98 | If you don't have an Azure subscription, create a [free account] before you begin.
99 |
100 | ### Quickstart
101 |
102 | 1. Clone the repository on your machine:
103 |
104 | ```bash
105 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
106 | ```
107 |
108 | 2. Switch to the project folder:
109 | ```bash
110 | cd samples/communication/manage-communication
111 | ```
112 |
113 | 3. Run the application with the `dotnet run` command.
114 |
115 | ```console
116 | dotnet run
117 | ```
118 |
119 | ## This sample shows how to do following operations to manage Communication Service resources
120 | - Check name availability for a Communication Service resource.
121 | - Create a Communication Service resource.
122 | - Get a Communication Service resource.
123 | - Update a Communication Service resource.
124 | - Delete a Communication Service resource.
125 | - List Communication Service resources by subscription.
126 | - List Communication Service resources by resource group.
127 | - List keys.
128 | - Regenerate keys.
129 | - Link Notification Hub.
130 |
131 | ## More information
132 |
133 | The [Azure Communication documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
134 |
135 | This project has adopted the [Microsoft Open Source Code of Conduct].
136 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
137 |
138 |
139 | [Linux]: https://dotnet.microsoft.com/download
140 | [Windows]: https://dotnet.microsoft.com/download
141 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
142 | [Azure Portal]: https://portal.azure.com
143 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
144 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
145 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
146 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
147 |
--------------------------------------------------------------------------------
/samples/compute/create-virtual-machine/CreateVMSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/samples/compute/create-virtual-machine/Program.cs:
--------------------------------------------------------------------------------
1 | using Azure.Identity;
2 | using Azure.ResourceManager.Resources;
3 | using Azure.ResourceManager;
4 | using Azure.ResourceManager.Resources.Models;
5 | using Azure.ResourceManager.Compute;
6 | using Azure.ResourceManager.Compute.Models;
7 | using Azure.ResourceManager.Network;
8 | using Azure.ResourceManager.Network.Models;
9 | using System;
10 | using System.Collections.Generic;
11 | using System.Threading.Tasks;
12 | using System.Linq;
13 | using Azure.Core;
14 | using System.Xml.Linq;
15 |
16 | namespace CreateVMSample
17 | {
18 | public class Program
19 | {
20 | protected static string AdminUsername = "";
21 | protected static string AdminPassword = "";
22 |
23 | static async Task Main(string[] args)
24 | {
25 | var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
26 | var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
27 | var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
28 | var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
29 | ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
30 | ArmClient client = new ArmClient(credential, subscription);
31 |
32 | // Create Resource Group
33 | Console.WriteLine("--------Start create group--------");
34 | var resourceGroupName = "QuickStartRG";
35 | String location = AzureLocation.WestUS2;
36 |
37 | ResourceGroupResource resourceGroup = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, resourceGroupName, new ResourceGroupData(location))).Value;
38 | Console.WriteLine("--------Finish create group--------");
39 |
40 | // Create a Virtual Machine
41 | await Program.CreateVmAsync(resourceGroup, "QuickStartRG", location, "quickstartvm");
42 |
43 | // Delete resource group if necessary
44 | //Console.WriteLine("--------Start delete group--------");
45 | //await (await resourceGroups.StartDeleteAsync(resourceGroupName)).WaitForCompletionAsync();
46 | //Console.WriteLine("--------Finish delete group--------");
47 | //Console.ReadKey();
48 | }
49 |
50 | public static async Task CreateVmAsync(
51 | ResourceGroupResource resourcegroup,
52 | string resourceGroupName,
53 | string location,
54 | string vmName)
55 | {
56 | var collection = resourcegroup.GetVirtualMachines();
57 |
58 | // Create VNet
59 | Console.WriteLine("--------Start create VNet--------");
60 | var vnet = new VirtualNetworkData()
61 | {
62 | Location = location,
63 | AddressPrefixes = { "10.0.0.0/16" },
64 | Subnets = { new SubnetData() { Name = "SubnetSampleName", AddressPrefix = "10.0.0.0/28" } }
65 | };
66 |
67 | // Create Network Interface
68 | Console.WriteLine("--------Start create Network Interface--------");
69 | var nicData = new NetworkInterfaceData()
70 | {
71 | Location = location,
72 | IPConfigurations = {
73 | new NetworkInterfaceIPConfigurationData()
74 | {
75 | Name = "SampleIpConfigName",
76 | PrivateIPAllocationMethod = NetworkIPAllocationMethod.Dynamic,
77 | Primary = false,
78 | Subnet = new SubnetData()
79 | {
80 | Id = vnet.Subnets.ElementAt(0).Id
81 | }
82 | }
83 | }
84 | };
85 | var nicCollection = resourcegroup.GetNetworkInterfaces();
86 | var nic = (await nicCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, "SampleNicName", nicData)).Value;
87 |
88 | // Create VM
89 | Console.WriteLine("--------Start create VM--------");
90 | var vmData = new VirtualMachineData(location)
91 | {
92 | HardwareProfile = new VirtualMachineHardwareProfile()
93 | {
94 | VmSize = VirtualMachineSizeType.StandardF2
95 | },
96 | OSProfile = new VirtualMachineOSProfile()
97 | {
98 | AdminUsername = AdminUsername,
99 | AdminPassword = AdminPassword,
100 | ComputerName = "linux Compute",
101 | LinuxConfiguration = new LinuxConfiguration()
102 | {
103 | DisablePasswordAuthentication = true,
104 | }
105 | },
106 | NetworkProfile = new VirtualMachineNetworkProfile()
107 | {
108 | NetworkInterfaces =
109 | {
110 | new VirtualMachineNetworkInterfaceReference()
111 | {
112 | Id = nic.Id,
113 | Primary = true,
114 | }
115 | }
116 | },
117 | StorageProfile = new VirtualMachineStorageProfile()
118 | {
119 | OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
120 | {
121 | Name = "Sample",
122 | OSType = SupportedOperatingSystemType.Windows,
123 | Caching = CachingType.ReadWrite,
124 | ManagedDisk = new VirtualMachineManagedDisk()
125 | {
126 | StorageAccountType = StorageAccountType.StandardLrs
127 | }
128 | },
129 | DataDisks =
130 | {
131 | new VirtualMachineDataDisk(1, DiskCreateOptionType.Empty)
132 | {
133 | DiskSizeGB = 100,
134 | ManagedDisk = new VirtualMachineManagedDisk()
135 | {
136 | StorageAccountType = StorageAccountType.StandardLrs
137 | }
138 | },
139 | new VirtualMachineDataDisk(2, DiskCreateOptionType.Empty)
140 | {
141 | DiskSizeGB = 10,
142 | Caching = CachingType.ReadWrite,
143 | ManagedDisk = new VirtualMachineManagedDisk()
144 | {
145 | StorageAccountType = StorageAccountType.StandardLrs
146 | }
147 | },
148 | },
149 | ImageReference = new ImageReference()
150 | {
151 | Publisher = "MicrosoftWindowsServer",
152 | Offer = "WindowsServer",
153 | Sku = "2016-Datacenter",
154 | Version = "latest",
155 | }
156 | }
157 | };
158 |
159 | var resource = await collection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, vmName, vmData);
160 | Console.WriteLine("VM ID: " + resource.Id);
161 | Console.WriteLine("--------Done create VM--------");
162 | }
163 | }
164 | }
165 |
--------------------------------------------------------------------------------
/samples/compute/create-virtual-machine/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code samples will show you how to create a Vitural Machine using Azure SDK for .NET."
8 | urlFragment: compute-create-vm
9 | ---
10 | # Getting started - Managing Compute Resources using Azure .NET SDK
11 |
12 | This code sample will show you how to create a Virtual Machine using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### Compute
19 | * You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/#dotnet).
20 |
21 | ## Getting Started
22 |
23 | ### Prerequisites
24 |
25 | You will need the following values to authenticate to Azure
26 |
27 | - **Subscription ID**
28 | - **Client ID**
29 | - **Client Secret**
30 | - **Tenant ID**
31 |
32 | These values can be obtained from the portal, here's the instructions:
33 |
34 | ### Get Subscription ID
35 |
36 | 1. Login into your Azure account
37 | 2. Select Subscriptions in the left sidebar
38 | 3. Select whichever subscription is needed
39 | 4. Click on Overview
40 | 5. Copy the Subscription ID
41 |
42 | ### Get Client ID / Client Secret / Tenant ID
43 |
44 | For information on how to get Client ID, Client Secret, and Tenant ID,
45 | please refer to [this
46 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
47 |
48 | ### Setting Environment Variables
49 |
50 | After you obtained the values, you need to set the following values as
51 | your environment variables
52 |
53 | - `AZURE_CLIENT_ID`
54 | - `AZURE_CLIENT_SECRET`
55 | - `AZURE_TENANT_ID`
56 | - `AZURE_SUBSCRIPTION_ID`
57 |
58 | To set the following environment variables on your development system:
59 |
60 | Windows (Note: Administrator access is required)
61 |
62 | 1. Open the Control Panel
63 | 2. Click System Security, then System
64 | 3. Click Advanced system settings on the left
65 | 4. Inside the System Properties window, click the Environment
66 | Variables… button.
67 | 5. Click on the property you would like to change, then click the Edit…
68 | button. If the property name is not listed, then click the New…
69 | button.
70 |
71 | Linux-based OS :
72 |
73 | export AZURE_CLIENT_ID="__CLIENT_ID__"
74 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
75 | export AZURE_TENANT_ID="__TENANT_ID__"
76 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
77 |
78 | ### Installation
79 |
80 | To complete this tutorial:
81 |
82 | * Install .NET Core latest version for [Linux] or [Windows]
83 |
84 | If you don't have an Azure subscription, create a [free account] before you begin.
85 |
86 | ### Quickstart
87 |
88 | 1. Clone the repository on your machine:
89 |
90 | ```bash
91 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
92 | ```
93 |
94 | 2. Switch to the project folder:
95 | ```bash
96 | cd samples/compute/create-virtual-machine
97 | ```
98 | 3. Replace the ```AdminUsername``` and ```AdminPassowrd``` in the following code snip from Program.cs file.
99 | ```csharp
100 | protected static string AdminUsername = "";
101 | protected static string AdminPassword = "";
102 | ```
103 |
104 | 4. Run the application with the `dotnet run` command.
105 |
106 | ```console
107 | dotnet run
108 | ```
109 |
110 | ## This sample shows how to do following operations to create a Virtual Machine
111 | - Create a Resource Group.
112 | - Create a AvailabilitySet.
113 | - Create a IP Address.
114 | - Create a Virtual Network.
115 | - Craete a Network Interface.
116 | - Create a Virtual Machine.
117 |
118 | ## More information
119 |
120 | The [Azure Compute documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
121 |
122 | This project has adopted the [Microsoft Open Source Code of Conduct].
123 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
124 |
125 |
126 | [Linux]: https://dotnet.microsoft.com/download
127 | [Windows]: https://dotnet.microsoft.com/download
128 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
129 | [Azure Portal]: https://portal.azure.com
130 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
131 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
132 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
133 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
134 |
--------------------------------------------------------------------------------
/samples/compute/create-virtual-machines-in-parallel/CreateVirtualMachinesInParallel.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/samples/compute/create-virtual-machines-in-parallel/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License. See License.txt in the project root for license information.
3 |
4 | using Azure;
5 | using Azure.Core;
6 | using Azure.Identity;
7 | using Azure.ResourceManager;
8 | using Azure.ResourceManager.Compute;
9 | using Azure.ResourceManager.Compute.Models;
10 | using Azure.ResourceManager.Network;
11 | using Azure.ResourceManager.Network.Models;
12 | using Azure.ResourceManager.Resources;
13 | using Azure.ResourceManager.Storage;
14 | using Azure.ResourceManager.Storage.Models;
15 | using Samples.Utilities;
16 | using System;
17 | using System.Collections.Generic;
18 | using System.Linq;
19 | using System.Threading.Tasks;
20 |
21 | namespace CreateVirtualMachinesInParallel
22 | {
23 | public class Program
24 | {
25 | //Azure compute sample for creating multiple virtual machines in parallel.
26 | // - Define 1 virtual network per region
27 | // - Define 1 storage account per region
28 | // - Create 5 virtual machines in 2 regions using defined virtual network and storage account
29 | // - Create a traffic manager to route traffic across the virtual machines(Wait for Track2 Traffic Manager ready)
30 |
31 | private const string Username = "tirekicker";
32 | private const string Password = "";
33 | private static readonly string rgName = Utilities.RandomResourceName("rgCOMV", 10);
34 | private static readonly string SubscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
35 |
36 | public static async Task RunSample(ArmClient client)
37 | {
38 |
39 | IDictionary virtualMachinesByLocation = new Dictionary();
40 |
41 | virtualMachinesByLocation.Add("eastus", 5);
42 | virtualMachinesByLocation.Add("southcentralus", 5);
43 |
44 | var resourceGroupName = "QuickStartRG";
45 | String location = AzureLocation.WestUS2;
46 | // Create a resource group (Where all resources gets created)
47 | ResourceGroupResource resourceGroup = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, resourceGroupName, new ResourceGroupData(location))).Value;
48 |
49 | try
50 | {
51 | var publicIpCreatableKeys = new List();
52 | // Prepare a batch of Creatable definitions
53 | //var creatableVirtualMachines = new Dictionary();
54 | var creatableVirtualMachines = new List();
55 | var startTime = DateTimeOffset.Now.UtcDateTime;
56 |
57 | foreach (var entry in virtualMachinesByLocation)
58 | {
59 | var region = entry.Key;
60 | var vmCount = entry.Value;
61 |
62 | // Create 1 network creatable per region
63 | // Prepare Creatable Network definition (Where all the virtual machines get added to)
64 | var networkName = Utilities.RandomResourceName("vnetCOPD-", 20);
65 | var networkCollection = resourceGroup.GetVirtualNetworks();
66 | var networkData = new VirtualNetworkData()
67 | {
68 | Location = region,
69 | AddressPrefixes =
70 | {
71 | "172.16.0.0/16"
72 | }
73 | };
74 | var networkCreatable = networkCollection.CreateOrUpdate(Azure.WaitUntil.Completed, networkName, networkData).Value;
75 |
76 | // Create 1 storage creatable per region (For storing VMs disk)
77 | var storageAccountSkuName = Utilities.RandomResourceName("stgsku", 20);
78 | var storageAccountName = Utilities.RandomResourceName("stgcopd", 20);
79 | var storageAccountCollection = resourceGroup.GetStorageAccounts();
80 | var storageAccountData = new StorageAccountCreateOrUpdateContent(new StorageSku(storageAccountSkuName), StorageKind.Storage, region);
81 | {
82 | };
83 | var storageAccountCreatable = storageAccountCollection.CreateOrUpdate(WaitUntil.Completed, storageAccountName, storageAccountData).Value;
84 | string containerName = Utilities.RandomResourceName("cndisk", 20);
85 |
86 | var linuxVMNamePrefix = Utilities.RandomResourceName("vm-", 15);
87 | var pipDnsLabelLinuxVM = Utilities.CreateRandomName("rgpip1");
88 | string pipName = Utilities.CreateRandomName("pip1");
89 | var publicIpAddressCollection = resourceGroup.GetPublicIPAddresses();
90 | var publicIPAddressData = new PublicIPAddressData()
91 | {
92 | Location = region,
93 | DnsSettings =
94 | {
95 | DomainNameLabel = pipDnsLabelLinuxVM
96 | }
97 | };
98 | var publicIpAddressCreatable = (publicIpAddressCollection.CreateOrUpdate(Azure.WaitUntil.Completed, pipName, publicIPAddressData)).Value;
99 | //Create a subnet
100 | Utilities.Log("Creating a Linux subnet...");
101 | var subnetName = Utilities.CreateRandomName("subnet_");
102 | var subnetData = new SubnetData()
103 | {
104 | ServiceEndpoints =
105 | {
106 | new ServiceEndpointProperties()
107 | {
108 | Service = "Microsoft.Storage"
109 | }
110 | },
111 | Name = subnetName,
112 | AddressPrefix = "10.0.0.0/28",
113 | };
114 | var subnetLRro = networkCreatable.GetSubnets().CreateOrUpdate(WaitUntil.Completed, subnetName, subnetData);
115 | var subnet = subnetLRro.Value;
116 | Utilities.Log("Created a Linux subnet with name : " + subnet.Data.Name);
117 |
118 | //Create a networkInterface
119 | Utilities.Log("Created a linux networkInterface");
120 | var networkInterfaceData = new NetworkInterfaceData()
121 | {
122 | Location = region,
123 | IPConfigurations =
124 | {
125 | new NetworkInterfaceIPConfigurationData()
126 | {
127 | Name = "internal",
128 | Primary = true,
129 | Subnet = new SubnetData
130 | {
131 | Name = subnetName,
132 | Id = new ResourceIdentifier($"{networkCreatable.Data.Id}/subnets/{subnetName}")
133 | },
134 | PrivateIPAllocationMethod = NetworkIPAllocationMethod.Dynamic,
135 | PublicIPAddress = publicIpAddressCreatable.Data,
136 | }
137 | }
138 | };
139 | var networkInterfaceName = Utilities.CreateRandomName("networkInterface");
140 | var nic = (resourceGroup.GetNetworkInterfaces().CreateOrUpdate(WaitUntil.Completed, networkInterfaceName, networkInterfaceData)).Value;
141 | Utilities.Log("Created a Linux networkInterface with name : " + nic.Data.Name);
142 | var virtualMachineCollection = resourceGroup.GetVirtualMachines();
143 | var linuxComputerName = Utilities.CreateRandomName("linuxComputer");
144 | // Create 1 virtual machine creatable
145 | for (int i = 1; i <= vmCount; i++)
146 | {
147 | var vhdContainer = "https://" + storageAccountName + ".blob.core.windows.net/" + containerName;
148 |
149 | var linuxVmdata = new VirtualMachineData(region)
150 | {
151 | HardwareProfile = new VirtualMachineHardwareProfile()
152 | {
153 | VmSize = "Standard_D2a_v4"
154 | },
155 | OSProfile = new VirtualMachineOSProfile()
156 | {
157 | AdminUsername = Username,
158 | AdminPassword = Password,
159 | ComputerName = linuxComputerName,
160 | },
161 | NetworkProfile = new VirtualMachineNetworkProfile()
162 | {
163 | NetworkInterfaces =
164 | {
165 | new VirtualMachineNetworkInterfaceReference()
166 | {
167 | Id = nic.Id,
168 | Primary = true,
169 | }
170 | }
171 | },
172 | StorageProfile = new VirtualMachineStorageProfile()
173 | {
174 | OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
175 | {
176 | OSType = SupportedOperatingSystemType.Linux,
177 | Caching = CachingType.ReadWrite,
178 | ManagedDisk = new VirtualMachineManagedDisk()
179 | {
180 | StorageAccountType = StorageAccountType.StandardLrs
181 | }
182 | },
183 | ImageReference = new ImageReference()
184 | {
185 | Publisher = "Canonical",
186 | Offer = "UbuntuServer",
187 | Sku = "16.04-LTS",
188 | Version = "latest",
189 | },
190 | },
191 | Zones =
192 | {
193 | "1"
194 | },
195 | BootDiagnostics = new BootDiagnostics()
196 | {
197 | StorageUri = new Uri($"http://{storageAccountCreatable.Data.Name}.blob.core.windows.net")
198 | }
199 | };
200 | var creatableVirtualMachine = virtualMachineCollection.CreateOrUpdate(WaitUntil.Completed, "vm-" + i, linuxVmdata).Value;
201 | creatableVirtualMachines.Add(creatableVirtualMachine);
202 | }
203 | var virtualMachines = virtualMachineCollection.GetAll();
204 | foreach (var virtualMachine in virtualMachines)
205 | {
206 | Utilities.Log(virtualMachine.Id);
207 | }
208 | var endTime = DateTimeOffset.Now.UtcDateTime;
209 | Utilities.Log($"Created VM: took {(endTime - startTime).TotalSeconds} seconds");
210 | }
211 |
212 | }
213 | finally
214 | {
215 | try
216 | {
217 | await resourceGroup.DeleteAsync(Azure.WaitUntil.Completed);
218 | }
219 | catch (NullReferenceException)
220 | {
221 | Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
222 | }
223 | catch (Exception ex)
224 | {
225 | Utilities.Log(ex);
226 | }
227 | }
228 | }
229 |
230 | public static async Task Main(string[] args)
231 | {
232 | try
233 | {
234 | // Authenticate
235 | var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
236 | var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
237 | var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
238 | var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
239 | ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
240 | ArmClient client = new ArmClient(credential, subscription);
241 |
242 | await RunSample(client);
243 | }
244 | catch (Exception ex)
245 | {
246 | Utilities.Log(ex);
247 | }
248 | }
249 | }
250 | }
251 |
--------------------------------------------------------------------------------
/samples/compute/create-virtual-machines-in-parallel/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code samples will show you how to create multiple virtual machines in parallel using Azure SDK for .NET."
8 | urlFragment: compute-create-vms-in-parallel
9 | ---
10 | # Getting started - Create Virtual Machines in parallel using Azure .NET SDK
11 |
12 | This code sample will show you how to create multiple virtual machines in parallel using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### Compute
19 | * You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/#dotnet).
20 |
21 | ## Getting Started
22 |
23 | ### Prerequisites
24 |
25 | You will need the following values to authenticate to Azure
26 |
27 | - **Subscription ID**
28 | - **Client ID**
29 | - **Client Secret**
30 | - **Tenant ID**
31 |
32 | These values can be obtained from the portal, here's the instructions:
33 |
34 | ### Get Subscription ID
35 |
36 | 1. Login into your Azure account
37 | 2. Select Subscriptions in the left sidebar
38 | 3. Select whichever subscription is needed
39 | 4. Click on Overview
40 | 5. Copy the Subscription ID
41 |
42 | ### Get Client ID / Client Secret / Tenant ID
43 |
44 | For information on how to get Client ID, Client Secret, and Tenant ID,
45 | please refer to [this
46 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
47 |
48 | ### Setting Environment Variables
49 |
50 | After you obtained the values, you need to set the following values as
51 | your environment variables
52 |
53 | - `AZURE_CLIENT_ID`
54 | - `AZURE_CLIENT_SECRET`
55 | - `AZURE_TENANT_ID`
56 | - `AZURE_SUBSCRIPTION_ID`
57 |
58 | To set the following environment variables on your development system:
59 |
60 | Windows (Note: Administrator access is required)
61 |
62 | 1. Open the Control Panel
63 | 2. Click System Security, then System
64 | 3. Click Advanced system settings on the left
65 | 4. Inside the System Properties window, click the Environment
66 | Variables… button.
67 | 5. Click on the property you would like to change, then click the Edit…
68 | button. If the property name is not listed, then click the New…
69 | button.
70 |
71 | Linux-based OS :
72 |
73 | export AZURE_CLIENT_ID="__CLIENT_ID__"
74 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
75 | export AZURE_TENANT_ID="__TENANT_ID__"
76 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
77 |
78 | ### Installation
79 |
80 | To complete this tutorial:
81 |
82 | * Install .NET Core latest version for [Linux] or [Windows]
83 |
84 | If you don't have an Azure subscription, create a [free account] before you begin.
85 |
86 | ### Quickstart
87 |
88 | 1. Clone the repository on your machine:
89 |
90 | ```bash
91 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
92 | ```
93 |
94 | 2. Switch to the project folder:
95 | ```bash
96 | cd samples/compute/create-virtual-machines-in-parallel
97 | ```
98 |
99 | 3. Replace all the `````` placeholder with a valid password in the Program.cs file.
100 |
101 | 4. Run the application with the `dotnet run` command.
102 |
103 | ## This sample shows how to do following operations to creating multiple virtual machines in parallel
104 | - Create 1 virtual network per region.
105 | - Create 1 storage account per region.
106 | - Create 5 virtual machines in 2 regions using defined virtual network and storage account.
107 | - Create a traffic manager to route traffic across the virtual machines (Wait for Track2 Traffic Manager ready).
108 |
109 | ## More information
110 |
111 | The [Azure Compute documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
112 |
113 | This project has adopted the [Microsoft Open Source Code of Conduct].
114 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
115 |
116 |
117 | [Linux]: https://dotnet.microsoft.com/download
118 | [Windows]: https://dotnet.microsoft.com/download
119 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
120 | [Azure Portal]: https://portal.azure.com
121 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
122 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
123 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
124 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
125 |
--------------------------------------------------------------------------------
/samples/compute/manage-virtual-machine-extension/ManageVMExtension.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/samples/compute/manage-virtual-machine-extension/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code samples will show you how to manage a Vitural Machine using Azure SDK for .NET."
8 | urlFragment: compute-manage-vm-extension
9 | ---
10 | # Getting started - Managing Virtual Machine using Azure .NET SDK
11 |
12 | This code sample will show you how to manage a Virtual Machine using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### Compute
19 | * You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/#dotnet).
20 |
21 | ## Getting Started
22 |
23 | ### Prerequisites
24 |
25 | You will need the following values to authenticate to Azure
26 |
27 | - **Subscription ID**
28 | - **Client ID**
29 | - **Client Secret**
30 | - **Tenant ID**
31 |
32 | These values can be obtained from the portal, here's the instructions:
33 |
34 | ### Get Subscription ID
35 |
36 | 1. Login into your Azure account
37 | 2. Select Subscriptions in the left sidebar
38 | 3. Select whichever subscription is needed
39 | 4. Click on Overview
40 | 5. Copy the Subscription ID
41 |
42 | ### Get Client ID / Client Secret / Tenant ID
43 |
44 | For information on how to get Client ID, Client Secret, and Tenant ID,
45 | please refer to [this
46 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
47 |
48 | ### Setting Environment Variables
49 |
50 | After you obtained the values, you need to set the following values as
51 | your environment variables
52 |
53 | - `AZURE_CLIENT_ID`
54 | - `AZURE_CLIENT_SECRET`
55 | - `AZURE_TENANT_ID`
56 | - `AZURE_SUBSCRIPTION_ID`
57 |
58 | To set the following environment variables on your development system:
59 |
60 | Windows (Note: Administrator access is required)
61 |
62 | 1. Open the Control Panel
63 | 2. Click System Security, then System
64 | 3. Click Advanced system settings on the left
65 | 4. Inside the System Properties window, click the Environment
66 | Variables… button.
67 | 5. Click on the property you would like to change, then click the Edit…
68 | button. If the property name is not listed, then click the New…
69 | button.
70 |
71 | Linux-based OS :
72 |
73 | export AZURE_CLIENT_ID="__CLIENT_ID__"
74 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
75 | export AZURE_TENANT_ID="__TENANT_ID__"
76 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
77 |
78 | ### Installation
79 |
80 | To complete this tutorial:
81 |
82 | * Install .NET Core latest version for [Linux] or [Windows]
83 |
84 | If you don't have an Azure subscription, create a [free account] before you begin.
85 |
86 | ### Quickstart
87 |
88 | 1. Clone the repository on your machine:
89 |
90 | ```bash
91 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
92 | ```
93 |
94 | 2. Switch to the project folder:
95 | ```bash
96 | cd samples/compute/manage-virtual-machine
97 | ```
98 |
99 | 3. Replace all the `````` placeholder with a valid password in the Program.cs file.
100 |
101 | 4. Run the application with the `dotnet run` command.
102 |
103 | ## This sample shows how to do following operations to manage a Virtual Machine
104 | - Create a virtual machine with managed OS Disk
105 | - Start a virtual machine
106 | - Stop a virtual machine
107 | - Restart a virtual machine
108 | - Update a virtual machine
109 | - Tag a virtual machine (there are many possible variations here)
110 | - Attach data disks
111 | - Detach data disks
112 | - List virtual machines
113 | - Delete a virtual machine.
114 |
115 | ## More information
116 |
117 | The [Azure Compute documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
118 |
119 | This project has adopted the [Microsoft Open Source Code of Conduct].
120 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
121 |
122 |
123 | [Linux]: https://dotnet.microsoft.com/download
124 | [Windows]: https://dotnet.microsoft.com/download
125 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
126 | [Azure Portal]: https://portal.azure.com
127 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
128 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
129 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
130 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
131 |
--------------------------------------------------------------------------------
/samples/compute/manage-virtual-machine/ManageVMSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/samples/compute/manage-virtual-machine/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License. See License.txt in the project root for license information.
3 |
4 | using Azure.Core;
5 | using Azure.Identity;
6 | using Azure.ResourceManager;
7 | using Azure.ResourceManager.Compute;
8 | using Azure.ResourceManager.Compute.Models;
9 | using Azure.ResourceManager.Network;
10 | using Azure.ResourceManager.Network.Models;
11 | using Azure.ResourceManager.Resources;
12 | using Samples.Utilities;
13 | using System;
14 | using System.Collections.Generic;
15 | using System.Linq;
16 | using System.Threading.Tasks;
17 | using System.Xml.Linq;
18 |
19 | namespace ManageVirtualMachine
20 | {
21 | public class Program
22 | {
23 |
24 | //Azure Compute sample for managing virtual machines -
25 | // - Create a virtual machine with managed OS Disk
26 | // - Start a virtual machine
27 | // - Stop a virtual machine
28 | // - Restart a virtual machine
29 | // - Update a virtual machine
30 | // - Tag a virtual machine(there are many possible variations here)
31 | // - Attach data disks
32 | // - Detach data disks
33 | // - List virtual machines
34 | // - Delete a virtual machine.
35 |
36 | public static async Task RunSample(ArmClient client)
37 | {
38 | var region = "westcentralus";
39 | var nicName = Utilities.CreateRandomName("nic");
40 | var nicName2 = Utilities.CreateRandomName("nic2");
41 | var windowsVmName = Utilities.CreateRandomName("wVM");
42 | var linuxVmName = Utilities.CreateRandomName("lVM");
43 | var rgName = Utilities.CreateRandomName("rgCOMV");
44 | var userName = "tirekicker";
45 | var password = "";
46 | var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
47 | ResourceGroupResource resourceGroup = null;
48 | try
49 | {
50 | String location = AzureLocation.WestUS2;
51 |
52 | resourceGroup = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, rgName, new ResourceGroupData(location))).Value;
53 |
54 | // Create a Windows virtual machine
55 | var collection = resourceGroup.GetVirtualMachines();
56 | // Create VNet
57 | Console.WriteLine("--------Start create VNet--------");
58 | var vnet = new VirtualNetworkData()
59 | {
60 | Location = location,
61 | AddressPrefixes = { "10.0.0.0/16" },
62 | Subnets = { new SubnetData() { Name = "SubnetSampleName", AddressPrefix = "10.0.0.0/28" } }
63 | };
64 |
65 | // Create Network Interface
66 | Console.WriteLine("--------Start create Network Interface--------");
67 | var nicData = new NetworkInterfaceData()
68 | {
69 | Location = location,
70 | IPConfigurations = {
71 | new NetworkInterfaceIPConfigurationData()
72 | {
73 | Name = "SampleIpConfigName",
74 | PrivateIPAllocationMethod = NetworkIPAllocationMethod.Dynamic,
75 | Primary = false,
76 | Subnet = new SubnetData()
77 | {
78 | Id = vnet.Subnets.ElementAt(0).Id
79 | }
80 | }
81 | }
82 | };
83 | var nicCollection = resourceGroup.GetNetworkInterfaces();
84 | var nic = (await nicCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, nicName, nicData)).Value;
85 | var t1 = new DateTime();
86 | // Create VM
87 | Console.WriteLine("--------Start create VM--------");
88 | var vmData = new VirtualMachineData(location)
89 | {
90 | HardwareProfile = new VirtualMachineHardwareProfile()
91 | {
92 | VmSize = VirtualMachineSizeType.StandardF2
93 | },
94 | OSProfile = new VirtualMachineOSProfile()
95 | {
96 | AdminUsername = userName,
97 | AdminPassword = password,
98 | ComputerName = "linux Compute",
99 | LinuxConfiguration = new LinuxConfiguration()
100 | {
101 | DisablePasswordAuthentication = true,
102 | }
103 | },
104 | NetworkProfile = new VirtualMachineNetworkProfile()
105 | {
106 | NetworkInterfaces =
107 | {
108 | new VirtualMachineNetworkInterfaceReference()
109 | {
110 | Id = nic.Id,
111 | Primary = true,
112 | }
113 | }
114 | },
115 | StorageProfile = new VirtualMachineStorageProfile()
116 | {
117 | OSDisk = new VirtualMachineOSDisk(DiskCreateOptionType.FromImage)
118 | {
119 | Name = "Sample",
120 | OSType = SupportedOperatingSystemType.Windows,
121 | Caching = CachingType.ReadWrite,
122 | ManagedDisk = new VirtualMachineManagedDisk()
123 | {
124 | StorageAccountType = StorageAccountType.StandardLrs
125 | }
126 | },
127 | DataDisks =
128 | {
129 | new VirtualMachineDataDisk(1, DiskCreateOptionType.Empty)
130 | {
131 | DiskSizeGB = 100,
132 | ManagedDisk = new VirtualMachineManagedDisk()
133 | {
134 | StorageAccountType = StorageAccountType.StandardLrs
135 | }
136 | },
137 | new VirtualMachineDataDisk(2, DiskCreateOptionType.Empty)
138 | {
139 | DiskSizeGB = 10,
140 | Caching = CachingType.ReadWrite,
141 | ManagedDisk = new VirtualMachineManagedDisk()
142 | {
143 | StorageAccountType = StorageAccountType.StandardLrs
144 | }
145 | },
146 | },
147 | ImageReference = new ImageReference()
148 | {
149 | Publisher = "MicrosoftWindowsServer",
150 | Offer = "WindowsServer",
151 | Sku = "2016-Datacenter",
152 | Version = "latest",
153 | }
154 | }
155 | };
156 |
157 | var windowsVM = await collection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, windowsVmName, vmData);
158 | Console.WriteLine("VM ID: " + windowsVM.Id);
159 | Console.WriteLine("--------Done create VM--------");
160 |
161 | var t2 = new DateTime();
162 | Utilities.Log($"Created VM: (took {(t2 - t1).TotalSeconds} seconds) " + windowsVM.Id);
163 | // Print virtual machine details
164 | Utilities.PrintVirtualMachine(windowsVM.Value);
165 |
166 | // Update - Tag the virtual machine
167 |
168 | var update = new VirtualMachinePatch
169 | {
170 | Tags =
171 | {
172 | { "who-rocks", "java" },
173 | { "where", "on azure" }
174 | }
175 | };
176 |
177 | windowsVM = await windowsVM.Value.UpdateAsync(Azure.WaitUntil.Completed, update);
178 |
179 | Utilities.Log("Tagged VM: " + windowsVM.Id);
180 |
181 | // Update - Add data disk
182 |
183 | windowsVM.Value.Data.StorageProfile.DataDisks.Add(new VirtualMachineDataDisk(3, DiskCreateOptionType.Empty) { DiskSizeGB = 10 });
184 |
185 | Utilities.Log("Added a data disk to VM" + windowsVM.Id);
186 | Utilities.PrintVirtualMachine(windowsVM.Value);
187 |
188 | // Update - detach data disk
189 | var removeDisk = windowsVM.Value.Data.StorageProfile.DataDisks.First(x => x.Lun == 0);
190 | windowsVM.Value.Data.StorageProfile.DataDisks.Remove(removeDisk);
191 |
192 | Utilities.Log("Detached data disk at lun 0 from VM " + windowsVM.Id);
193 |
194 | // Restart the virtual machine
195 |
196 | Utilities.Log("Restarting VM: " + windowsVM.Id);
197 | await windowsVM.Value.RestartAsync(Azure.WaitUntil.Completed);
198 |
199 | Utilities.Log("Restarted VM: " + windowsVM.Id);
200 |
201 | // Stop (powerOff) the virtual machine
202 |
203 | Utilities.Log("Powering OFF VM: " + windowsVM.Id);
204 |
205 | await windowsVM.Value.PowerOffAsync(Azure.WaitUntil.Completed);
206 |
207 | Utilities.Log("Powered OFF VM: " + windowsVM.Id);
208 |
209 | // Create a Linux VM in the same virtual network
210 |
211 | Utilities.Log("Creating a Network Interface #2");
212 |
213 | var nicData2 = new NetworkInterfaceData()
214 | {
215 | Location = region,
216 | /*IpConfigurations = new List
217 | {
218 | new NetworkInterfaceIPConfiguration
219 | {
220 | Name = "Primary",
221 | Primary = true,
222 | Subnet = new Subnet { Id = vnet.Subnets.First().Id },
223 | PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
224 | }
225 | }*/
226 | IPConfigurations = {
227 | new NetworkInterfaceIPConfigurationData()
228 | {
229 | Name = "Primary",
230 | Primary = true,
231 | Subnet = new SubnetData()
232 | {
233 | Id = vnet.Subnets.ElementAt(0).Id,
234 | }
235 | }
236 | }
237 | };
238 | var nic2 = (await nicCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, nicName2, nicData2)).Value;
239 |
240 | Utilities.Log("Created a Network Interface #2");
241 |
242 | Utilities.Log("Creating a Linux VM in the network");
243 |
244 | var linuxVMData = new VirtualMachineData(region)
245 | {
246 | NetworkProfile = new VirtualMachineNetworkProfile()
247 | {
248 | NetworkInterfaces =
249 | {
250 | new VirtualMachineNetworkInterfaceReference()
251 | {
252 | Id = nic2.Id,
253 | Primary = true,
254 | }
255 | }
256 | },
257 | OSProfile = new VirtualMachineOSProfile()
258 | {
259 | ComputerName = linuxVmName,
260 | AdminUsername = userName,
261 | AdminPassword = password,
262 | LinuxConfiguration = new LinuxConfiguration
263 | {
264 | DisablePasswordAuthentication = false,
265 | ProvisionVmAgent = true
266 | }
267 | },
268 | StorageProfile = new VirtualMachineStorageProfile()
269 | {
270 | ImageReference = new ImageReference
271 | {
272 | Offer = "UbuntuServer",
273 | Publisher = "Canonical",
274 | Sku = "18.04-LTS",
275 | Version = "latest"
276 | },
277 | DataDisks =
278 | {
279 | }
280 | },
281 | HardwareProfile = new VirtualMachineHardwareProfile() { VmSize = VirtualMachineSizeType.StandardD3V2 },
282 | };
283 |
284 | var linuxVM = (await collection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, linuxVmName, linuxVMData)).Value;
285 |
286 | Utilities.Log("Created a Linux VM (in the same virtual network): " + linuxVM.Id);
287 | Utilities.PrintVirtualMachine(linuxVM);
288 |
289 | // List virtual machines in the resource group
290 |
291 | Utilities.Log("Printing list of VMs =======");
292 |
293 | await foreach (var virtualMachine in collection.GetAllAsync())
294 | {
295 | Utilities.PrintVirtualMachine(virtualMachine);
296 | }
297 |
298 | // Delete the virtual machine
299 | Utilities.Log("Deleting VM: " + windowsVM.Id);
300 |
301 | await windowsVM.Value.DeleteAsync(Azure.WaitUntil.Completed);
302 |
303 | Utilities.Log("Deleted VM: " + windowsVM.Id);
304 | }
305 | finally
306 | {
307 | try
308 | {
309 | await resourceGroup.DeleteAsync(Azure.WaitUntil.Completed);
310 | }
311 | catch (NullReferenceException)
312 | {
313 | Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
314 | }
315 | catch (Exception ex)
316 | {
317 | Utilities.Log(ex);
318 | }
319 | }
320 | }
321 |
322 | public static async Task Main(string[] args)
323 | {
324 | try
325 | {
326 | // Authenticate
327 | var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
328 | var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
329 | var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
330 | var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
331 | ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
332 | ArmClient client = new ArmClient(credential, subscription);
333 |
334 | await RunSample(client);
335 | }
336 | catch (Exception ex)
337 | {
338 | Utilities.Log(ex);
339 | }
340 | }
341 | }
342 | }
343 |
--------------------------------------------------------------------------------
/samples/compute/manage-virtual-machine/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code samples will show you how to manage a Vitural Machine using Azure SDK for .NET."
8 | urlFragment: compute-manage-vm
9 | ---
10 | # Getting started - Managing Virtual Machine using Azure .NET SDK
11 |
12 | This code sample will show you how to manage a Virtual Machine using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### Compute
19 | * You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/#dotnet).
20 |
21 | ## Getting Started
22 |
23 | ### Prerequisites
24 |
25 | You will need the following values to authenticate to Azure
26 |
27 | - **Subscription ID**
28 | - **Client ID**
29 | - **Client Secret**
30 | - **Tenant ID**
31 |
32 | These values can be obtained from the portal, here's the instructions:
33 |
34 | ### Get Subscription ID
35 |
36 | 1. Login into your Azure account
37 | 2. Select Subscriptions in the left sidebar
38 | 3. Select whichever subscription is needed
39 | 4. Click on Overview
40 | 5. Copy the Subscription ID
41 |
42 | ### Get Client ID / Client Secret / Tenant ID
43 |
44 | For information on how to get Client ID, Client Secret, and Tenant ID,
45 | please refer to [this
46 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
47 |
48 | ### Setting Environment Variables
49 |
50 | After you obtained the values, you need to set the following values as
51 | your environment variables
52 |
53 | - `AZURE_CLIENT_ID`
54 | - `AZURE_CLIENT_SECRET`
55 | - `AZURE_TENANT_ID`
56 | - `AZURE_SUBSCRIPTION_ID`
57 |
58 | To set the following environment variables on your development system:
59 |
60 | Windows (Note: Administrator access is required)
61 |
62 | 1. Open the Control Panel
63 | 2. Click System Security, then System
64 | 3. Click Advanced system settings on the left
65 | 4. Inside the System Properties window, click the Environment
66 | Variables… button.
67 | 5. Click on the property you would like to change, then click the Edit…
68 | button. If the property name is not listed, then click the New…
69 | button.
70 |
71 | Linux-based OS :
72 |
73 | export AZURE_CLIENT_ID="__CLIENT_ID__"
74 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
75 | export AZURE_TENANT_ID="__TENANT_ID__"
76 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
77 |
78 | ### Installation
79 |
80 | To complete this tutorial:
81 |
82 | * Install .NET Core latest version for [Linux] or [Windows]
83 |
84 | If you don't have an Azure subscription, create a [free account] before you begin.
85 |
86 | ### Quickstart
87 |
88 | 1. Clone the repository on your machine:
89 |
90 | ```bash
91 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
92 | ```
93 |
94 | 2. Switch to the project folder:
95 | ```bash
96 | cd samples/compute/manage-virtual-machine
97 | ```
98 |
99 | 3. Replace all the `````` placeholder with a valid password in the Program.cs file.
100 |
101 | 4. Run the application with the `dotnet run` command.
102 |
103 | ## This sample shows how to do following operations to manage a Virtual Machine
104 | - Create a virtual machine with managed OS Disk
105 | - Start a virtual machine
106 | - Stop a virtual machine
107 | - Restart a virtual machine
108 | - Update a virtual machine
109 | - Tag a virtual machine (there are many possible variations here)
110 | - Attach data disks
111 | - Detach data disks
112 | - List virtual machines
113 | - Delete a virtual machine.
114 |
115 | ## More information
116 |
117 | The [Azure Compute documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
118 |
119 | This project has adopted the [Microsoft Open Source Code of Conduct].
120 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
121 |
122 |
123 | [Linux]: https://dotnet.microsoft.com/download
124 | [Windows]: https://dotnet.microsoft.com/download
125 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
126 | [Azure Portal]: https://portal.azure.com
127 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
128 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
129 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
130 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
131 |
--------------------------------------------------------------------------------
/samples/eventhub/manage-event-hub-events/ManageEventHubEvents.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/samples/eventhub/manage-event-hub-events/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License. See License.txt in the project root for license information.
3 |
4 | using Azure.Core;
5 | using Azure.Identity;
6 | using Azure.Messaging.EventHubs;
7 | using Azure.Messaging.EventHubs.Consumer;
8 | using Azure.Messaging.EventHubs.Producer;
9 | using Azure.ResourceManager;
10 | using Azure.ResourceManager.EventHubs;
11 | using Azure.ResourceManager.EventHubs.Models;
12 | using Azure.ResourceManager.Resources;
13 | using Samples.Utilities;
14 | using System;
15 | using System.Collections.Generic;
16 | using System.Text;
17 | using System.Threading;
18 | using System.Threading.Tasks;
19 |
20 | namespace ManageEventHubEvents
21 | {
22 | //Azure Event Hub sample for managing event hub models.
23 | // - Create a Event Hub namespace and an Event Hub in it
24 | // - Create Authorization Rule and get key
25 | // - Send events to Event Hub and read them
26 |
27 | public class Program
28 | {
29 | public static async Task RunSample(ArmClient client)
30 | {
31 | string location = AzureLocation.EastUS;
32 | string subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
33 | string rgName = Utilities.RandomResourceName("rgEvHb", 15);
34 | string namespaceName = Utilities.RandomResourceName("ns", 15);
35 | string eventHubName = "FirstEventHub";
36 | ResourceGroupResource resourceGroup = null;
37 |
38 | try
39 | {
40 | resourceGroup = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, rgName, new ResourceGroupData(location))).Value;
41 |
42 | // Creates a Event Hub namespace and an Event Hub in it.
43 | Utilities.Log("Creating event hub namespace and event hub");
44 |
45 | Utilities.Log("Creating a namespace");
46 |
47 | var ehNamespaceCollection = resourceGroup.GetEventHubsNamespaces();
48 | var ehNamespace = (await ehNamespaceCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, namespaceName, new EventHubsNamespaceData(AzureLocation.EastUS2))).Value;
49 |
50 | Utilities.PrintNameSpace(ehNamespace);
51 | Utilities.Log("Created a namespace");
52 |
53 | var eventHubCollection = ehNamespace.GetEventHubs();
54 | var eventHub = (await eventHubCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, eventHubName, new EventHubData()
55 | {
56 | Status = EventHubEntityStatus.Active,
57 | PartitionCount = 4,
58 | RetentionDescription = new RetentionDescription()
59 | {
60 | RetentionTimeInHours = 48,
61 | }
62 | })).Value;
63 |
64 | Utilities.Log($"Created event hub namespace {ehNamespace.Data.Name} and event hub {eventHubName}");
65 | Utilities.PrintEventHub(eventHub);
66 |
67 | // Create a Authorization Rule for Event Hub created.
68 | Utilities.Log("Creating a Authorization Rule");
69 |
70 | var listenRuleCollection = eventHub.GetEventHubAuthorizationRules();
71 | var listenRule = (await listenRuleCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, "listenrule1", new EventHubsAuthorizationRuleData()
72 | {
73 | Rights =
74 | {
75 | EventHubsAccessRight.Listen,
76 | EventHubsAccessRight.Send
77 | }
78 | })).Value;
79 |
80 | Utilities.Log("Created a Authorization Rule");
81 |
82 | // Send events using dataplane eventhub sdk.
83 | Utilities.Log("Sending events");
84 |
85 | var keys = (await listenRule.GetKeysAsync()).Value;
86 | var producerClient = new EventHubProducerClient(keys.PrimaryConnectionString, eventHubName);
87 |
88 | using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();
89 | eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes("Hello, Event Hubs!")));
90 | eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes("The middle event is this one")));
91 | eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes("Goodbye, Event Hubs!")));
92 |
93 | await producerClient.SendAsync(eventBatch);
94 |
95 | Utilities.Log("Sent events");
96 |
97 | Utilities.Log("Reading events");
98 |
99 | var consumerClient = new EventHubConsumerClient(EventHubConsumerClient.DefaultConsumerGroupName, keys.PrimaryConnectionString, eventHubName);
100 | using CancellationTokenSource cancellationSource = new CancellationTokenSource();
101 | cancellationSource.CancelAfter(TimeSpan.FromSeconds(90));
102 |
103 | int eventsRead = 0;
104 | int maximumEvents = 3;
105 |
106 | await foreach (PartitionEvent partitionEvent in consumerClient.ReadEventsAsync(cancellationSource.Token))
107 | {
108 | Utilities.Log($"Event Read: { Encoding.UTF8.GetString(partitionEvent.Data.Body.ToArray()) }");
109 | eventsRead++;
110 |
111 | if (eventsRead >= maximumEvents)
112 | {
113 | break;
114 | }
115 | }
116 | }
117 | finally
118 | {
119 | try
120 | {
121 | await resourceGroup.DeleteAsync(Azure.WaitUntil.Completed);
122 | }
123 | catch (NullReferenceException)
124 | {
125 | Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
126 | }
127 | catch (Exception ex)
128 | {
129 | Utilities.Log(ex);
130 | }
131 | }
132 | }
133 |
134 | public static async Task Main(string[] args)
135 | {
136 | try
137 | {
138 | // Authenticate
139 | var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
140 | var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
141 | var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
142 | var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
143 | ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
144 | ArmClient client = new ArmClient(credential, subscription);
145 |
146 | await RunSample(client);
147 | }
148 | catch (Exception ex)
149 | {
150 | Utilities.Log(ex);
151 | }
152 | }
153 | }
154 | }
155 |
--------------------------------------------------------------------------------
/samples/eventhub/manage-event-hub-events/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code samples will show you how to manage event hub events using Azure SDK for .NET."
8 | urlFragment: eventhub-manage-eventhub-events
9 | ---
10 | # Getting started - Managing Event Hub Events using Azure .NET SDK
11 |
12 | This code sample will show you how to manage Event Hub Events using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### EventHub
19 | * You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/#dotnet).
20 |
21 | ## Getting Started
22 |
23 | ### Prerequisites
24 |
25 | You will need the following values to authenticate to Azure
26 |
27 | - **Subscription ID**
28 | - **Client ID**
29 | - **Client Secret**
30 | - **Tenant ID**
31 |
32 | These values can be obtained from the portal, here's the instructions:
33 |
34 | ### Get Subscription ID
35 |
36 | 1. Login into your Azure account
37 | 2. Select Subscriptions in the left sidebar
38 | 3. Select whichever subscription is needed
39 | 4. Click on Overview
40 | 5. Copy the Subscription ID
41 |
42 | ### Get Client ID / Client Secret / Tenant ID
43 |
44 | For information on how to get Client ID, Client Secret, and Tenant ID,
45 | please refer to [this
46 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
47 |
48 | ### Setting Environment Variables
49 |
50 | After you obtained the values, you need to set the following values as
51 | your environment variables
52 |
53 | - `AZURE_CLIENT_ID`
54 | - `AZURE_CLIENT_SECRET`
55 | - `AZURE_TENANT_ID`
56 | - `AZURE_SUBSCRIPTION_ID`
57 |
58 | To set the following environment variables on your development system:
59 |
60 | Windows (Note: Administrator access is required)
61 |
62 | 1. Open the Control Panel
63 | 2. Click System Security, then System
64 | 3. Click Advanced system settings on the left
65 | 4. Inside the System Properties window, click the Environment
66 | Variables… button.
67 | 5. Click on the property you would like to change, then click the Edit…
68 | button. If the property name is not listed, then click the New…
69 | button.
70 |
71 | Linux-based OS :
72 |
73 | export AZURE_CLIENT_ID="__CLIENT_ID__"
74 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
75 | export AZURE_TENANT_ID="__TENANT_ID__"
76 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
77 |
78 | ### Installation
79 |
80 | To complete this tutorial:
81 |
82 | * Install .NET Core latest version for [Linux] or [Windows]
83 |
84 | If you don't have an Azure subscription, create a [free account] before you begin.
85 |
86 | ### Quickstart
87 |
88 | 1. Clone the repository on your machine:
89 |
90 | ```bash
91 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
92 | ```
93 |
94 | 2. Switch to the project folder:
95 | ```bash
96 | cd samples/eventhub/manage-event-hub-events
97 | ```
98 |
99 | 3. Run the application with the `dotnet run` command.
100 |
101 | ```console
102 | dotnet run
103 | ```
104 |
105 | ## This sample shows how to do following operations to manage Event Hub Events
106 | - Create a Event Hub namespace and an Event Hub in it.
107 | - Create Authorization Rule and get key.
108 | - Send events to Event Hub and read them.
109 |
110 | ## More information
111 |
112 | The [Azure Compute documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
113 |
114 | This project has adopted the [Microsoft Open Source Code of Conduct].
115 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
116 |
117 |
118 | [Linux]: https://dotnet.microsoft.com/download
119 | [Windows]: https://dotnet.microsoft.com/download
120 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
121 | [Azure Portal]: https://portal.azure.com
122 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
123 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
124 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
125 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
126 |
--------------------------------------------------------------------------------
/samples/eventhub/manage-event-hub-geo-disaster-recovery/ManageEventHubGeoDisasterRecovery.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/samples/eventhub/manage-event-hub-geo-disaster-recovery/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License. See License.txt in the project root for license information.
3 |
4 | using Azure;
5 | using Azure.Core;
6 | using Azure.Identity;
7 | using Azure.ResourceManager;
8 | using Azure.ResourceManager.EventHubs;
9 | using Azure.ResourceManager.EventHubs.Models;
10 | using Azure.ResourceManager.Resources;
11 | using Samples.Utilities;
12 | using System;
13 | using System.Reflection.Metadata;
14 | using System.Threading;
15 | using System.Threading.Tasks;
16 |
17 | namespace ManageEventHubGeoDisasterRecovery
18 | {
19 | public class Program
20 | {
21 | //Azure Event Hub sample for managing geo disaster recovery pairing -
22 | // - Create two event hub namespaces
23 | // - Create a pairing between two namespaces
24 | // - Create an event hub in the primary namespace and retrieve it from the secondary namespace
25 | // - Retrieve the pairing connection string
26 | // - Fail over so that secondary namespace become primary.
27 | public static async Task RunSample(ArmClient client)
28 | {
29 | string location = AzureLocation.EastUS;
30 | string subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
31 | string rgName = Utilities.RandomResourceName("rgeh", 15);
32 | string primaryNamespaceName = Utilities.RandomResourceName("ns", 15);
33 | string secondaryNamespaceName = Utilities.RandomResourceName("ns", 15);
34 | string geoDRName = Utilities.RandomResourceName("geodr", 14);
35 | string eventHubName = Utilities.RandomResourceName("eh", 14);
36 | bool isFailOverSucceeded = false;
37 | EventHubsDisasterRecoveryResource pairing = null;
38 | ResourceGroupResource resourceGroup = null;
39 | try
40 | {
41 | resourceGroup = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, rgName, new ResourceGroupData(location))).Value;
42 |
43 | // Create resource group for the namespaces and recovery pairings
44 |
45 | Utilities.Log($"Creating primary event hub namespace {primaryNamespaceName}");
46 |
47 | var nameSpaceCollection = resourceGroup.GetEventHubsNamespaces();
48 | var primaryNamespace = (await nameSpaceCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, primaryNamespaceName, new EventHubsNamespaceData(AzureLocation.SouthCentralUS))).Value;
49 |
50 | Utilities.Log("Primary event hub namespace created");
51 | Utilities.PrintNameSpace(primaryNamespace);
52 |
53 | Utilities.Log($"Creating secondary event hub namespace {primaryNamespaceName}");
54 |
55 | var secondaryNamespace = (await nameSpaceCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, secondaryNamespaceName, new EventHubsNamespaceData(AzureLocation.NorthCentralUS))).Value;
56 |
57 | Utilities.Log("Secondary event hub namespace created");
58 | Utilities.PrintNameSpace(secondaryNamespace);
59 |
60 | // Create primary and secondary namespaces and recovery pairing
61 |
62 | Utilities.Log($"Creating geo-disaster recovery pairing {geoDRName}");
63 |
64 | var disasterRecoveryCollection = primaryNamespace.GetEventHubsDisasterRecoveries();
65 | pairing = (await disasterRecoveryCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, geoDRName, new EventHubsDisasterRecoveryData()
66 | {
67 | PartnerNamespace = secondaryNamespace.Id
68 | })).Value;
69 | while (pairing.Data.ProvisioningState != EventHubsDisasterRecoveryProvisioningState.Succeeded)
70 | {
71 | Utilities.Log("Wait for create disaster recovery");
72 | Thread.Sleep(15 * 1000);
73 | if (pairing.Data.ProvisioningState == EventHubsDisasterRecoveryProvisioningState.Failed)
74 | {
75 | throw new Exception("Provisioning state of the pairing is FAILED");
76 | }
77 | }
78 |
79 | Utilities.Log($"Created geo-disaster recovery pairing {geoDRName}");
80 | Utilities.PrintDisasterRecovery(pairing);
81 |
82 | // Create an event hub and consumer group in primary namespace
83 |
84 | Utilities.Log("Creating an event hub and consumer group in primary namespace");
85 |
86 | var eventCollection = primaryNamespace.GetEventHubs();
87 | EventHubResource primaryEventHub = (await eventCollection.CreateOrUpdateAsync(WaitUntil.Completed, eventHubName, new EventHubData())).Value;
88 | var consumerGroupCollection = primaryEventHub.GetEventHubsConsumerGroups();
89 | EventHubsConsumerGroupResource consumerGroup = (await consumerGroupCollection.CreateOrUpdateAsync(WaitUntil.Completed, "consumerGrp1", new EventHubsConsumerGroupData())).Value;
90 |
91 | var eventHubInPrimaryNamespace = (await primaryEventHub.GetAsync()).Value;
92 |
93 | Utilities.Log("Created event hub and consumer group in primary namespace");
94 | Utilities.PrintNameSpace(primaryNamespace);
95 |
96 | Utilities.Log("Waiting for 60 seconds to allow metadata to sync across primary and secondary");
97 | Thread.Sleep(60 * 1000); // Wait for syncing to finish
98 |
99 | Utilities.Log("Retrieving the event hubs in secondary namespace");
100 |
101 | var eventHubInSecondaryNamespace = (await secondaryNamespace.GetAsync()).Value;
102 |
103 | Utilities.Log("Retrieved the event hubs in secondary namespace");
104 | Utilities.PrintNameSpace(eventHubInSecondaryNamespace);
105 |
106 | // Retrieving the connection string
107 |
108 | var ruleCollection = primaryNamespace.GetEventHubsNamespaceAuthorizationRules();
109 | var rules = ruleCollection.GetAll();
110 | foreach (var rule in rules)
111 | {
112 | EventHubsAccessKeys keys = await rule.GetKeysAsync();
113 | Utilities.PrintAccessKey(keys);
114 | }
115 |
116 | Utilities.Log("Initiating fail over");
117 |
118 | var failOverResult =await pairing.FailOverAsync();
119 | Thread.Sleep(10 * 1000);
120 | while ((await pairing.GetAsync()).Value.Data.ProvisioningState == EventHubsDisasterRecoveryProvisioningState.Accepted)
121 | {
122 | Utilities.Log("Wait for fail over");
123 | Thread.Sleep(10 * 1000);
124 | }
125 | if ((await pairing.GetAsync()).Value.Data.ProvisioningState == EventHubsDisasterRecoveryProvisioningState.Succeeded)
126 | {
127 | isFailOverSucceeded = true;
128 | Utilities.Log("Fail over initiated");
129 | }
130 | else
131 | {
132 | Utilities.Log("Fail over is FAILED");
133 | }
134 |
135 | }
136 | finally
137 | {
138 | try
139 | {
140 | try
141 | {
142 | // It is necessary to break pairing before deleting resource group
143 | if (pairing != null && !isFailOverSucceeded)
144 | {
145 | await pairing.BreakPairingAsync();
146 | Thread.Sleep(10 * 1000);
147 | while ((await pairing.GetAsync()).Value.Data.ProvisioningState == EventHubsDisasterRecoveryProvisioningState.Accepted)
148 | {
149 | Thread.Sleep(10 * 1000);
150 | }
151 | if ((await pairing.GetAsync()).Value.Data.ProvisioningState == EventHubsDisasterRecoveryProvisioningState.Failed)
152 | {
153 | throw new Exception("Provisioning state of the break pairing is FAILED");
154 | }
155 | }
156 | }
157 | catch (Exception ex)
158 | {
159 | Utilities.Log("Pairing breaking failed:" + ex.Message);
160 | }
161 | await resourceGroup.DeleteAsync(WaitUntil.Completed);
162 | }
163 | catch (NullReferenceException)
164 | {
165 | Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
166 | }
167 | catch (Exception ex)
168 | {
169 | Utilities.Log(ex);
170 | }
171 | }
172 | }
173 |
174 | public static async Task Main(string[] args)
175 | {
176 | try
177 | {
178 | // Authenticate
179 | var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
180 | var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
181 | var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
182 | var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
183 | ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
184 | ArmClient client = new ArmClient(credential, subscription);
185 |
186 | await RunSample(client);
187 | }
188 | catch (Exception ex)
189 | {
190 | Utilities.Log(ex);
191 | }
192 | }
193 | }
194 | }
195 |
--------------------------------------------------------------------------------
/samples/eventhub/manage-event-hub-geo-disaster-recovery/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code samples will show you how to manage event hub geo disaster recovery pairing using Azure SDK for .NET."
8 | urlFragment: eventhub-manage-eventhub-geo-recovery
9 | ---
10 | # Getting started - Managing Event Hub Geo Disaster Recovery Pairing using Azure .NET SDK
11 |
12 | This code sample will show you how to manage Event Hub Geo Disaster Recovery Pairing using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### EventHub
19 | * You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/#dotnet).
20 |
21 | ## Getting Started
22 |
23 | ### Prerequisites
24 |
25 | You will need the following values to authenticate to Azure
26 |
27 | - **Subscription ID**
28 | - **Client ID**
29 | - **Client Secret**
30 | - **Tenant ID**
31 |
32 | These values can be obtained from the portal, here's the instructions:
33 |
34 | ### Get Subscription ID
35 |
36 | 1. Login into your Azure account
37 | 2. Select Subscriptions in the left sidebar
38 | 3. Select whichever subscription is needed
39 | 4. Click on Overview
40 | 5. Copy the Subscription ID
41 |
42 | ### Get Client ID / Client Secret / Tenant ID
43 |
44 | For information on how to get Client ID, Client Secret, and Tenant ID,
45 | please refer to [this
46 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
47 |
48 | ### Setting Environment Variables
49 |
50 | After you obtained the values, you need to set the following values as
51 | your environment variables
52 |
53 | - `AZURE_CLIENT_ID`
54 | - `AZURE_CLIENT_SECRET`
55 | - `AZURE_TENANT_ID`
56 | - `AZURE_SUBSCRIPTION_ID`
57 |
58 | To set the following environment variables on your development system:
59 |
60 | Windows (Note: Administrator access is required)
61 |
62 | 1. Open the Control Panel
63 | 2. Click System Security, then System
64 | 3. Click Advanced system settings on the left
65 | 4. Inside the System Properties window, click the Environment
66 | Variables… button.
67 | 5. Click on the property you would like to change, then click the Edit…
68 | button. If the property name is not listed, then click the New…
69 | button.
70 |
71 | Linux-based OS :
72 |
73 | export AZURE_CLIENT_ID="__CLIENT_ID__"
74 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
75 | export AZURE_TENANT_ID="__TENANT_ID__"
76 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
77 |
78 | ### Installation
79 |
80 | To complete this tutorial:
81 |
82 | * Install .NET Core latest version for [Linux] or [Windows]
83 |
84 | If you don't have an Azure subscription, create a [free account] before you begin.
85 |
86 | ### Quickstart
87 |
88 | 1. Clone the repository on your machine:
89 |
90 | ```bash
91 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
92 | ```
93 |
94 | 2. Switch to the project folder:
95 | ```bash
96 | cd samples/eventhub/manage-event-hub-geo-disaster-recovery
97 | ```
98 |
99 | 3. Run the application with the `dotnet run` command.
100 |
101 | ```console
102 | dotnet run
103 | ```
104 |
105 | ## This sample shows how to do following operations to manage Event Hub Events
106 | - Create two event hub namespaces.
107 | - Create a pairing between two namespaces.
108 | - Create an event hub in the primary namespace and retrieve it from the secondary namespace.
109 | - Retrieve the pairing connection string.
110 | - Fail over so that secondary namespace become primary.
111 |
112 | ## More information
113 |
114 | The [Azure Compute documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
115 |
116 | This project has adopted the [Microsoft Open Source Code of Conduct].
117 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
118 |
119 |
120 | [Linux]: https://dotnet.microsoft.com/download
121 | [Windows]: https://dotnet.microsoft.com/download
122 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
123 | [Azure Portal]: https://portal.azure.com
124 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
125 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
126 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
127 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
128 |
--------------------------------------------------------------------------------
/samples/eventhub/manage-event-hub/ManageEventHub.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/samples/eventhub/manage-event-hub/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License. See License.txt in the project root for license information.
3 |
4 | using Azure;
5 | using Azure.Core;
6 | using Azure.Identity;
7 | using Azure.ResourceManager;
8 | using Azure.ResourceManager.EventHubs;
9 | using Azure.ResourceManager.EventHubs.Models;
10 | using Azure.ResourceManager.Resources;
11 | using Azure.ResourceManager.Resources.Models;
12 | using Azure.ResourceManager.Storage;
13 | using Azure.ResourceManager.Storage.Models;
14 | using Samples.Utilities;
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Threading.Tasks;
18 |
19 | namespace ManageEventHub
20 | {
21 | // Azure Event Hub sample for managing event hub -
22 | // - Create an event hub namespace
23 | // - Create an event hub in the namespace with data capture enabled along with a consumer group and rule
24 | // - List consumer groups in the event hub
25 | // - Create a second event hub in the namespace
26 | // - Create a consumer group in the second event hub
27 | // - List consumer groups in the second event hub
28 | // - Create an event hub namespace along with event hub.
29 |
30 | public class Program
31 | {
32 | public static async Task RunSample(ArmClient client)
33 | {
34 | string location = AzureLocation.EastUS;
35 | string subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
36 | string rgName = Utilities.RandomResourceName("rgeh", 15);
37 | string namespaceName1 = Utilities.RandomResourceName("ns", 15);
38 | string namespaceName2 = Utilities.RandomResourceName("ns", 15);
39 | string storageAccountName = Utilities.RandomResourceName("stg", 14);
40 | string eventHubName1 = Utilities.RandomResourceName("eh", 14);
41 | string eventHubName2 = Utilities.RandomResourceName("eh", 14);
42 | ResourceGroupResource resourceGroup = null;
43 | try
44 | {
45 | resourceGroup = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, rgName, new ResourceGroupData(location))).Value;
46 |
47 | // Create an event hub namespace
48 |
49 | Utilities.Log("Creating a namespace");
50 | EventHubsNamespaceCollection namespaceCollection = resourceGroup.GetEventHubsNamespaces();
51 | EventHubsNamespaceResource eventHubNamespace = (await namespaceCollection.CreateOrUpdateAsync(WaitUntil.Completed, namespaceName1, new EventHubsNamespaceData(location))).Value;
52 |
53 | Utilities.PrintNameSpace(eventHubNamespace);
54 | Utilities.Log("Created a namespace");
55 |
56 | // Create an event hub in the namespace with data capture enabled, with consumer group and auth rule
57 |
58 | GenericResourceData input = new GenericResourceData(AzureLocation.EastUS2)
59 | {
60 | Sku = new ResourcesSku
61 | {
62 | Name = "Standard_LRS"
63 | },
64 | Kind = "StorageV2",
65 | };
66 | ResourceIdentifier storageAccountId = resourceGroup.Id.AppendProviderResource("Microsoft.Storage", "storageAccounts", storageAccountName);
67 | GenericResource account = (await client.GetGenericResources().CreateOrUpdateAsync(WaitUntil.Completed, storageAccountId, input)).Value;
68 |
69 | //create eventhub with Cleanup policy Compaction.
70 | EventHubData parameter = new EventHubData()
71 | {
72 | PartitionCount = 4,
73 | Status = EventHubEntityStatus.Active,
74 | CaptureDescription = new CaptureDescription()
75 | {
76 | Enabled = true,
77 | Encoding = EncodingCaptureDescription.Avro,
78 | IntervalInSeconds = 120,
79 | SizeLimitInBytes = 10485763,
80 | Destination = new EventHubDestination()
81 | {
82 | Name = "EventHubArchive.AzureBlockBlob",
83 | BlobContainer = "container",
84 | ArchiveNameFormat = "{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}",
85 | StorageAccountResourceId = new ResourceIdentifier(account.Id.ToString())
86 | }
87 | },
88 | };
89 | var eventCollection = eventHubNamespace.GetEventHubs();
90 | EventHubResource eventHub = (await eventCollection.CreateOrUpdateAsync(WaitUntil.Completed, eventHubName1, parameter)).Value;
91 | // Optional - create one consumer group in event hub
92 | var consumerGroupCollection = eventHub.GetEventHubsConsumerGroups();
93 | EventHubsConsumerGroupResource consumerGroup = (await consumerGroupCollection.CreateOrUpdateAsync(WaitUntil.Completed, "cg1", new EventHubsConsumerGroupData())).Value;
94 | // Optional - create an authorization rule for event hub
95 | EventHubsNamespaceAuthorizationRuleCollection collection = eventHubNamespace.GetEventHubsNamespaceAuthorizationRules();
96 | var listenRuleData1 = new EventHubsAuthorizationRuleData()
97 | {
98 | Rights =
99 | {
100 | EventHubsAccessRight.Listen,EventHubsAccessRight.Send
101 | }
102 | };
103 | var listenRule1 = (await collection.CreateOrUpdateAsync(WaitUntil.Completed, "listenrule1", listenRuleData1)).Value;
104 |
105 | // Retrieve consumer groups in the event hub
106 | Utilities.Log("Retrieving consumer groups");
107 |
108 | var consumerGroups = consumerGroupCollection.GetAll();
109 |
110 | Utilities.Log("Retrieved consumer groups");
111 |
112 | foreach (var group in consumerGroups)
113 | {
114 | Utilities.PrintConsumerGroup(group);
115 | }
116 |
117 | // Create another event hub in the namespace
118 |
119 | Utilities.Log("Creating another event hub in the namespace");
120 |
121 | var eventHub2 = (await eventCollection.CreateOrUpdateAsync(WaitUntil.Completed, eventHubName2, new EventHubData())).Value;
122 |
123 | Utilities.Log("Created second event hub");
124 | Utilities.PrintEventHub(eventHub2);
125 |
126 | // Create a consumer group in the event hub
127 |
128 | Utilities.Log("Creating a consumer group in the second event hub");
129 |
130 | var consumerGroupCollection2 = eventHub2.GetEventHubsConsumerGroups();
131 | var consumerGroup2 = (await consumerGroupCollection2.CreateOrUpdateAsync(WaitUntil.Completed, "cg2", new EventHubsConsumerGroupData()
132 | {
133 | UserMetadata = "sometadata"
134 | })).Value;
135 |
136 | Utilities.PrintConsumerGroup(consumerGroup2);
137 |
138 | // Retrieve consumer groups in the event hub
139 | Utilities.Log("Retrieving consumer groups in the second event hub");
140 |
141 | var listResult2 = consumerGroupCollection2.GetAll();
142 |
143 | Utilities.Log("Retrieved consumer groups in the seoond event hub");
144 |
145 | foreach (var group in listResult2)
146 | {
147 | Utilities.PrintConsumerGroup(group);
148 | }
149 |
150 | // Create an event hub namespace with event hub
151 |
152 | Utilities.Log("Creating an event hub namespace along with event hub");
153 |
154 | var namespace2 = (await namespaceCollection.CreateOrUpdateAsync(WaitUntil.Completed, namespaceName2, new EventHubsNamespaceData(location))).Value;
155 |
156 | var eventHubCollection = namespace2.GetEventHubs();
157 | var newEventHub2 = (await eventHubCollection.CreateOrUpdateAsync(WaitUntil.Completed, namespaceName2, new EventHubData())).Value;
158 |
159 | Utilities.Log("Created an event hub namespace along with event hub");
160 | Utilities.PrintNameSpace(namespace2);
161 |
162 | await foreach (var eh in eventHubCollection.GetAllAsync())
163 | {
164 | Utilities.PrintEventHub(eh);
165 | }
166 |
167 | }
168 | finally
169 | {
170 | try
171 | {
172 | await resourceGroup.DeleteAsync(WaitUntil.Completed);
173 | }
174 | catch (NullReferenceException)
175 | {
176 | Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
177 | }
178 | catch (Exception ex)
179 | {
180 | Utilities.Log(ex);
181 | }
182 | }
183 | }
184 |
185 | public static async Task Main(string[] args)
186 | {
187 | try
188 | {
189 | // Authenticate
190 | var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
191 | var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
192 | var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
193 | var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
194 | ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
195 | ArmClient client = new ArmClient(credential, subscription);
196 |
197 | await RunSample(client);
198 | }
199 | catch (Exception ex)
200 | {
201 | Utilities.Log(ex);
202 | }
203 | }
204 | }
205 | }
206 |
--------------------------------------------------------------------------------
/samples/eventhub/manage-event-hub/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code samples will show you how to manage event hub using Azure SDK for .NET."
8 | urlFragment: eventhub-manage-eventhub
9 | ---
10 | # Getting started - Managing Event Hub using Azure .NET SDK
11 |
12 | This code sample will show you how to manage Event Hub using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### EventHub
19 | * You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/#dotnet).
20 |
21 | ## Getting Started
22 |
23 | ### Prerequisites
24 |
25 | You will need the following values to authenticate to Azure
26 |
27 | - **Subscription ID**
28 | - **Client ID**
29 | - **Client Secret**
30 | - **Tenant ID**
31 |
32 | These values can be obtained from the portal, here's the instructions:
33 |
34 | ### Get Subscription ID
35 |
36 | 1. Login into your Azure account
37 | 2. Select Subscriptions in the left sidebar
38 | 3. Select whichever subscription is needed
39 | 4. Click on Overview
40 | 5. Copy the Subscription ID
41 |
42 | ### Get Client ID / Client Secret / Tenant ID
43 |
44 | For information on how to get Client ID, Client Secret, and Tenant ID,
45 | please refer to [this
46 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
47 |
48 | ### Setting Environment Variables
49 |
50 | After you obtained the values, you need to set the following values as
51 | your environment variables
52 |
53 | - `AZURE_CLIENT_ID`
54 | - `AZURE_CLIENT_SECRET`
55 | - `AZURE_TENANT_ID`
56 | - `AZURE_SUBSCRIPTION_ID`
57 |
58 | To set the following environment variables on your development system:
59 |
60 | Windows (Note: Administrator access is required)
61 |
62 | 1. Open the Control Panel
63 | 2. Click System Security, then System
64 | 3. Click Advanced system settings on the left
65 | 4. Inside the System Properties window, click the Environment
66 | Variables… button.
67 | 5. Click on the property you would like to change, then click the Edit…
68 | button. If the property name is not listed, then click the New…
69 | button.
70 |
71 | Linux-based OS :
72 |
73 | export AZURE_CLIENT_ID="__CLIENT_ID__"
74 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
75 | export AZURE_TENANT_ID="__TENANT_ID__"
76 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
77 |
78 | ### Installation
79 |
80 | To complete this tutorial:
81 |
82 | * Install .NET Core latest version for [Linux] or [Windows]
83 |
84 | If you don't have an Azure subscription, create a [free account] before you begin.
85 |
86 | ### Quickstart
87 |
88 | 1. Clone the repository on your machine:
89 |
90 | ```bash
91 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
92 | ```
93 |
94 | 2. Switch to the project folder:
95 | ```bash
96 | cd samples/eventhub/manage-event-hub
97 | ```
98 |
99 | 3. Run the application with the `dotnet run` command.
100 |
101 | ```console
102 | dotnet run
103 | ```
104 |
105 | ## This sample shows how to do following operations to manage Event Hub
106 | - Create an event hub namespace.
107 | - Create an event hub in the namespace with data capture enabled along with a consumer group and rule.
108 | - List consumer groups in the event hub.
109 | - Create a second event hub in the namespace.
110 | - Create a consumer group in the second event hub.
111 | - List consumer groups in the second event hub.
112 | - Create an event hub namespace along with event hub.
113 |
114 | ## More information
115 |
116 | The [Azure Compute documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
117 |
118 | This project has adopted the [Microsoft Open Source Code of Conduct].
119 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
120 |
121 |
122 | [Linux]: https://dotnet.microsoft.com/download
123 | [Windows]: https://dotnet.microsoft.com/download
124 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
125 | [Azure Portal]: https://portal.azure.com
126 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
127 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
128 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
129 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
130 |
--------------------------------------------------------------------------------
/samples/keyvault/manage-key-vault/ManageKeyVault.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/samples/keyvault/manage-key-vault/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License. See License.txt in the project root for license information.
3 |
4 | using Azure.Core;
5 | using Azure.Identity;
6 | using Azure.ResourceManager;
7 | using Azure.ResourceManager.KeyVault;
8 | using Azure.ResourceManager.KeyVault.Models;
9 | using Azure.ResourceManager.Resources;
10 | using Samples.Utilities;
11 | using System;
12 | using System.Collections.Generic;
13 | using System.Linq;
14 | using System.Threading.Tasks;
15 |
16 | namespace ManageKeyVault
17 | {
18 | public class Program
19 | {
20 | //Azure Key Vault sample for managing key vaults -
21 | // - Create a key vault
22 | // - Authorize an application
23 | // - Update a key vault
24 | // - alter configurations
25 | // - change permissions
26 | // - Create another key vault
27 | // - List key vaults
28 | // - Delete a key vault.
29 | public static async Task RunSample(ArmClient client)
30 | {
31 | string subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
32 | Guid tenantId = new Guid(Environment.GetEnvironmentVariable("AZURE_TENANT_ID"));
33 | // Please pre-define the Client's Object in Environment Variable settings
34 | string objectId = Environment.GetEnvironmentVariable("AZURE_OBJECT_ID");
35 | string vaultName1 = Utilities.RandomResourceName("vault1", 20);
36 | string vaultName2 = Utilities.RandomResourceName("vault2", 20);
37 | string rgName = Utilities.RandomResourceName("rgNEMV", 24);
38 | string location = AzureLocation.EastUS;
39 | ResourceGroupResource resourceGroup = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, rgName, new ResourceGroupData(location))).Value;
40 |
41 | try
42 | {
43 | // Create a key vault with empty access policy
44 |
45 | Utilities.Log("Creating a key vault...");
46 |
47 | var vaultCollection = resourceGroup.GetKeyVaults();
48 | var vaultProperties = new KeyVaultProperties(tenantId, new KeyVaultSku(KeyVaultSkuFamily.A, KeyVaultSkuName.Standard))
49 | {
50 | AccessPolicies =
51 | {
52 | new KeyVaultAccessPolicy(tenantId, objectId, new IdentityAccessPermissions())
53 | }
54 | };
55 | KeyVaultCreateOrUpdateContent parameters = new KeyVaultCreateOrUpdateContent(location, vaultProperties);
56 | var keyVault = (await vaultCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, vaultName1, parameters)).Value;
57 |
58 | Utilities.Log("Created key vault");
59 | Utilities.PrintVault(keyVault);
60 |
61 | // Authorize an application
62 |
63 | Utilities.Log("Authorizing the application associated with the current service principal...");
64 |
65 | IEnumerable policies = new List();
66 | {
67 | new KeyVaultAccessPolicy(tenantId, objectId, new IdentityAccessPermissions()
68 | {
69 | Keys =
70 | {
71 | IdentityAccessKeyPermission.All
72 | },
73 | Secrets =
74 | {
75 | IdentityAccessSecretPermission.Get,
76 | IdentityAccessSecretPermission.List
77 |
78 | }
79 | });
80 | }
81 | var UpdateProperties = new KeyVaultAccessPolicyProperties(policies);
82 | var UpdateAccessPolicy = (await keyVault.UpdateAccessPolicyAsync(AccessPolicyUpdateKind.Add, new KeyVaultAccessPolicyParameters(UpdateProperties))).Value;
83 | var UpdateKeyVault = await keyVault.UpdateAsync(new KeyVaultPatch()
84 | {
85 | Properties = new KeyVaultPatchProperties()
86 | {
87 | AccessPolicies =
88 | {
89 | UpdateAccessPolicy.AccessPolicies.ElementAt(0)
90 | }
91 | }
92 | });
93 |
94 | Utilities.Log("Updated key vault");
95 | Utilities.PrintVault(UpdateKeyVault.Value);
96 |
97 | // Update a key vault
98 |
99 | Utilities.Log("Update a key vault to enable deployments and add permissions to the application...");
100 |
101 | var permissions = new IdentityAccessPermissions()
102 | {
103 | Secrets =
104 | {
105 | IdentityAccessSecretPermission.All
106 | }
107 | };
108 | var patch = new KeyVaultPatch()
109 | {
110 | Properties = new KeyVaultPatchProperties()
111 | {
112 | EnabledForDeployment = true,
113 | EnabledForTemplateDeployment = true,
114 | AccessPolicies =
115 | {
116 | new KeyVaultAccessPolicy(tenantId, objectId, permissions)
117 | }
118 | },
119 | };
120 | var UpdateKeyVault2 = await keyVault.UpdateAsync(patch);
121 |
122 | Utilities.Log("Updated key vault");
123 |
124 | Utilities.PrintVault(UpdateKeyVault2);
125 |
126 | // Create another key vault
127 |
128 | Utilities.Log("Create another key vault");
129 |
130 | permissions = new IdentityAccessPermissions()
131 | {
132 | Keys =
133 | {
134 | IdentityAccessKeyPermission.Get
135 | },
136 | Secrets =
137 | {
138 | IdentityAccessSecretPermission.List,
139 | IdentityAccessSecretPermission.Get,
140 | IdentityAccessSecretPermission.Purge
141 | }
142 | };
143 | //accessPolicyEntry = new AccessPolicyEntry(tenantId, objectId, permissions);
144 | var vaultProperties2 = new KeyVaultProperties(tenantId, new KeyVaultSku(KeyVaultSkuFamily.A, KeyVaultSkuName.Standard))
145 | {
146 | AccessPolicies =
147 | {
148 | new KeyVaultAccessPolicy(tenantId, objectId, permissions)
149 | }
150 | };
151 | var vaultParameters2 = new KeyVaultCreateOrUpdateContent(location, vaultProperties2);
152 |
153 | var rawResult = await vaultCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, vaultName2, vaultParameters2);
154 | var keyvault2 = rawResult.Value;
155 |
156 | Utilities.Log("Created key vault");
157 | // Print the network security group
158 | Utilities.PrintVault(keyvault2);
159 |
160 | // List key vaults
161 |
162 | Utilities.Log("Listing key vaults...");
163 |
164 | await foreach (var vault in vaultCollection.GetAllAsync())
165 | {
166 | Utilities.PrintVault(vault);
167 | }
168 |
169 | // Delete key vaults
170 | Utilities.Log("Deleting the key vaults");
171 | await keyVault.DeleteAsync(Azure.WaitUntil.Completed);
172 | await keyvault2.DeleteAsync(Azure.WaitUntil.Completed);
173 | Utilities.Log("Deleted the key vaults");
174 | }
175 | finally
176 | {
177 | try
178 | {
179 | await resourceGroup.DeleteAsync(Azure.WaitUntil.Completed);
180 | }
181 | catch (NullReferenceException)
182 | {
183 | Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
184 | }
185 | catch (Exception ex)
186 | {
187 | Utilities.Log(ex);
188 | }
189 | }
190 |
191 |
192 | }
193 |
194 | public static async Task Main(string[] args)
195 | {
196 | try
197 | {
198 | // Authenticate
199 | var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
200 | var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
201 | var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
202 | var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
203 | ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
204 | ArmClient client = new ArmClient(credential, subscription);
205 |
206 | await RunSample(client);
207 | }
208 | catch (Exception ex)
209 | {
210 | Utilities.Log(ex);
211 | }
212 | }
213 | }
214 | }
215 |
--------------------------------------------------------------------------------
/samples/keyvault/manage-key-vault/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code samples will show you how to manage keyvault using Azure SDK for .NET."
8 | urlFragment: keyvault-manage-keyvault
9 | ---
10 | # Getting started - Managing KeyVault using Azure .NET SDK
11 |
12 | This code sample will show you how to manage KeyVault using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### KeyVault
19 | * You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/#dotnet).
20 |
21 | ## Getting Started
22 |
23 | ### Prerequisites
24 |
25 | You will need the following values to authenticate to Azure
26 |
27 | - **Subscription ID**
28 | - **Client ID**
29 | - **Client Secret**
30 | - **Tenant ID**
31 |
32 | These values can be obtained from the portal, here's the instructions:
33 |
34 | ### Get Subscription ID
35 |
36 | 1. Login into your Azure account
37 | 2. Select Subscriptions in the left sidebar
38 | 3. Select whichever subscription is needed
39 | 4. Click on Overview
40 | 5. Copy the Subscription ID
41 |
42 | ### Get Client ID / Client Secret / Tenant ID
43 |
44 | For information on how to get Client ID, Client Secret, and Tenant ID,
45 | please refer to [this
46 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
47 |
48 | ### Setting Environment Variables
49 |
50 | After you obtained the values, you need to set the following values as
51 | your environment variables
52 |
53 | - `AZURE_CLIENT_ID`
54 | - `AZURE_CLIENT_SECRET`
55 | - `AZURE_TENANT_ID`
56 | - `AZURE_SUBSCRIPTION_ID`
57 |
58 | To set the following environment variables on your development system:
59 |
60 | Windows (Note: Administrator access is required)
61 |
62 | 1. Open the Control Panel
63 | 2. Click System Security, then System
64 | 3. Click Advanced system settings on the left
65 | 4. Inside the System Properties window, click the Environment
66 | Variables… button.
67 | 5. Click on the property you would like to change, then click the Edit…
68 | button. If the property name is not listed, then click the New…
69 | button.
70 |
71 | Linux-based OS :
72 |
73 | export AZURE_CLIENT_ID="__CLIENT_ID__"
74 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
75 | export AZURE_TENANT_ID="__TENANT_ID__"
76 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
77 |
78 | ### Installation
79 |
80 | To complete this tutorial:
81 |
82 | * Install .NET Core latest version for [Linux] or [Windows]
83 |
84 | If you don't have an Azure subscription, create a [free account] before you begin.
85 |
86 | ### Quickstart
87 |
88 | 1. Clone the repository on your machine:
89 |
90 | ```bash
91 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
92 | ```
93 |
94 | 2. Switch to the project folder:
95 | ```bash
96 | cd samples/keyvault/manage-key-vault
97 | ```
98 |
99 | 3. Run the application with the `dotnet run` command.
100 |
101 | ```console
102 | dotnet run
103 | ```
104 |
105 | ## This sample shows how to do following operations to manage KeyVault
106 | - Create a key vault.
107 | - Authorize an application.
108 | - Update a key vault.
109 | - alter configurations.
110 | - change permissions.
111 | - Create another key vault.
112 | - List key vaults.
113 | - Delete a key vault.
114 |
115 | ## More information
116 |
117 | The [Azure Compute documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
118 |
119 | This project has adopted the [Microsoft Open Source Code of Conduct].
120 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
121 |
122 |
123 | [Linux]: https://dotnet.microsoft.com/download
124 | [Windows]: https://dotnet.microsoft.com/download
125 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
126 | [Azure Portal]: https://portal.azure.com
127 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
128 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
129 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
130 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
131 |
--------------------------------------------------------------------------------
/samples/network/manage-ip-address/ManageIPAddress.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/samples/network/manage-ip-address/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License. See License.txt in the project root for license information.
3 |
4 | using Azure.Core;
5 | using Azure.Identity;
6 | using Azure.ResourceManager;
7 | using Azure.ResourceManager.Resources;
8 | using Azure.ResourceManager.Compute;
9 | using Azure.ResourceManager.Compute.Models;
10 | using Azure.ResourceManager.Network;
11 | using Azure.ResourceManager.Network.Models;
12 | using System;
13 | using System.Collections.Generic;
14 | using System.Linq;
15 | using System.Threading.Tasks;
16 |
17 | namespace ManageIPAddress
18 | {
19 | public class Program
20 | {
21 | //Azure Network sample for managing IP address -
22 | // - Assign a public IP address for a virtual machine during its creation
23 | // - Assign a public IP address for a virtual machine through an virtual machine update action
24 | // - Get the associated public IP address for a virtual machine
25 | // - Get the assigned public IP address for a virtual machine
26 | // - Remove a public IP address from a virtual machine.
27 |
28 |
29 | public static async Task RunSample()
30 | {
31 | const string UserName = "tirekicker";
32 | const string Password = ""; // replace with a password following the policy
33 | const string PublicIPAddressName1 = "pip1";
34 | const string PublicIPAddressName2 = "pip2";
35 | const string PublicIPAddressLeafDNS1 = "pipdns1";
36 | const string PublicIPAddressLeafDNS2 = "pipdns2";
37 | const string NetworkInterfaceName = "nic";
38 | const string VmName = "vm";
39 | const string ResourceGroupName = "rgNEMP";
40 | var location = AzureLocation.EastUS;
41 |
42 | // create an ArmClient as the entry of all resource management API
43 | var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
44 | var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
45 | var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
46 | var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
47 | ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
48 | ArmClient client = new ArmClient(credential, subscription);
49 |
50 | // implicit conversion from Resource to ResourceGroup, similar cases can be found below
51 | ResourceGroupResource resourceGroup = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, ResourceGroupName, new ResourceGroupData(location))).Value;
52 |
53 | // Assign a public IP address for a VM during its creation
54 |
55 | // Define a public IP address to be used during VM creation time
56 |
57 | Console.WriteLine("Creating a public IP address...");
58 | var publicIPAddressData = new PublicIPAddressData()
59 | {
60 | PublicIPAddressVersion = NetworkIPVersion.IPv4,
61 | PublicIPAllocationMethod = NetworkIPAllocationMethod.Dynamic,
62 | Location = location,
63 | DnsSettings = new PublicIPAddressDnsSettings
64 | {
65 | DomainNameLabel = PublicIPAddressLeafDNS1
66 | }
67 | };
68 |
69 | var publicIPAddressContainer = resourceGroup.GetPublicIPAddresses();
70 | var publicIPAddress = (await publicIPAddressContainer.CreateOrUpdateAsync(Azure.WaitUntil.Completed, PublicIPAddressName1, publicIPAddressData)).Value;
71 | Console.WriteLine($"Created a public IP address {publicIPAddress.Id}");
72 |
73 | // Use the pre-created public IP for the new VM
74 | Console.WriteLine("Creating a Virtual Network");
75 | var vnetData = new VirtualNetworkData()
76 | {
77 | Location = location,
78 | AddressPrefixes =
79 | {
80 | "10.0.0.0/16"
81 | },
82 | Subnets =
83 | {
84 | new SubnetData
85 | {
86 | Name = "mySubnet",
87 | AddressPrefix = "10.0.0.0/28",
88 | }
89 | },
90 | };
91 |
92 | var virtualNetworkContainer = resourceGroup.GetVirtualNetworks();
93 | var vnet = (await virtualNetworkContainer.CreateOrUpdateAsync(Azure.WaitUntil.Completed, $"{VmName}_vent", vnetData)).Value;
94 | Console.WriteLine($"Created a Virtual Network {vnet.Id}");
95 |
96 | Console.WriteLine("Creating a Network Interface");
97 | var networkInterfaceData = new NetworkInterfaceData()
98 | {
99 | Location = location,
100 | IPConfigurations =
101 | {
102 | new NetworkInterfaceIPConfigurationData
103 | {
104 | Name = "Primary",
105 | Primary = true,
106 | Subnet = new SubnetData() { Id = vnet.Data.Subnets.First().Id },
107 | PrivateIPAllocationMethod = NetworkIPAllocationMethod.Dynamic,
108 | PublicIPAddress = new PublicIPAddressData() { Id = publicIPAddress.Id }
109 | }
110 | }
111 | };
112 |
113 | var networkInterfaceContainer = resourceGroup.GetNetworkInterfaces();
114 | var networkInterface = (await networkInterfaceContainer.CreateOrUpdateAsync(Azure.WaitUntil.Completed, NetworkInterfaceName, networkInterfaceData)).Value;
115 | Console.WriteLine($"Created a Network Interface {networkInterface.Id}");
116 |
117 | Console.WriteLine("Creating a Windows VM");
118 | var t1 = DateTime.UtcNow;
119 |
120 | var vmData = new VirtualMachineData(location)
121 | {
122 | NetworkProfile = new VirtualMachineNetworkProfile()
123 | {
124 | NetworkInterfaces =
125 | {
126 | new VirtualMachineNetworkInterfaceReference() { Id = networkInterface.Id }
127 | }
128 | },
129 | OSProfile = new VirtualMachineOSProfile()
130 | {
131 | ComputerName = VmName,
132 | AdminUsername = UserName,
133 | AdminPassword = Password,
134 | },
135 | StorageProfile = new VirtualMachineStorageProfile()
136 | {
137 | ImageReference = new ImageReference()
138 | {
139 | Offer = "WindowsServer",
140 | Publisher = "MicrosoftWindowsServer",
141 | Sku = "2016-Datacenter",
142 | Version = "latest"
143 | },
144 | },
145 | HardwareProfile = new VirtualMachineHardwareProfile() { VmSize = VirtualMachineSizeType.StandardD3V2 },
146 | };
147 |
148 | var virtualMachineContainer = resourceGroup.GetVirtualMachines();
149 | var vm = (await virtualMachineContainer.CreateOrUpdateAsync(Azure.WaitUntil.Completed, VmName, vmData)).Value;
150 |
151 | var t2 = DateTime.UtcNow;
152 | Console.WriteLine($"Created VM: (took {(t2 - t1).TotalSeconds} seconds) {vmData.Id}");
153 |
154 | // Assign a new public IP address for the VM
155 | // Define a new public IP address
156 | Console.WriteLine("Creating a public IP address...");
157 | var publicIPAddressData2 = new PublicIPAddressData()
158 | {
159 | PublicIPAddressVersion = NetworkIPVersion.IPv4,
160 | PublicIPAllocationMethod = NetworkIPAllocationMethod.Dynamic,
161 | Location = location,
162 | DnsSettings = new PublicIPAddressDnsSettings
163 | {
164 | DomainNameLabel = PublicIPAddressLeafDNS2
165 | }
166 | };
167 |
168 | var publicIPAddress2 = (await publicIPAddressContainer.CreateOrUpdateAsync(Azure.WaitUntil.Completed, PublicIPAddressName2, publicIPAddressData2)).Value;
169 | Console.WriteLine($"Created a public IP address {publicIPAddress.Id}");
170 |
171 | // Update VM's primary NIC to use the new public IP address
172 | Console.WriteLine("Updating the VM's primary NIC with new public IP address");
173 | networkInterfaceData = new NetworkInterfaceData
174 | {
175 | Location = location,
176 | IPConfigurations =
177 | {
178 | new NetworkInterfaceIPConfigurationData
179 | {
180 | Name = "Primary",
181 | Primary = true,
182 | Subnet = new SubnetData() { Id = vnet.Data.Subnets.First().Id },
183 | PrivateIPAllocationMethod = NetworkIPAllocationMethod.Dynamic,
184 | PublicIPAddress = new PublicIPAddressData() { Id = publicIPAddress2.Id }
185 | }
186 | }
187 | };
188 | var networkInterfaceUpdate = (await networkInterfaceContainer.CreateOrUpdateAsync(Azure.WaitUntil.Completed, NetworkInterfaceName, networkInterfaceData)).Value;
189 | Console.WriteLine("New public IP address associated with the VM's primary NIC");
190 |
191 | // Remove public IP associated with the VM
192 | Console.WriteLine("Removing public IP address associated with the VM");
193 | networkInterfaceData = new NetworkInterfaceData
194 | {
195 | Location = location,
196 | IPConfigurations =
197 | {
198 | new NetworkInterfaceIPConfigurationData
199 | {
200 | Name = "Primary",
201 | Primary = true,
202 | Subnet = new SubnetData() { Id = vnet.Data.Subnets.First().Id },
203 | PrivateIPAllocationMethod = NetworkIPAllocationMethod.Dynamic,
204 | }
205 | }
206 | };
207 |
208 | var networkInterFaceRemove = (await networkInterfaceContainer.CreateOrUpdateAsync(Azure.WaitUntil.Completed, NetworkInterfaceName, networkInterfaceData)).Value;
209 | Console.WriteLine("Removed public IP address associated with the VM");
210 |
211 | // Delete the public ip
212 | Console.WriteLine("Deleting the public IP addresses");
213 | await publicIPAddress.DeleteAsync(Azure.WaitUntil.Completed);
214 | Console.WriteLine("Deleted the public IP addresses");
215 |
216 | // Delete resource group if necessary
217 | // await resourceGroup.Delete().WaitForCompletionResponseAsync();
218 | }
219 |
220 | public static async Task Main(string[] args)
221 | {
222 | try
223 | {
224 | await RunSample();
225 | }
226 | catch (Exception ex)
227 | {
228 | Console.WriteLine(ex);
229 | }
230 | }
231 | }
232 | }
233 |
--------------------------------------------------------------------------------
/samples/network/manage-ip-address/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code samples will show you how to manage ip address using Azure SDK for .NET."
8 | urlFragment: network-manage-ip-address
9 | ---
10 | # Getting started - Managing IP Address using Azure .NET SDK
11 |
12 | This code sample will show you how to manage IP Address using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### Network
19 |
20 | - You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/mgmt/dotnet.html).
21 |
22 | ## Getting Started
23 |
24 | ### Prerequisites
25 |
26 | You will need the following values to authenticate to Azure
27 |
28 | - **Subscription ID**
29 | - **Client ID**
30 | - **Client Secret**
31 | - **Tenant ID**
32 |
33 | These values can be obtained from the portal, here's the instructions:
34 |
35 | #### Get Subscription ID
36 |
37 | 1. Login into your Azure account
38 | 2. Select `Subscriptions` under `Navigation` section in the portal
39 | 3. Select whichever subscription is needed
40 | 4. Click on `Overview`
41 | 5. Copy the `Subscription ID`
42 |
43 | #### Get Client ID / Client Secret / Tenant ID
44 |
45 | For information on how to get Client ID, Client Secret, and Tenant ID,
46 | please refer to [this
47 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
48 |
49 | ### Setting Environment Variables
50 |
51 | After you obtained the values, you need to set the following values as
52 | your environment variables
53 |
54 | - `AZURE_CLIENT_ID`
55 | - `AZURE_CLIENT_SECRET`
56 | - `AZURE_TENANT_ID`
57 | - `AZURE_SUBSCRIPTION_ID`
58 |
59 | To set the following environment variables on your development system:
60 |
61 | Windows: (Note: Administrator access is required)
62 |
63 | 1. Open the System Control Panel
64 | 2. Select `Advanced system settings`
65 | 3. Open the `Advanced` tab, then click `Environment Variables...`
66 | button.
67 | 4. Click on the property you would like to change, then click the `Edit…`
68 | button. If the property name is not listed, then click the `New…`
69 | button.
70 |
71 | Linux-based OS :
72 |
73 | ```bash
74 | export AZURE_CLIENT_ID="__CLIENT_ID__"
75 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
76 | export AZURE_TENANT_ID="__TENANT_ID__"
77 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
78 | ```
79 |
80 | ### Installation
81 |
82 | To complete this tutorial:
83 |
84 | - Install .NET Core latest version for [Linux] or [Windows]
85 |
86 | If you don't have an Azure subscription, create a [free account] before you begin.
87 |
88 | ### Quickstart
89 |
90 | 1. Clone the repository on your machine:
91 |
92 | ```bash
93 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
94 | ```
95 |
96 | 2. Switch to the project folder:
97 |
98 | ```bash
99 | cd samples/network/manage-ip-address
100 | ```
101 |
102 | 3. Replace all the `````` placeholder with a valid password in the Program.cs file.
103 | 4. Run the application with the `dotnet run` command.
104 |
105 | ## This sample shows how to do following operations to manage IP Address
106 |
107 | - Assign a public IP address for a virtual machine during its creation.
108 | - Assign a public IP address for a virtual machine through an virtual machine update action.
109 | - Get the associated public IP address for a virtual machine.
110 | - Get the assigned public IP address for a virtual machine.
111 | - Remove a public IP address from a virtual machine.
112 |
113 | ## More information
114 |
115 | The [Azure Compute documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
116 |
117 | This project has adopted the [Microsoft Open Source Code of Conduct].
118 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
119 |
120 |
121 | [Linux]: https://dotnet.microsoft.com/download
122 | [Windows]: https://dotnet.microsoft.com/download
123 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
124 | [Azure Portal]: https://portal.azure.com
125 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
126 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
127 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
128 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
129 |
--------------------------------------------------------------------------------
/samples/network/manage-virtual-network/ManageVirtualNetwork.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/samples/network/manage-virtual-network/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code samples will show you how to manage virtual network using Azure SDK for .NET."
8 | urlFragment: network-manage-virtual-network
9 | ---
10 | # Getting started - Managing Virtual Network using Azure .NET SDK
11 |
12 | This code sample will show you how to manage Virtual Network using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### Network
19 |
20 | - You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/mgmt/dotnet.html).
21 |
22 | ## Getting Started
23 |
24 | ### Prerequisites
25 |
26 | You will need the following values to authenticate to Azure
27 |
28 | - **Subscription ID**
29 | - **Client ID**
30 | - **Client Secret**
31 | - **Tenant ID**
32 |
33 | These values can be obtained from the portal, here's the instructions:
34 |
35 | ### Get Subscription ID
36 |
37 | 1. Login into your Azure account
38 | 2. Select `Subscriptions` under `Navigation` section in the portal
39 | 3. Select whichever subscription is needed
40 | 4. Click on `Overview`
41 | 5. Copy the `Subscription ID`
42 |
43 | ### Get Client ID / Client Secret / Tenant ID
44 |
45 | For information on how to get Client ID, Client Secret, and Tenant ID,
46 | please refer to [this
47 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
48 |
49 | ### Setting Environment Variables
50 |
51 | After you obtained the values, you need to set the following values as
52 | your environment variables
53 |
54 | - `AZURE_CLIENT_ID`
55 | - `AZURE_CLIENT_SECRET`
56 | - `AZURE_TENANT_ID`
57 | - `AZURE_SUBSCRIPTION_ID`
58 |
59 | To set the following environment variables on your development system:
60 |
61 | Windows: (Note: Administrator access is required)
62 |
63 | 1. Open the System Control Panel
64 | 2. Select `Advanced system settings`
65 | 3. Open the `Advanced` tab, then click `Environment Variables...`
66 | button.
67 | 4. Click on the property you would like to change, then click the `Edit…`
68 | button. If the property name is not listed, then click the `New…`
69 | button.
70 |
71 | Linux-based OS :
72 |
73 | ```bash
74 | export AZURE_CLIENT_ID="__CLIENT_ID__"
75 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
76 | export AZURE_TENANT_ID="__TENANT_ID__"
77 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
78 | ```
79 |
80 | ### Installation
81 |
82 | To complete this tutorial:
83 |
84 | - Install .NET Core latest version for [Linux] or [Windows]
85 |
86 | If you don't have an Azure subscription, create a [free account] before you begin.
87 |
88 | ### Quickstart
89 |
90 | 1. Clone the repository on your machine:
91 |
92 | ```bash
93 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
94 | ```
95 |
96 | 2. Switch to the project folder:
97 |
98 | ```bash
99 | cd samples/network/manage-virtual-network
100 | ```
101 |
102 | 3. Run the application with the `dotnet run` command.
103 |
104 | ## This sample shows how to do following operations to manage Virtual Network
105 |
106 | - Create a virtual network with Subnets.
107 | - Update a virtual network.
108 | - Create virtual machines in the virtual network subnets.
109 | - Create another virtual network.
110 | - List virtual networks.
111 |
112 | ## More information
113 |
114 | The [Azure Compute documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
115 |
116 | This project has adopted the [Microsoft Open Source Code of Conduct].
117 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
118 |
119 |
120 | [Linux]: https://dotnet.microsoft.com/download
121 | [Windows]: https://dotnet.microsoft.com/download
122 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
123 | [Azure Portal]: https://portal.azure.com
124 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
125 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
126 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
127 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
128 |
--------------------------------------------------------------------------------
/samples/resources/deploy-using-arm-template/Asset/ArmTemplate.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
3 | "contentVersion": "1.0.0.0",
4 | "parameters": {
5 | "hostingPlanName": {
6 | "type": "string",
7 | "defaultValue": ""
8 | },
9 | "skuName": {
10 | "type": "string",
11 | "defaultValue": "B1"
12 | },
13 | "skuCapacity": {
14 | "type": "int",
15 | "defaultValue": 1
16 | },
17 | "webSiteName": {
18 | "type": "string",
19 | "defaultValue": ""
20 | }
21 | },
22 | "resources": [
23 | {
24 | "apiVersion": "2015-08-01",
25 | "name": "[parameters('hostingPlanName')]",
26 | "type": "Microsoft.Web/serverfarms",
27 | "location": "[resourceGroup().location]",
28 | "tags": {
29 | "displayName": "HostingPlan"
30 | },
31 | "sku": {
32 | "name": "[parameters('skuName')]",
33 | "capacity": "[parameters('skuCapacity')]"
34 | },
35 | "properties": {
36 | "name": "[parameters('hostingPlanName')]"
37 | }
38 | },
39 | {
40 | "apiVersion": "2015-08-01",
41 | "name": "[parameters('webSiteName')]",
42 | "type": "Microsoft.Web/sites",
43 | "location": "[resourceGroup().location]",
44 | "tags": {
45 | "[concat('hidden-related:', resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]": "Resource",
46 | "displayName": "Website"
47 | },
48 | "dependsOn": [
49 | "[concat('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
50 | ],
51 | "properties": {
52 | "name": "[parameters('webSiteName')]",
53 | "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', parameters('hostingPlanName'))]"
54 | },
55 | "resources": [
56 | {
57 | "apiVersion": "2015-08-01",
58 | "name": "web",
59 | "type": "config",
60 | "dependsOn": [
61 | "[concat('Microsoft.Web/sites/', parameters('webSiteName'))]"
62 | ],
63 | "properties": {
64 | "javaVersion": "1.8",
65 | "javaContainer": "TOMCAT",
66 | "javaContainerVersion": "8.0"
67 | }
68 | }
69 | ]
70 | }
71 | ]
72 | }
--------------------------------------------------------------------------------
/samples/resources/deploy-using-arm-template/Asset/ArmTemplateVM.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
3 | "contentVersion": "1.0.0.0",
4 | "parameters":
5 | {
6 | "adminUsername":
7 | {
8 | "type": "String",
9 | "metadata":
10 | {
11 | "description": "Username for the Virtual Machine."
12 | }
13 | }
14 | ,
15 | "adminPassword":
16 | {
17 | "type": "SecureString",
18 | "metadata":
19 | {
20 | "description": "Password for the Virtual Machine."
21 | }
22 | }
23 | ,
24 | "windowsOSVersion":
25 | {
26 | "defaultValue": "2012-R2-Datacenter",
27 | "allowedValues": [
28 | "R2",
29 | "2008-R2-SP1",
30 | "2012-Datacenter",
31 | "2012-R2-Datacenter"
32 | ],
33 | "type": "String",
34 | "metadata":
35 | {
36 | "description": "The Windows version for the VM. This will pick a fully patched image of this given Windows version. Allowed values: 2008-R2-SP1, 2012-Datacenter, 2012-R2-Datacenter."
37 | }
38 | }
39 | }
40 | ,
41 | "variables":
42 | {
43 | "location": "[resourceGroup().location]",
44 | "imagePublisher": "MicrosoftWindowsServer",
45 | "imageOffer": "WindowsServer",
46 | "OSDiskName": "osdiskforwindowssimple",
47 | "nicName": "mynic",
48 | "addressPrefix": "10.0.0.0/8",
49 | "subnetName": "Subnet11",
50 | "subnetPrefix": "10.0.0.0/16",
51 | "storageAccountType": "Standard_LRS",
52 | "publicIPAddressName": "myip",
53 | "publicIPAddressType": "Dynamic",
54 | "vmStorageAccountContainerName": "vhds",
55 | "vmName": "myVMDataDisk",
56 | "vmSize": "Standard_A1",
57 | "virtualNetworkName": "myvnet",
58 | "vnetID": "[resourceId('Microsoft.Network/virtualNetworks',variables('virtualNetworkName'))]",
59 | "subnetRef": "[concat(variables('vnetID'),'/subnets/',variables('subnetName'))]",
60 | "apiVersion": "2015-06-15",
61 | "computeResouresApiVersion": "2016-04-30-preview",
62 | "dnsLabelPrefix" : "[toLower(resourceGroup().name)]"
63 | }
64 | ,
65 | "resources": [
66 | {
67 | "type": "Microsoft.Network/publicIPAddresses",
68 | "name": "[variables('publicIPAddressName')]",
69 | "apiVersion": "[variables('apiVersion')]",
70 | "location": "[variables('location')]",
71 | "properties": {
72 | "publicIPAllocationMethod": "[variables('publicIPAddressType')]",
73 | "dnsSettings": {
74 | "domainNameLabel": "[variables('dnsLabelPrefix')]"
75 | }
76 | }
77 | }
78 | ,
79 | {
80 | "type": "Microsoft.Network/virtualNetworks",
81 | "name": "[variables('virtualNetworkName')]",
82 | "apiVersion": "[variables('apiVersion')]",
83 | "location": "[variables('location')]",
84 | "properties":
85 | {
86 | "addressSpace":
87 | {
88 | "addressPrefixes": [
89 | "[variables('addressPrefix')]"
90 | ]
91 | }
92 | ,
93 | "subnets": [
94 | {
95 | "name": "[variables('subnetName')]",
96 | "properties":
97 | {
98 | "addressPrefix": "[variables('subnetPrefix')]"
99 | }
100 | }
101 | ]
102 | }
103 | }
104 | ,
105 | {
106 | "type": "Microsoft.Network/networkInterfaces",
107 | "name": "[variables('nicName')]",
108 | "apiVersion": "[variables('apiVersion')]",
109 | "location": "[variables('location')]",
110 | "properties":
111 | {
112 | "ipConfigurations": [
113 | {
114 | "name": "ipconfig1",
115 | "properties":
116 | {
117 | "privateIPAllocationMethod": "Dynamic",
118 | "publicIPAddress":
119 | {
120 | "id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]"
121 | }
122 | ,
123 | "subnet":
124 | {
125 | "id": "[variables('subnetRef')]"
126 | }
127 | }
128 | }
129 | ]
130 | }
131 | ,
132 | "dependsOn": [
133 | "[concat('Microsoft.Network/publicIPAddresses/', variables('publicIPAddressName'))]",
134 | "[concat('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]"
135 | ]
136 | }
137 | ,
138 | {
139 | "type": "Microsoft.Compute/disks",
140 | "name": "myManagedDataDisk",
141 | "apiVersion": "[variables('computeResouresApiVersion')]",
142 | "location": "[variables('location')]",
143 | "properties":
144 | {
145 | "creationData":
146 | {
147 | "createOption" : "Empty"
148 | }
149 | ,
150 | "accountType" : "[variables('storageAccountType')]",
151 | "diskSizeGB": 64
152 | }
153 | }
154 | ,
155 | {
156 | "type": "Microsoft.Compute/disks",
157 | "name": "myManagedDataDisk1",
158 | "apiVersion": "[variables('computeResouresApiVersion')]",
159 | "location": "[variables('location')]",
160 | "properties":
161 | {
162 | "creationData":
163 | {
164 | "createOption" : "Empty"
165 | }
166 | ,
167 | "accountType" : "[variables('storageAccountType')]",
168 | "diskSizeGB": 128
169 | }
170 | }
171 | ,
172 | {
173 | "type": "Microsoft.Compute/virtualMachines",
174 | "name": "[variables('vmName')]",
175 | "apiVersion": "[variables('computeResouresApiVersion')]",
176 | "location": "[variables('location')]",
177 | "properties":
178 | {
179 | "hardwareProfile":
180 | {
181 | "vmSize": "[variables('vmSize')]"
182 | }
183 | ,
184 | "osProfile":
185 | {
186 | "computerName": "[variables('vmName')]",
187 | "adminUsername": "[parameters('adminUsername')]",
188 | "adminPassword": "[parameters('adminPassword')]"
189 | }
190 | ,
191 | "storageProfile":
192 | {
193 | "imageReference":
194 | {
195 | "publisher": "[variables('imagePublisher')]",
196 | "offer": "[variables('imageOffer')]",
197 | "sku": "[parameters('windowsOSVersion')]",
198 | "version": "latest"
199 | }
200 | ,
201 | "osDisk":
202 | {
203 | "name": "myOSDisk",
204 | "createOption": "fromImage"
205 | }
206 | ,
207 | "dataDisks": [
208 | {
209 | "lun": 2,
210 | "name": "myManagedDataDisk",
211 | "createOption": "attach",
212 | "managedDisk":
213 | {
214 | "id": "[resourceId('Microsoft.Compute/disks', 'myManagedDataDisk')]"
215 | }
216 | }
217 | ,
218 | {
219 | "lun": 3,
220 | "name": "myManagedDataDisk1",
221 | "createOption": "attach",
222 | "managedDisk":
223 | {
224 | "id": "[resourceId('Microsoft.Compute/disks', 'myManagedDataDisk1')]"
225 | }
226 | }
227 | ]
228 | }
229 | ,
230 | "networkProfile":
231 | {
232 | "networkInterfaces": [
233 | {
234 | "id": "[resourceId('Microsoft.Network/networkInterfaces',variables('nicName'))]"
235 | }
236 | ]
237 | }
238 | }
239 | ,
240 | "dependsOn": [
241 | "[concat('Microsoft.Network/networkInterfaces/', variables('nicName'))]",
242 | "Microsoft.Compute/disks/myManagedDataDisk"
243 | ]
244 | }
245 | ]
246 | }
--------------------------------------------------------------------------------
/samples/resources/deploy-using-arm-template/DeployUsingARMTemplate.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | Always
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/samples/resources/deploy-using-arm-template/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License. See License.txt in the project root for license information.
3 |
4 | using Azure.Core;
5 | using Azure.Identity;
6 | using Azure.ResourceManager;
7 | using Azure.ResourceManager.Resources;
8 | using Azure.ResourceManager.Resources.Models;
9 | using Samples.Utilities;
10 | using System;
11 | using System.Threading.Tasks;
12 |
13 | namespace DeployUsingARMTemplate
14 | {
15 | public class Program
16 | {
17 | public static async Task RunSample(ArmClient client)
18 | {
19 | var rgName = Utilities.RandomResourceName("rgRSAT", 24);
20 | var deploymentName = Utilities.RandomResourceName("dpRSAT", 24);
21 | var location = AzureLocation.WestUS;
22 | var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
23 | var templateJson = Utilities.GetArmTemplate("ArmTemplate.json");
24 |
25 | // Create resource group.
26 |
27 | Utilities.Log("Creating a resource group with name: " + rgName);
28 | ResourceGroupResource resourceGroup = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, rgName, new ResourceGroupData(location))).Value;
29 | Utilities.Log("Created a resource group with name: " + rgName);
30 |
31 | try
32 | {
33 | // Create a deployment for an Azure App Service via an ARM
34 | // template.
35 |
36 | Utilities.Log("Starting a deployment for an Azure App Service: " + deploymentName);
37 |
38 | var deployMentCollection = resourceGroup.GetArmDeployments();
39 |
40 | var deployMentData = new ArmDeploymentContent
41 | (
42 | new ArmDeploymentProperties(ArmDeploymentMode.Incremental)
43 | {
44 | Template = BinaryData.FromObjectAsJson(templateJson),
45 | Parameters = BinaryData.FromString("\"{}\"")
46 | }
47 | );
48 | var rawResult = await deployMentCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, deploymentName, deployMentData);
49 | var deployMent = rawResult.Value;
50 |
51 | Utilities.Log("Completed the deployment: " + deploymentName);
52 | }
53 | finally
54 | {
55 | try
56 | {
57 | Utilities.Log("Deleting Resource Group: " + rgName);
58 |
59 | await resourceGroup.DeleteAsync(Azure.WaitUntil.Completed);
60 |
61 | Utilities.Log("Deleted Resource Group: " + rgName);
62 | }
63 | catch (Exception ex)
64 | {
65 | Utilities.Log(ex);
66 | }
67 | }
68 | }
69 |
70 | public static async Task Main(string[] args)
71 | {
72 | try
73 | {
74 | // Authenticate
75 | var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
76 | var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
77 | var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
78 | var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
79 | ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
80 | ArmClient client = new ArmClient(credential, subscription);
81 |
82 | await RunSample(client);
83 | }
84 | catch (Exception ex)
85 | {
86 | Utilities.Log(ex);
87 | }
88 | }
89 | }
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/samples/resources/deploy-using-arm-template/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code samples will show you how to deploy resources with arm template using Azure SDK for .NET."
8 | urlFragment: resources-deploy-with-arm-template
9 | ---
10 | # Getting started - Deploy resources with ARM template using Azure .NET SDK
11 |
12 | This code sample will show you how to deploy resources with ARM template using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### Resources
19 | * You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/#dotnet).
20 |
21 | ## Getting Started
22 |
23 | ### Prerequisites
24 |
25 | You will need the following values to authenticate to Azure
26 |
27 | - **Subscription ID**
28 | - **Client ID**
29 | - **Client Secret**
30 | - **Tenant ID**
31 |
32 | These values can be obtained from the portal, here's the instructions:
33 |
34 | ### Get Subscription ID
35 |
36 | 1. Login into your Azure account
37 | 2. Select Subscriptions in the left sidebar
38 | 3. Select whichever subscription is needed
39 | 4. Click on Overview
40 | 5. Copy the Subscription ID
41 |
42 | ### Get Client ID / Client Secret / Tenant ID
43 |
44 | For information on how to get Client ID, Client Secret, and Tenant ID,
45 | please refer to [this
46 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
47 |
48 | ### Setting Environment Variables
49 |
50 | After you obtained the values, you need to set the following values as
51 | your environment variables
52 |
53 | - `AZURE_CLIENT_ID`
54 | - `AZURE_CLIENT_SECRET`
55 | - `AZURE_TENANT_ID`
56 | - `AZURE_SUBSCRIPTION_ID`
57 |
58 | To set the following environment variables on your development system:
59 |
60 | Windows (Note: Administrator access is required)
61 |
62 | 1. Open the Control Panel
63 | 2. Click System Security, then System
64 | 3. Click Advanced system settings on the left
65 | 4. Inside the System Properties window, click the Environment
66 | Variables… button.
67 | 5. Click on the property you would like to change, then click the Edit…
68 | button. If the property name is not listed, then click the New…
69 | button.
70 |
71 | Linux-based OS :
72 |
73 | export AZURE_CLIENT_ID="__CLIENT_ID__"
74 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
75 | export AZURE_TENANT_ID="__TENANT_ID__"
76 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
77 |
78 | ### Installation
79 |
80 | To complete this tutorial:
81 |
82 | * Install .NET Core latest version for [Linux] or [Windows]
83 |
84 | If you don't have an Azure subscription, create a [free account] before you begin.
85 |
86 | ### Quickstart
87 |
88 | 1. Clone the repository on your machine:
89 |
90 | ```bash
91 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
92 | ```
93 |
94 | 2. Switch to the project folder:
95 | ```bash
96 | cd samples/resources/deploy-using-arm-template
97 | ```
98 |
99 | 3. Run the application with the `dotnet run` command.
100 |
101 | ```console
102 | dotnet run
103 | ```
104 |
105 | ## This sample shows how to do following operations to deploy resources with ARM template
106 | - Create resource group.
107 | - Create a deployment for an Azure App Service via an ARM template.
108 |
109 | ## More information
110 |
111 | The [Azure Compute documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
112 |
113 | This project has adopted the [Microsoft Open Source Code of Conduct].
114 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
115 |
116 |
117 | [Linux]: https://dotnet.microsoft.com/download
118 | [Windows]: https://dotnet.microsoft.com/download
119 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
120 | [Azure Portal]: https://portal.azure.com
121 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
122 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
123 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
124 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
125 |
--------------------------------------------------------------------------------
/samples/resources/manage-resource-group/ManageResourceGroup.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/samples/resources/manage-resource-group/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License. See License.txt in the project root for license information.
3 |
4 | using Azure.Core;
5 | using Azure.Identity;
6 | using Azure.ResourceManager;
7 | using Azure.ResourceManager.Resources;
8 | using Azure.ResourceManager.Resources.Models;
9 | using Samples.Utilities;
10 | using System;
11 | using System.Collections.Generic;
12 | using System.Threading.Tasks;
13 |
14 | namespace ManageResourceGroup
15 | {
16 | public class Program
17 | {
18 | //Azure Resource sample for managing resource groups -
19 | // - Create a resource group
20 | // - Update a resource group
21 | // - Create another resource group
22 | // - List resource groups
23 | // - Delete a resource group.
24 |
25 | public static async Task RunSample(ArmClient client)
26 | {
27 | var rgName = Utilities.RandomResourceName("rgRSMA", 24);
28 | var rgName2 = Utilities.RandomResourceName("rgRSMA", 24);
29 | var resourceTagName = Utilities.RandomResourceName("rgRSTN", 24);
30 | var resourceTagValue = Utilities.RandomResourceName("rgRSTV", 24);
31 | var location = AzureLocation.WestUS;
32 | var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
33 |
34 | // Create resource group.
35 |
36 | Utilities.Log("Creating a resource group with name: " + rgName);
37 |
38 | ResourceGroupResource resourceGroup = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, rgName, new ResourceGroupData(location))).Value;
39 |
40 | Utilities.Log("Created a resource group with name: " + rgName);
41 |
42 | try
43 | {
44 |
45 | // Update the resource group.
46 |
47 | Utilities.Log("Updating the resource group with name: " + rgName);
48 |
49 | await resourceGroup.UpdateAsync(new ResourceGroupPatch()
50 | {
51 | Tags =
52 | {
53 | [resourceTagName] = resourceTagValue
54 | }
55 | });
56 |
57 | Utilities.Log("Updated the resource group with name: " + rgName);
58 |
59 | // Create another resource group.
60 |
61 | Utilities.Log("Creating another resource group with name: " + rgName2);
62 |
63 | ResourceGroupResource resourceGroup2 = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, rgName2, new ResourceGroupData(location))).Value;
64 |
65 | Utilities.Log("Created another resource group with name: " + rgName2);
66 |
67 | // List resource groups.
68 |
69 | Utilities.Log("Listing all resource groups");
70 |
71 |
72 | await foreach (var rGroup in client.GetDefaultSubscription().GetResourceGroups().GetAllAsync())
73 | {
74 | Utilities.Log("Resource group: " + rGroup.Data.Name);
75 | }
76 |
77 | // Delete a resource group.
78 |
79 | Utilities.Log("Deleting resource group: " + rgName2);
80 |
81 | await resourceGroup2.DeleteAsync(Azure.WaitUntil.Completed);
82 |
83 | Utilities.Log("Deleted resource group: " + rgName2);
84 | }
85 | finally
86 | {
87 | try
88 | {
89 | Utilities.Log("Deleting Resource Group: " + rgName);
90 |
91 | await resourceGroup.DeleteAsync(Azure.WaitUntil.Completed);
92 |
93 | Utilities.Log("Deleted Resource Group: " + rgName);
94 | }
95 | catch (Exception ex)
96 | {
97 | Utilities.Log(ex);
98 | }
99 | }
100 | }
101 |
102 | public static async Task Main(string[] args)
103 | {
104 | try
105 | {
106 | // Authenticate
107 | var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
108 | var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
109 | var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
110 | var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
111 | ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
112 | ArmClient client = new ArmClient(credential, subscription);
113 |
114 | await RunSample(client);
115 | }
116 | catch (Exception ex)
117 | {
118 | Utilities.Log(ex);
119 | }
120 | }
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/samples/resources/manage-resource-group/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code samples will show you how to managing resource groups using Azure SDK for .NET."
8 | urlFragment: resources-manage-resource-groups
9 | ---
10 | # Getting started - Managing Resource Groups using Azure .NET SDK
11 |
12 | This code sample will show you how to managing Resources Groups using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### Resources
19 | * You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/#dotnet).
20 |
21 | ## Getting Started
22 |
23 | ### Prerequisites
24 |
25 | You will need the following values to authenticate to Azure
26 |
27 | - **Subscription ID**
28 | - **Client ID**
29 | - **Client Secret**
30 | - **Tenant ID**
31 |
32 | These values can be obtained from the portal, here's the instructions:
33 |
34 | ### Get Subscription ID
35 |
36 | 1. Login into your Azure account
37 | 2. Select Subscriptions in the left sidebar
38 | 3. Select whichever subscription is needed
39 | 4. Click on Overview
40 | 5. Copy the Subscription ID
41 |
42 | ### Get Client ID / Client Secret / Tenant ID
43 |
44 | For information on how to get Client ID, Client Secret, and Tenant ID,
45 | please refer to [this
46 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
47 |
48 | ### Setting Environment Variables
49 |
50 | After you obtained the values, you need to set the following values as
51 | your environment variables
52 |
53 | - `AZURE_CLIENT_ID`
54 | - `AZURE_CLIENT_SECRET`
55 | - `AZURE_TENANT_ID`
56 | - `AZURE_SUBSCRIPTION_ID`
57 |
58 | To set the following environment variables on your development system:
59 |
60 | Windows (Note: Administrator access is required)
61 |
62 | 1. Open the Control Panel
63 | 2. Click System Security, then System
64 | 3. Click Advanced system settings on the left
65 | 4. Inside the System Properties window, click the Environment
66 | Variables… button.
67 | 5. Click on the property you would like to change, then click the Edit…
68 | button. If the property name is not listed, then click the New…
69 | button.
70 |
71 | Linux-based OS :
72 |
73 | export AZURE_CLIENT_ID="__CLIENT_ID__"
74 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
75 | export AZURE_TENANT_ID="__TENANT_ID__"
76 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
77 |
78 | ### Installation
79 |
80 | To complete this tutorial:
81 |
82 | * Install .NET Core latest version for [Linux] or [Windows]
83 |
84 | If you don't have an Azure subscription, create a [free account] before you begin.
85 |
86 | ### Quickstart
87 |
88 | 1. Clone the repository on your machine:
89 |
90 | ```bash
91 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
92 | ```
93 |
94 | 2. Switch to the project folder:
95 | ```bash
96 | cd samples/resources/manage-resource-group
97 | ```
98 |
99 | 3. Run the application with the `dotnet run` command.
100 |
101 | ```console
102 | dotnet run
103 | ```
104 |
105 | ## This sample shows how to do following operations to manage Resource Groups
106 | - Create a resource group.
107 | - Update a resource group.
108 | - Create another resource group.
109 | - List resource groups.
110 | - Delete a resource group.
111 |
112 | ## More information
113 |
114 | The [Azure Compute documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
115 |
116 | This project has adopted the [Microsoft Open Source Code of Conduct].
117 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
118 |
119 |
120 | [Linux]: https://dotnet.microsoft.com/download
121 | [Windows]: https://dotnet.microsoft.com/download
122 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
123 | [Azure Portal]: https://portal.azure.com
124 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
125 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
126 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
127 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
128 |
--------------------------------------------------------------------------------
/samples/resources/manage-resource/ManageResource.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/samples/resources/manage-resource/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License. See License.txt in the project root for license information.
3 |
4 | using Azure.Core;
5 | using Azure.Identity;
6 | using Azure.ResourceManager;
7 | using Azure.ResourceManager.Resources;
8 | using Azure.ResourceManager.Storage;
9 | using Azure.ResourceManager.Storage.Models;
10 | using Azure.ResourceManager.Resources.Models;
11 | using Samples.Utilities;
12 | using System;
13 | using System.Collections.Generic;
14 | using System.Threading.Tasks;
15 | using System.Xml.Linq;
16 |
17 | namespace ManageResource
18 | {
19 | public class Program
20 | {
21 | //Azure Resource sample for managing resources -
22 | // - Create a resource
23 | // - Update a resource
24 | // - Create another resource
25 | // - List resources
26 | // - Delete a resource.
27 |
28 | public static async Task RunSample(ArmClient client)
29 | {
30 | var resourceGroupName = Utilities.RandomResourceName("rgRSMR", 24);
31 | var resourceName1 = Utilities.RandomResourceName("rn1", 24);
32 | var resourceName2 = Utilities.RandomResourceName("rn2", 24);
33 | var location = AzureLocation.EastUS;
34 | var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
35 |
36 | // Create resource group.
37 |
38 | Utilities.Log("Creating a resource group with name: " + resourceGroupName);
39 | ResourceGroupResource resourceGroup = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, resourceGroupName, new ResourceGroupData(location))).Value;
40 | Utilities.Log("Created a resource group with name: " + resourceGroupName);
41 | try
42 | {
43 |
44 | // Create storage account.
45 |
46 | Utilities.Log("Creating a storage account with name: " + resourceName1);
47 |
48 | var storageCollection = resourceGroup.GetStorageAccounts();
49 | var rawResult = await storageCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, resourceName1, new StorageAccountCreateOrUpdateContent(new StorageSku(StorageSkuName.StandardLrs), StorageKind.StorageV2, location)
50 | {
51 | AccessTier = StorageAccountAccessTier.Hot
52 | });
53 | var storageResource = rawResult.Value;
54 |
55 | Utilities.Log("Storage account created: " + storageResource.Id);
56 |
57 | // Update - set the sku name
58 |
59 | Utilities.Log("Updating the storage account with name: " + resourceName1);
60 |
61 | var updateResult = await storageResource.UpdateAsync(new StorageAccountPatch()
62 | {
63 | AccessTier = StorageAccountAccessTier.Premium
64 | });
65 |
66 | Utilities.Log("Updated the storage account with name: " + resourceName1);
67 |
68 | // Create another storage account.
69 |
70 | Utilities.Log("Creating another storage account with name: " + resourceName2);
71 |
72 | var rawResult2 = await storageCollection.CreateOrUpdateAsync(Azure.WaitUntil.Completed, resourceName1, new StorageAccountCreateOrUpdateContent(new StorageSku(StorageSkuName.StandardLrs), StorageKind.StorageV2, location)
73 | {
74 | AccessTier = StorageAccountAccessTier.Hot
75 | });
76 | var storageResource2 = rawResult2.Value;
77 |
78 | Utilities.Log("Storage account created: " + storageResource2.Id);
79 |
80 | // List storage accounts.
81 |
82 | // Add Sleep to handle the lag for list operation
83 | System.Threading.Thread.Sleep(10 * 1000);
84 |
85 | Utilities.Log("Listing all storage accounts for resource group: " + resourceGroupName);
86 |
87 | await foreach (var sAccount in storageCollection.GetAllAsync())
88 | {
89 | Utilities.Log("Storage account: " + sAccount.Data.Name);
90 | }
91 |
92 | // Delete a storage accounts.
93 |
94 | Utilities.Log("Deleting storage account: " + resourceName2);
95 |
96 | await storageResource2.DeleteAsync(Azure.WaitUntil.Completed);
97 |
98 | Utilities.Log("Deleted storage account: " + resourceName2);
99 | }
100 | finally
101 | {
102 | try
103 | {
104 | Utilities.Log("Deleting Resource Group: " + resourceGroupName);
105 |
106 | await resourceGroup.DeleteAsync(Azure.WaitUntil.Completed);
107 |
108 | Utilities.Log("Deleted Resource Group: " + resourceGroupName);
109 | }
110 | catch (Exception ex)
111 | {
112 | Utilities.Log(ex);
113 | }
114 | }
115 | }
116 | public static async Task Main(string[] args)
117 | {
118 | try
119 | {
120 | // Authenticate
121 | var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
122 | var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
123 | var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
124 | var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
125 | ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
126 | ArmClient client = new ArmClient(credential, subscription);
127 |
128 | await RunSample(client);
129 | }
130 | catch (Exception ex)
131 | {
132 | Utilities.Log(ex);
133 | }
134 | }
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/samples/resources/manage-resource/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | languages:
4 | - csharp
5 | products:
6 | - azure
7 | description: "This code samples will show you how to managing resources using Azure SDK for .NET."
8 | urlFragment: resources-manage-resources
9 | ---
10 | # Getting started - Managing resources using Azure .NET SDK
11 |
12 | This code sample will show you how to managing resources using Azure SDK for .NET.
13 |
14 | ## Features
15 |
16 | This project framework provides examples for the following services:
17 |
18 | ### Resources
19 | * You can find the details for the library [here](https://azure.github.io/azure-sdk/releases/latest/#dotnet).
20 |
21 | ## Getting Started
22 |
23 | ### Prerequisites
24 |
25 | You will need the following values to authenticate to Azure
26 |
27 | - **Subscription ID**
28 | - **Client ID**
29 | - **Client Secret**
30 | - **Tenant ID**
31 |
32 | These values can be obtained from the portal, here's the instructions:
33 |
34 | ### Get Subscription ID
35 |
36 | 1. Login into your Azure account
37 | 2. Select Subscriptions in the left sidebar
38 | 3. Select whichever subscription is needed
39 | 4. Click on Overview
40 | 5. Copy the Subscription ID
41 |
42 | ### Get Client ID / Client Secret / Tenant ID
43 |
44 | For information on how to get Client ID, Client Secret, and Tenant ID,
45 | please refer to [this
46 | document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
47 |
48 | ### Setting Environment Variables
49 |
50 | After you obtained the values, you need to set the following values as
51 | your environment variables
52 |
53 | - `AZURE_CLIENT_ID`
54 | - `AZURE_CLIENT_SECRET`
55 | - `AZURE_TENANT_ID`
56 | - `AZURE_SUBSCRIPTION_ID`
57 |
58 | To set the following environment variables on your development system:
59 |
60 | Windows (Note: Administrator access is required)
61 |
62 | 1. Open the Control Panel
63 | 2. Click System Security, then System
64 | 3. Click Advanced system settings on the left
65 | 4. Inside the System Properties window, click the Environment
66 | Variables… button.
67 | 5. Click on the property you would like to change, then click the Edit…
68 | button. If the property name is not listed, then click the New…
69 | button.
70 |
71 | Linux-based OS :
72 |
73 | export AZURE_CLIENT_ID="__CLIENT_ID__"
74 | export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
75 | export AZURE_TENANT_ID="__TENANT_ID__"
76 | export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
77 |
78 | ### Installation
79 |
80 | To complete this tutorial:
81 |
82 | * Install .NET Core latest version for [Linux] or [Windows]
83 |
84 | If you don't have an Azure subscription, create a [free account] before you begin.
85 |
86 | ### Quickstart
87 |
88 | 1. Clone the repository on your machine:
89 |
90 | ```bash
91 | git clone https://github.com/Azure-Samples/azure-samples-net-management.git
92 | ```
93 |
94 | 2. Switch to the project folder:
95 | ```bash
96 | cd samples/resources/manage-resource
97 | ```
98 |
99 | 3. Run the application with the `dotnet run` command.
100 |
101 | ```console
102 | dotnet run
103 | ```
104 |
105 | ## This sample shows how to do following operations to manage resources
106 | - Create a resource.
107 | - Update a resource.
108 | - Create another resource.
109 | - List resources.
110 | - Delete a resource.
111 |
112 | ## More information
113 |
114 | The [Azure Compute documentation] includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples.
115 |
116 | This project has adopted the [Microsoft Open Source Code of Conduct].
117 | For more information see the [Code of Conduct FAQ] or contact [opencode@microsoft.com] with any additional questions or comments.
118 |
119 |
120 | [Linux]: https://dotnet.microsoft.com/download
121 | [Windows]: https://dotnet.microsoft.com/download
122 | [free account]: https://azure.microsoft.com/free/?WT.mc_id=A261C142F
123 | [Azure Portal]: https://portal.azure.com
124 | [Azure Compute documentation]: https://docs.microsoft.com/azure/?product=compute
125 | [Microsoft Open Source Code of Conduct]: https://opensource.microsoft.com/codeofconduct/
126 | [Code of Conduct FAQ]: https://opensource.microsoft.com/codeofconduct/faq/
127 | [opencode@microsoft.com]: mailto:opencode@microsoft.com
128 |
--------------------------------------------------------------------------------
/samples/storage/create-storage-account/CreateStorageSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/samples/storage/create-storage-account/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading.Tasks;
3 | using System.Xml.Linq;
4 | using Azure.Core;
5 | using Azure.Identity;
6 | using Azure.ResourceManager;
7 | using Azure.ResourceManager.Resources;
8 | using Azure.ResourceManager.Storage;
9 | using Azure.ResourceManager.Storage.Models;
10 |
11 | namespace CreateStorageSample
12 | {
13 | public class Program
14 | {
15 | public static async Task Main(string[] args)
16 | {
17 | try
18 | {
19 | // Authenticate
20 | var clientId = Environment.GetEnvironmentVariable("CLIENT_ID");
21 | var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET");
22 | var tenantId = Environment.GetEnvironmentVariable("TENANT_ID");
23 | var subscription = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID");
24 | ClientSecretCredential credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
25 | ArmClient client = new ArmClient(credential, subscription);
26 |
27 | await RunSample(client);
28 | }
29 | catch (Exception ex)
30 | {
31 | Console.Error.WriteLine(ex);
32 | }
33 | }
34 |
35 | public static async Task RunSample(ArmClient client)
36 | {
37 | const string StorageAccountName = "strg1";
38 | const string ResourceGroupName = "rgNEMV";
39 | AzureLocation location = AzureLocation.EastUS;
40 |
41 | ResourceGroupResource resourceGroup = (await client.GetDefaultSubscription().GetResourceGroups().CreateOrUpdateAsync(Azure.WaitUntil.Completed, ResourceGroupName, new ResourceGroupData(location))).Value;
42 |
43 | // Create a storage account
44 | Console.WriteLine("Creating a Storage Account...");
45 |
46 | var StorageAccountCreateParameters = new StorageAccountCreateOrUpdateContent(new StorageSku(StorageSkuName.StandardLrs), StorageKind.StorageV2, location);
47 |
48 | var rawResult = await resourceGroup.GetStorageAccounts().CreateOrUpdateAsync(Azure.WaitUntil.Completed, StorageAccountName, StorageAccountCreateParameters);
49 | var storageAccount = rawResult.Value;
50 |
51 | Console.WriteLine("Created Storage Account");
52 | PrintStorageAccount(storageAccount);
53 | }
54 |
55 | private static void PrintStorageAccount(StorageAccountResource storageAccount)
56 | {
57 | Console.WriteLine($@"Storage Account: {storageAccount.Id}
58 | Name: {storageAccount.Data.Name}
59 | Location: {storageAccount.Data.Location}
60 | Sku: {storageAccount.Data.Sku.Name} - {storageAccount.Data.Sku.Tier}");
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/samples/utilities/ResourceNamer.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License. See License.txt in the project root for license information.
3 |
4 | using System;
5 |
6 | namespace Samples.Utilities
7 | {
8 | public class ResourceNamer
9 | {
10 | private readonly string randName;
11 | private static Random random = new Random();
12 |
13 | public ResourceNamer(string name)
14 | {
15 | lock (random)
16 | {
17 | this.randName = name.ToLower() + Guid.NewGuid().ToString("N").Substring(0, 3).ToLower();
18 | }
19 | }
20 |
21 | public virtual string RandomName(string prefix, int maxLen)
22 | {
23 | lock (random)
24 | {
25 | prefix = prefix.ToLower();
26 | int minRandomnessLength = 5;
27 | string minRandomString = random.Next(0, 100000).ToString("D5");
28 |
29 | if (maxLen < (prefix.Length + randName.Length + minRandomnessLength))
30 | {
31 | var str1 = prefix + minRandomString;
32 | return str1 + RandomString((maxLen - str1.Length) / 2);
33 | }
34 |
35 | string str = prefix + randName + minRandomString;
36 | return str + RandomString((maxLen - str.Length) / 2);
37 | }
38 | }
39 |
40 | private string RandomString(int length)
41 | {
42 | string str = string.Empty;
43 | while (str.Length < length)
44 | {
45 | str += Guid.NewGuid().ToString("N").Substring(0, Math.Min(32, length)).ToLower();
46 | }
47 | return str;
48 | }
49 |
50 | public virtual string RandomGuid()
51 | {
52 | return Guid.NewGuid().ToString();
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/samples/utilities/Utilities.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Library
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------