diff --git a/eng/Packages.Data.props b/eng/Packages.Data.props index 6db7c956504be..bce2bd466898c 100644 --- a/eng/Packages.Data.props +++ b/eng/Packages.Data.props @@ -71,6 +71,8 @@ + + @@ -81,6 +83,7 @@ + diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/Azure.ResourceManager.Core.sln b/sdk/resourcemanager/Azure.ResourceManager.Core/Azure.ResourceManager.Core.sln new file mode 100644 index 0000000000000..40437f8262ad3 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/Azure.ResourceManager.Core.sln @@ -0,0 +1,43 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.31019.35 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Core", "..\..\core\Azure.Core\src\Azure.Core.csproj", "{856C6092-55EB-4C02-B7D0-9846EDD70745}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Core.TestFramework", "..\..\core\Azure.Core.TestFramework\src\Azure.Core.TestFramework.csproj", "{62AF7C88-CE3F-416E-B18E-BC6F884C89E2}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.ResourceManager.Core", "src\Azure.ResourceManager.Core.csproj", "{010FE057-7BB5-4F8C-BB9A-6378144F4CA8}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.ResourceManager.Core.Tests", "tests\Azure.ResourceManager.Core.Tests.csproj", "{83E7651C-7FBE-45AA-B740-31FE9A3E44C7}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {856C6092-55EB-4C02-B7D0-9846EDD70745}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {856C6092-55EB-4C02-B7D0-9846EDD70745}.Debug|Any CPU.Build.0 = Debug|Any CPU + {856C6092-55EB-4C02-B7D0-9846EDD70745}.Release|Any CPU.ActiveCfg = Release|Any CPU + {856C6092-55EB-4C02-B7D0-9846EDD70745}.Release|Any CPU.Build.0 = Release|Any CPU + {62AF7C88-CE3F-416E-B18E-BC6F884C89E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {62AF7C88-CE3F-416E-B18E-BC6F884C89E2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {62AF7C88-CE3F-416E-B18E-BC6F884C89E2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {62AF7C88-CE3F-416E-B18E-BC6F884C89E2}.Release|Any CPU.Build.0 = Release|Any CPU + {010FE057-7BB5-4F8C-BB9A-6378144F4CA8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {010FE057-7BB5-4F8C-BB9A-6378144F4CA8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {010FE057-7BB5-4F8C-BB9A-6378144F4CA8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {010FE057-7BB5-4F8C-BB9A-6378144F4CA8}.Release|Any CPU.Build.0 = Release|Any CPU + {83E7651C-7FBE-45AA-B740-31FE9A3E44C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {83E7651C-7FBE-45AA-B740-31FE9A3E44C7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {83E7651C-7FBE-45AA-B740-31FE9A3E44C7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {83E7651C-7FBE-45AA-B740-31FE9A3E44C7}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {FA17550D-A020-4DD7-B3A3-0228FC290A1F} + EndGlobalSection +EndGlobal diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/CHANGELOG.md b/sdk/resourcemanager/Azure.ResourceManager.Core/CHANGELOG.md new file mode 100644 index 0000000000000..5c312e4ea9bea --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/CHANGELOG.md @@ -0,0 +1,5 @@ +# Release History + +## 1.0.0-beta.1 (Unreleased) + +-Initial checkin diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/Directory.Build.props b/sdk/resourcemanager/Azure.ResourceManager.Core/Directory.Build.props new file mode 100644 index 0000000000000..63bd836ad44b7 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/Directory.Build.props @@ -0,0 +1,6 @@ + + + + diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/README.md b/sdk/resourcemanager/Azure.ResourceManager.Core/README.md new file mode 100644 index 0000000000000..d3ec87665ccdf --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/README.md @@ -0,0 +1,77 @@ +# Azure ResourceManager Core client library for .NET + +This package follows the [new Azure SDK guidelines](https://azure.github.io/azure-sdk/general_introduction.html) which provide a number of core capabilities that are shared amongst all Azure SDKs, including the intuitive Azure Identity library, an HTTP Pipeline with custom policies, error-handling, distributed tracing, and much more. + +## Getting started + +### Install the package + +Install the Azure Resources management core library for .NET with [NuGet](https://www.nuget.org/): + +```PowerShell +Install-Package Azure.ResourceManager.Core -Version 1.0.0-beta.1 +``` + +### Prerequisites + +* You must have an [Azure subscription](https://azure.microsoft.com/free/) + +### Authenticate the Client + +To create an authenticated client and start interacting with Azure resources, please see the [quickstart guide here](https://github.com/Azure/azure-sdk-for-net/blob/master/doc/mgmt_preview_quickstart.md) + +## Key concepts + +Key concepts of the Azure .NET SDK can be found [here](https://azure.github.io/azure-sdk/dotnet_introduction.html) + +## Documentation + +Documentation is available to help you learn how to use this package + +- [Quickstart](https://github.com/Azure/azure-sdk-for-net/blob/master/doc/mgmt_preview_quickstart.md) +- [API References](https://docs.microsoft.com/dotnet/api/?view=azure-dotnet) +- [Authentication](https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/identity/Azure.Identity/README.md) + +## Examples + +Code samples for using the management library for .NET can be found in the following locations +- [.NET Management Library Code Samples](https://docs.microsoft.com/samples/browse/?branch=master&languages=csharp&term=managing%20using%20Azure%20.NET%20SDK) + +## Troubleshooting + +- File an issue via [Github + Issues](https://github.com/Azure/azure-sdk-for-net/issues) +- Check [previous + questions](https://stackoverflow.com/questions/tagged/azure+.net) + or ask new ones on Stack Overflow using azure and .net tags. + + +## Next steps + +For more information on Azure SDK, please refer to [this website](https://azure.github.io/azure-sdk/) + +## Contributing + +For details on contributing to this repository, see the contributing +guide. + +This project welcomes contributions and suggestions. Most contributions +require you to agree to a Contributor License Agreement (CLA) declaring +that you have the right to, and actually do, grant us the rights to use +your contribution. For details, visit . + +When you submit a pull request, a CLA-bot will automatically determine +whether you need to provide a CLA and decorate the PR appropriately +(e.g., label, comment). Simply follow the instructions provided by the +bot. You will only need to do this once across all repositories using +our CLA. + +This project has adopted the Microsoft Open Source Code of Conduct. For +more information see the Code of Conduct FAQ or contact + with any additional questions or comments. + + +[style-guide-msft]: https://docs.microsoft.com/style-guide/capitalization +[style-guide-cloud]: https://aka.ms/azsdk/cloud-style-guide + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-net%2Fsdk%2Ftemplate%2FAzure.Template%2FREADME.png) diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/PhArmResponse.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/PhArmResponse.cs new file mode 100644 index 0000000000000..c764cedd3366f --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/PhArmResponse.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; + +namespace Azure.ResourceManager.Core +{ + /// + /// Placeholder class, used to convert the gewneric type argument for a response from the underlyign rest API to the + /// desired type argument in the response + /// + /// The to convert the TModel into. + /// The model returned by the existing serivce calls. + public class PhArmResponse : ArmResponse + where TOperations : class + where TModel : class + { + private readonly Func _converter; + private readonly Response _wrapped; + + /// + /// Initializes a new instance of the class. + /// + /// The results to wrap. + /// The function used to convert from existing type to new type. + public PhArmResponse(Response wrapped, Func converter) + { + _wrapped = wrapped; + _converter = converter; + } + + /// + public override TOperations Value => _converter(_wrapped.Value); + + /// + public override Response GetRawResponse() + { + return _wrapped.GetRawResponse(); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/PhTaskDeferringAsyncPageable.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/PhTaskDeferringAsyncPageable.cs new file mode 100644 index 0000000000000..0740e1668a50c --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/PhTaskDeferringAsyncPageable.cs @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Core.Adapters +{ + /// + /// A class repreesnting an AsyncPageable that executes a given task before retrieving the first page of results + /// + /// The type of that will be returned. + public class PhTaskDeferringAsyncPageable : AsyncPageable + where TOperations : notnull + { + private readonly Func>> _task; + + /// + /// Initializes a new instance of the class. + /// + /// The function to execute returning the AsyncPageable task. + public PhTaskDeferringAsyncPageable(Func>> task) + { + _task = task; + } + + /// + public override async IAsyncEnumerable> AsPages( + string continuationToken = null, + int? pageSizeHint = null) + { + await foreach (var page in (await _task().ConfigureAwait(false)).AsPages().ConfigureAwait(false)) + { + yield return page; + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/PhWrappingAsyncPageable.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/PhWrappingAsyncPageable.cs new file mode 100644 index 0000000000000..a15098cf7eee5 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/PhWrappingAsyncPageable.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Core +{ + /// + /// Returns an AsyncPageable that transforms each page of contents after they are retrieved from the server + /// according to the profived transformation function + /// + /// The model returned by existing AsyncPageable methods. + /// The to convert TModel into. + public class PhWrappingAsyncPageable : AsyncPageable + where TOperations : class + where TModel : class + { + private readonly Func _converter; + private readonly IEnumerable> _wrapped; + + /// + /// Initializes a new instance of the class. + /// + /// The results to wrap. + /// The function used to convert from existing type to new type. + public PhWrappingAsyncPageable(AsyncPageable wrapped, Func converter) + { + _wrapped = new[] { wrapped }; + _converter = converter; + } + + /// + /// Initializes a new instance of the class. + /// + /// The results to wrap. + /// The function used to convert from existing type to new type. + public PhWrappingAsyncPageable(IEnumerable> wrapped, Func converter) + { + _wrapped = wrapped; + _converter = converter; + } + + /// + public override async IAsyncEnumerable> AsPages( + string continuationToken = null, + int? pageSizeHint = null) + { + foreach (var pageEnum in _wrapped) + { + await foreach (var page in pageEnum.AsPages().WithCancellation(CancellationToken)) + { + yield return new WrappingPage(page, _converter); + } + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/PhWrappingPageable.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/PhWrappingPageable.cs new file mode 100644 index 0000000000000..c11077cb01072 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/PhWrappingPageable.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Core +{ + /// + /// This class allows performing conversions on pages of data as they are accessed - used in the prototype to convett + /// between underlying model types and the new model types that extend Resource, + /// and also for returning Operations classes for those underlying objects. + /// + /// The type parameter of the Pageable we are wrapping. + /// The desired type parameter of the returned pageable. + public class PhWrappingPageable : Pageable + where TOperations : class + where TModel : class + { + private readonly Func _converter; + private readonly IEnumerable> _wrapped; + + /// + /// Initializes a new instance of the class. + /// + /// The results to wrap. + /// The function used to convert from existing type to new type. + public PhWrappingPageable(Pageable wrapped, Func converter) + { + _wrapped = new[] { wrapped }; + _converter = converter; + } + + /// + /// Initializes a new instance of the class. + /// + /// The results to wrap. + /// The function used to convert from existing type to new type. + public PhWrappingPageable(IEnumerable> wrapped, Func converter) + { + _wrapped = wrapped; + _converter = converter; + } + + /// + public override IEnumerable> AsPages(string continuationToken = null, int? pageSizeHint = null) + { + foreach (var pages in _wrapped) + { + foreach (var page in pages.AsPages()) + { + yield return new WrappingPage(page, _converter); + } + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/ProxyResource.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/ProxyResource.cs new file mode 100644 index 0000000000000..ac7ce5335c1b4 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/ProxyResource.cs @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing a generic proxy resource in Azure + /// + /// The type of the underlying model this class wraps + public abstract class ProxyResource : Resource + where TModel : class + { + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the resource that is the target of operations. + /// The model to copy from. + protected ProxyResource(ResourceIdentifier id, TModel data) + { + Id = id; + Model = data; + } + + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the resource that is the target of operations. + /// The model to copy from. + protected ProxyResource(string id, TModel data) + { + if (ReferenceEquals(id, null)) + { + Id = null; + } + else + { + Id = id; + } + + Model = data; + } + + /// + /// Gets or sets the identifier for the resource. + /// + public override ResourceIdentifier Id { get; protected set; } + + /// + /// Gets or sets the Model this resource is based off. + /// + public virtual TModel Model { get; set; } + + /// + /// Converts from a into the TModel. + /// + /// The tracked resource convert from. + public static implicit operator TModel(ProxyResource other) + { + return other.Model; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/TrackedResource.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/TrackedResource.cs new file mode 100644 index 0000000000000..f6aed917167f9 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/TrackedResource.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.ResourceManager.Resources.Models; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing a generic tracked resource in Azure. + /// + /// The type of the underlying model this class wraps + public abstract class TrackedResource : TrackedResource + where TModel : class + { + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the resource that is the target of operations. + /// The location of the resource. + /// The model to copy from. + protected TrackedResource(ResourceIdentifier id, LocationData location, TModel data) + { + Id = id; + Location = location; + Model = data; + } + + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the resource that is the target of operations. + /// The location of the resource. + /// The model to copy from. + protected TrackedResource(string id, LocationData location, TModel data) + { + if (ReferenceEquals(id, null)) + { + Id = null; + } + else + { + Id = id; + } + + Location = location; + Model = data; + } + + /// + /// Gets or sets the Model this resource is based off. + /// + public virtual TModel Model { get; set; } + + /// + /// Converts from a into the TModel. + /// + /// The tracked resource convert from. + public static implicit operator TModel(TrackedResource other) + { + return other.Model; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/WrappingPage.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/WrappingPage.cs new file mode 100644 index 0000000000000..821f8aaff7255 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Adapters/WrappingPage.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing a wrapper over + /// + /// The type parameter we are wrapping. + /// The desired type parameter of the returned page. + internal class WrappingPage : Page + where TOperations : class + where TModel : class + { + private readonly Func _converter; + private readonly Page _wrapped; + + /// + /// Initializes a new instance of the class. + /// + /// The results to wrap. + /// The function used to convert from existing type to new type. + internal WrappingPage(Page wrapped, Func converter) + { + _wrapped = wrapped; + _converter = converter; + } + + /// + public override IReadOnlyList Values => _wrapped.Values.Select(_converter).ToImmutableList(); + + /// + public override string ContinuationToken => _wrapped.ContinuationToken; + + /// + public override Response GetRawResponse() + { + return _wrapped.GetRawResponse(); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ApiVersionsBase.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ApiVersionsBase.cs new file mode 100644 index 0000000000000..d542b5b532a00 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ApiVersionsBase.cs @@ -0,0 +1,204 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Text.RegularExpressions; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing Azure resource API versions base. + /// + public class ApiVersionsBase : IEquatable, IComparable + { + private readonly string _value; + + /// + /// Initializes a new instance of the class. + /// + /// The API version value. + protected ApiVersionsBase(string value) + { + _value = value; + } + + /// + /// + /// + /// + /// + /// + public static bool operator <(ApiVersionsBase left, ApiVersionsBase right) + { + if (left is null) + return true; + + return left.CompareTo(right) == -1; + } + + /// + /// + /// + /// + /// + /// + public static bool operator >(ApiVersionsBase left, ApiVersionsBase right) + { + if (left is null) + return false; + + return left.CompareTo(right) == 1; + } + + /// + /// Implicit operator to convert ApiVersionsBase to string. + /// + /// The ApiVersionsBase object. + /// API version value. + public static implicit operator string(ApiVersionsBase version) + { + return version._value; + } + + /// + /// Overrides == operator for comparing ApiVersionsBase object with string object. + /// + /// The ApiVersionsBase object to compare. + /// The API version value in string to compare. + /// Comparison result in boolean. Equal returns true otherwise returns false. + public static bool operator ==(ApiVersionsBase first, string second) + { + if (ReferenceEquals(null, first)) + { + return ReferenceEquals(null, second); + } + + if (ReferenceEquals(null, second)) + { + return false; + } + + return first.Equals(second); + } + + /// + /// Overrides != operator for comparing ApiVersionsBase object with string object. + /// + /// The ApiVersionsBase object to compare. + /// The API version value in string to compare. + /// Comparison result in boolean. Equal returns false otherwise returns true. + public static bool operator !=(ApiVersionsBase first, string second) + { + if (ReferenceEquals(null, first)) + { + return !ReferenceEquals(null, second); + } + + if (ReferenceEquals(null, second)) + { + return true; + } + + return !first.Equals(second); + } + + /// + /// Compares two API version values in string type. + /// + /// The API version value to compare. + /// Comparison result in integer. 1 for greater than, 0 for equals to, and -1 for less than. + public int CompareTo(string other) + { + if (other == null) + { + return 1; + } + + var regPattern = @"(\d\d\d\d-\d\d-\d\d)(.*)"; + + var otherMatch = Regex.Match(other, regPattern); + var thisMatch = Regex.Match(_value, regPattern); + + var otherDatePart = otherMatch.Groups[1].Value; + var thisDatePart = thisMatch.Groups[1].Value; + + if (otherDatePart == thisDatePart) + { + var otherPreviewPart = otherMatch.Groups[2].Value; + var thisPreviewPart = thisMatch.Groups[2].Value; + + if (otherPreviewPart == thisPreviewPart) + { + return 0; + } + + if (string.IsNullOrEmpty(otherPreviewPart)) + { + return -1; + } + + if (string.IsNullOrEmpty(thisPreviewPart)) + { + return 1; + } + + return string.Compare(thisPreviewPart, otherPreviewPart, StringComparison.InvariantCulture); + } + + return string.Compare(thisDatePart, otherDatePart, StringComparison.InvariantCulture); + } + + /// + /// Compares the API version value in ApiVersionsBase object and the one in string. + /// + /// The API version value to compare. + /// Comparison result in boolean. Equal returns true otherwise returns false. + public bool Equals(string other) + { + if (other == null) + { + return false; + } + + return other == _value; + } + + /// + /// Converts ApiVersionsBase object to string. + /// + /// The API version value. + public override string ToString() + { + return _value; + } + + /// + /// Compares the API version value in ApiVersionsBase object and the one in object. + /// + /// The object to compare. + /// Comparison result in boolean. Equal returns true otherwise returns false. + public override bool Equals(object obj) + { + if (obj is ApiVersionsBase) + { + return Equals(obj as ApiVersionsBase); + } + + if (obj is string) + { + return Equals(obj as string); + } + + return false; + } + + /// + /// Gets the hash code of the API version value. + /// + /// The hash code of the API version value. + public override int GetHashCode() + { + return _value.GetHashCode(); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ArmBuilder.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ArmBuilder.cs new file mode 100644 index 0000000000000..353a316d5b792 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ArmBuilder.cs @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing a builder object used to create Azure resources. + /// + /// The type of the operations class for a specific resource. + /// The type of the class containing properties for the underlying resource. + public class ArmBuilder + where TResource : Resource + where TOperations : ResourceOperationsBase + { + /// + /// Initializes a new instance of the class. + /// + /// The container object to create the resource in. + /// The resource to create. + public ArmBuilder(ResourceContainerBase container, TResource resource) + { + Resource = resource; + UnTypedContainer = container; + } + + /// + /// Gets the resource object to create. + /// + protected TResource Resource { get; private set; } + + /// + /// Gets the resource name. + /// + protected string ResourceName { get; private set; } + + /// + /// Gets the container object to create the resource in. + /// + protected ResourceContainerBase UnTypedContainer { get; private set; } + + /// + /// Creates the resource object to send to the Azure API. + /// + /// The resource to create. + public TResource Build() + { + ThrowIfNotValid(); + OnBeforeBuild(); + InternalBuild(); + OnAfterBuild(); + + return Resource; + } + + /// + /// The operation to create or update a resource. Please note some properties can be set only during creation. + /// + /// The name of the new resource to create. + /// A response with the operation for this resource. + public ArmResponse CreateOrUpdate(string name) + { + ResourceName = name; + Resource = Build(); + + return UnTypedContainer.CreateOrUpdate(name, Resource); + } + + /// + /// The operation to create or update a resource. Please note some properties can be set only during creation. + /// + /// The name of the new resource to create. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + public async Task> CreateOrUpdateAsync( + string name, + CancellationToken cancellationToken = default) + { + ResourceName = name; + Resource = Build(); + + return await UnTypedContainer.CreateOrUpdateAsync(name, Resource, cancellationToken).ConfigureAwait(false); + } + + /// + /// The operation to create or update a resource. Please note some properties can be set only during creation. + /// + /// The name of the new resource to create. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An that allows polling for completion of the operation. + /// + /// Details on long running operation object. + /// + public ArmOperation StartCreateOrUpdate(string name, CancellationToken cancellationToken = default) + { + ResourceName = name; + Resource = Build(); + + return UnTypedContainer.StartCreateOrUpdate(name, Resource, cancellationToken); + } + + /// + /// The operation to create or update a resource. Please note some properties can be set only during creation. + /// + /// The name of the new resource to create. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns an that allows polling for completion of the operation. + /// + /// Details on long running operation object. + /// + public async Task> StartCreateOrUpdateAsync( + string name, + CancellationToken cancellationToken = default) + { + ResourceName = name; + Resource = Build(); + + return await UnTypedContainer.StartCreateOrUpdateAsync(name, Resource, cancellationToken).ConfigureAwait(false); + } + + /// + /// Determines whether or not the resource is valid. + /// + /// The message indicating what is wrong with the resource. + /// Whether or not the resource is valid. + protected virtual bool IsValid(out string message) + { + message = string.Empty; + + return true; + } + + /// + /// Perform any tasks necessary after the resource is built + /// + protected virtual void OnAfterBuild() + { + } + + /// + /// Perform any tasks necessary before the resource is built + /// + protected virtual void OnBeforeBuild() + { + } + + private static void InternalBuild() + { + } + + private void ThrowIfNotValid() + { + if (!IsValid(out var message)) + { + throw new InvalidOperationException(message); + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ArmOperation.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ArmOperation.cs new file mode 100644 index 0000000000000..18caabd837a3c --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ArmOperation.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Azure.ResourceManager.Core +{ + /// + /// Abstract class for long-running or synchronous applications. + /// + /// The to return representing the result of the ArmOperation. + public abstract class ArmOperation : Operation + { + /// + /// Initializes a new instance of the class. + /// + /// The representing the result of the ArmOperation. + protected ArmOperation(TOperations syncValue) + { + CompletedSynchronously = syncValue != null; + SyncValue = syncValue; + } + + /// + /// Gets a value indicating whether or not the operation completed synchronously. + /// + protected bool CompletedSynchronously { get; } + + /// + /// Gets the representing the result of the ArmOperation. + /// + protected TOperations SyncValue { get; } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ArmResponse.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ArmResponse.cs new file mode 100644 index 0000000000000..d130fc8186316 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ArmResponse.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing a response object from azure resource manager service. + /// + public sealed class ArmResponse : ArmResponse + { + private readonly Response _response; + + /// + /// Initializes a new instance of the class. + /// + /// The azure response object to wrap. + public ArmResponse(Response response) + { + _response = response; + } + + /// + public override Response Value => _response; + + /// + public override Response GetRawResponse() + { + return _response; + } + } + + /// + /// A class representing a response object from azure resource manager service. + /// + /// The operations object return by the api call. + [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:File may only contain a single type", Justification = "Allowed when we have a generic version of the same type")] + public abstract class ArmResponse : Response + { + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ArmVoidOperation.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ArmVoidOperation.cs new file mode 100644 index 0000000000000..bbab26ea2456e --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ArmVoidOperation.cs @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Core +{ + /// + /// Generic ARM long running operation class for operations with no returned value + /// + public sealed class ArmVoidOperation : ArmOperation + { + private readonly Operation _wrapped; + + /// + /// Initializes a new instance of the class. + /// + /// The operation that has a response which has no body. + public ArmVoidOperation(Operation other) + : base(null) + { + _wrapped = other; + } + + /// + /// Initializes a new instance of the class. + /// + /// The response which has no body. + public ArmVoidOperation(Response other) + : base(other) + { + } + + /// + public override string Id => _wrapped?.Id; + + /// + public override Response Value => SyncValue; + + /// + public override bool HasCompleted => CompletedSynchronously || _wrapped.HasCompleted; + + /// + public override bool HasValue => CompletedSynchronously || _wrapped.HasValue; + + /// + public override Response GetRawResponse() + { + return CompletedSynchronously ? SyncValue : _wrapped.GetRawResponse(); + } + + /// + public override Response UpdateStatus(CancellationToken cancellationToken = default) + { + return CompletedSynchronously ? SyncValue : _wrapped.UpdateStatus(cancellationToken); + } + + /// + public override async ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) + { + return CompletedSynchronously ? SyncValue : await _wrapped.UpdateStatusAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public override async ValueTask> WaitForCompletionAsync( + CancellationToken cancellationToken = default) + { + return CompletedSynchronously + ? new WrappingResponse(SyncValue) + : await _wrapped.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public override async ValueTask> WaitForCompletionAsync( + TimeSpan pollingInterval, + CancellationToken cancellationToken) + { + return CompletedSynchronously + ? new WrappingResponse(SyncValue) + : await _wrapped.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false); + } + + /// + /// A class which wraps a response with no body. + /// + internal class WrappingResponse : ArmResponse + { + private readonly Response _wrapped; + + /// + /// Initializes a new instance of the class. + /// + /// The response object to wrap. + public WrappingResponse(Response wrapped) + { + _wrapped = wrapped; + } + + /// + public override Response Value => _wrapped; + + /// + public override Response GetRawResponse() + { + return _wrapped; + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Azure.ResourceManager.Core.csproj b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Azure.ResourceManager.Core.csproj new file mode 100644 index 0000000000000..364c9d64f576c --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Azure.ResourceManager.Core.csproj @@ -0,0 +1,22 @@ + + + + 1.0.0-beta.1 + Azure.ResourceManager.Core + + Azure management core SDK for Azure resources. + This is a beta preview vesion. This version uses a next-generation code generator that introduces important breaking changes, but also new features (such as intuitive authentication, custom HTTP pipeline, distributed tracing and much more). + + azure;management;resource + $(NoWarn);AZC0008;AZC0001;AZC0107;CA2214;CA1036;CA1067;CA1065;SA1028 + true + + + + + + + + + + diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/AzureResourceManagerClient.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/AzureResourceManagerClient.cs new file mode 100644 index 0000000000000..e5db0c8bee2e7 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/AzureResourceManagerClient.cs @@ -0,0 +1,185 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core; +using Azure.Identity; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; + +namespace Azure.ResourceManager.Core +{ + /// + /// The entry point for all ARM clients. + /// + public class AzureResourceManagerClient + { + /// + /// The base URI of the service. + /// + internal const string DefaultUri = "https://management.azure.com"; + + private readonly TokenCredential _credentials; + + private readonly Uri _baseUri; + + /// + /// Initializes a new instance of the class for mocking. + /// + protected AzureResourceManagerClient() + : this(null, null, new DefaultAzureCredential(), new AzureResourceManagerClientOptions()) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + public AzureResourceManagerClient(AzureResourceManagerClientOptions options = default) + : this(null, null, new DefaultAzureCredential(), options) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// A credential used to authenticate to an Azure Service. + /// The client parameters to use in these operations. + public AzureResourceManagerClient(TokenCredential credential, AzureResourceManagerClientOptions options = default) + : this(null, null, credential, options) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The id of the default Azure subscription. + /// A credential used to authenticate to an Azure Service. + /// The client parameters to use in these operations. + public AzureResourceManagerClient(string defaultSubscriptionId, TokenCredential credential, AzureResourceManagerClientOptions options = default) + : this(defaultSubscriptionId, null, credential, options) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The base URI of the service. + /// A credential used to authenticate to an Azure Service. + /// The client parameters to use in these operations. + public AzureResourceManagerClient(Uri baseUri, TokenCredential credential, AzureResourceManagerClientOptions options = default) + : this(null, baseUri, credential, options) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The id of the default Azure subscription. + /// The base URI of the service. + /// A credential used to authenticate to an Azure Service. + /// The client parameters to use in these operations. + private AzureResourceManagerClient(string defaultSubscriptionId, Uri baseUri, TokenCredential credential, AzureResourceManagerClientOptions options = default) + { + _credentials = credential; + _baseUri = baseUri; + ClientOptions = options ?? new AzureResourceManagerClientOptions(); + + if (string.IsNullOrWhiteSpace(defaultSubscriptionId)) + { + DefaultSubscription = GetDefaultSubscription(); + } + else + { + DefaultSubscription = GetSubscriptionOperations(defaultSubscriptionId).Get().Value; + } + + ApiVersionOverrides = new Dictionary(); + } + + /// + /// Gets the Api version overrides. + /// + public Dictionary ApiVersionOverrides { get; private set; } + + /// + /// Gets the default Azure subscription. + /// + public Subscription DefaultSubscription { get; private set; } + + /// + /// Gets the Azure resource manager client options. + /// + internal AzureResourceManagerClientOptions ClientOptions { get; } + + /// + /// Gets the Azure subscription operations. + /// + /// The guid of the subscription. + /// Subscription operations. + public SubscriptionOperations GetSubscriptionOperations(string subscriptionGuid) => new SubscriptionOperations( + ClientOptions, + subscriptionGuid, + _credentials, + _baseUri); + + /// + /// Gets the Azure subscriptions. + /// + /// Subscription container. + public SubscriptionContainer GetSubscriptionContainer() + { + return new SubscriptionContainer(ClientOptions, _credentials, _baseUri); + } + + /// + /// Gets resource group operations. + /// + /// The id of the Azure subscription. + /// The resource group name. + /// Resource group operations. + public ResourceGroupOperations GetResourceGroupOperations(string subscriptionGuid, string resourceGroupName) + { + return GetSubscriptionOperations(subscriptionGuid).GetResourceGroupOperations(resourceGroupName); + } + + /// + /// Gets resource group operations. + /// + /// The resource identifier of the resource group. + /// Resource group operations. + public ResourceGroupOperations GetResourceGroupOperations(ResourceIdentifier resourceGroupId) + { + return GetSubscriptionOperations(resourceGroupId.Subscription).GetResourceGroupOperations(resourceGroupId.ResourceGroup); + } + + /// + /// Gets resource operations base. + /// + /// The type of the underlying model this class wraps. + /// The id of the Azure subscription. + /// The resource group name. + /// The resource type name. + /// Resource operations of the resource. + public T GetResourceOperations(string subscription, string resourceGroup, string name) + where T : OperationsBase + { + var rgOp = GetSubscriptionOperations(subscription).GetResourceGroupOperations(resourceGroup); + return Activator.CreateInstance( + typeof(T), + System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, + null, + new object[] { rgOp, name }, + CultureInfo.InvariantCulture) as T; + } + + private Subscription GetDefaultSubscription() + { + var sub = GetSubscriptionContainer().List().FirstOrDefault(); + if (sub is null) + throw new Exception("No subscriptions found for the given credentials"); + return sub; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/AzureResourceManagerClientOptions.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/AzureResourceManagerClientOptions.cs new file mode 100644 index 0000000000000..2b6e0a8a2753a --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/AzureResourceManagerClientOptions.cs @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core; +using Azure.Core.Pipeline; +using System; +using System.Collections.Generic; +using System.ComponentModel; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing Azure resource manager client options. + /// + public sealed class AzureResourceManagerClientOptions : ClientOptions + { + private static readonly object _overridesLock = new object(); + + private Dictionary _overrides = new Dictionary(); + + /// + /// Initializes a new instance of the class. + /// + public AzureResourceManagerClientOptions() + : this(LocationData.Default, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The default location to use if can't be inherited from parent. + public AzureResourceManagerClientOptions(LocationData defaultLocation) + : this(defaultLocation, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The default location to use if can't be inherited from parent. + /// The client parameters to use in these operations. + internal AzureResourceManagerClientOptions(LocationData defaultLocation, AzureResourceManagerClientOptions other = null) + { + // Will go away when moved into core since we will have directy acces the policies and transport, so just need to set those + if (!ReferenceEquals(other, null)) + Copy(other); + DefaultLocation = defaultLocation; + } + + /// + /// Gets the default location to use if can't be inherited from parent. + /// + public LocationData DefaultLocation { get; } + + /// + /// Gets each http call policies. + /// + /// A collection of http pipeline policy that may take multiple service requests to iterate over. + internal IList PerCallPolicies { get; } = new List(); + + /// + /// Gets each http retry call policies. + /// + /// A collection of http pipeline policy that may take multiple service requests to iterate over. + internal IList PerRetryPolicies { get; } = new List(); + + /// + /// Converts client options. + /// + /// The type of the underlying model this class wraps. + /// The converted client options. + public T Convert() + where T : ClientOptions, new() + { + var newOptions = new T(); + newOptions.Transport = Transport; + foreach (var pol in PerCallPolicies) + { + newOptions.AddPolicy(pol, HttpPipelinePosition.PerCall); + } + + foreach (var pol in PerRetryPolicies) + { + newOptions.AddPolicy(pol, HttpPipelinePosition.PerRetry); + } + + return newOptions; + } + + /// + /// Adds a policy for Azure resource manager client http call. + /// + /// The http call policy in the pipeline. + /// The position of the http call policy in the pipeline. + public new void AddPolicy(HttpPipelinePolicy policy, HttpPipelinePosition position) + { + // TODO policy lists are internal hence we don't have acces to them by inheriting ClientOptions in this Asembly, this is a wrapper for now to convert to the concrete + // policy options. + switch (position) + { + case HttpPipelinePosition.PerCall: + PerCallPolicies.Add(policy); + break; + case HttpPipelinePosition.PerRetry: + PerRetryPolicies.Add(policy); + break; + default: + throw new ArgumentOutOfRangeException(nameof(position), position, null); + } + + base.AddPolicy(policy, position); + } + + /// + /// Gets override object. + /// + /// The type of the underlying model this class wraps. + /// A function which returns an object. + /// The override object. + [EditorBrowsable(EditorBrowsableState.Never)] + public object GetOverrideObject(Func ctor) + { + object overrideObject; + Type type = typeof(T); + if (!_overrides.TryGetValue(type, out overrideObject)) + { + lock (_overridesLock) + { + if (!_overrides.TryGetValue(type, out overrideObject)) + { + overrideObject = ctor(); + _overrides[type] = overrideObject; + } + } + } + + return overrideObject; + } + + // Will be removed like AddPolicy when we move to azure core + private void Copy(AzureResourceManagerClientOptions other) + { + Transport = other.Transport; + foreach (var pol in other.PerCallPolicies) + { + AddPolicy(pol, HttpPipelinePosition.PerCall); + } + + foreach (var pol in other.PerRetryPolicies) + { + AddPolicy(pol, HttpPipelinePosition.PerRetry); + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ContainerBase.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ContainerBase.cs new file mode 100644 index 0000000000000..16cc90042c8a6 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ContainerBase.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core; +using System; +using System.Globalization; + +namespace Azure.ResourceManager.Core +{ + /// + /// Base class representing collection of resources. + /// + /// The type of the class containing operations for the underlying resource. + public abstract class ContainerBase : OperationsBase + where TOperations : ResourceOperationsBase + { + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + /// A credential used to authenticate to an Azure Service. + /// The base URI of the service. + protected ContainerBase(AzureResourceManagerClientOptions options, ResourceIdentifier id, TokenCredential credential, Uri baseUri) + : base(options, id, credential, baseUri) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The resource representing the parent resource. + protected ContainerBase(ResourceOperationsBase parent) + : base(parent.ClientOptions, parent.Id, parent.Credential, parent.BaseUri) + { + Parent = parent; + } + + /// + /// Gets the parent resource of this resource + /// + protected ResourceOperationsBase Parent { get; } + + /// + /// Returns the resource from Azure if it exists + /// + /// The name of the resource you want to get. + /// The resource if it existed, null otherwise. + /// Whether or not the resource existed. + public virtual bool TryGetValue(string resourceName, out ArmResponse resource) + { + var op = GetOperation(resourceName); + + try + { + resource = op.Get(); + return true; + } + catch + { + resource = null; + return false; + } + } + + /// + /// Determines whether or not the azure resource exists in this container + /// + /// The name of the resource you want to check. + /// Whether or not the resource existed. + public virtual bool DoesExist(string resourceName) + { + ArmResponse output; + return TryGetValue(resourceName, out output); + } + + /// + /// Get an instance of the operations this container holds. + /// + /// The name of the resource to scope the operations to. + /// An instance of . + protected virtual ResourceOperationsBase GetOperation(string resourceName) + { + return Activator.CreateInstance( + typeof(TOperations).BaseType, + System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, + null, + new object[] { Parent, resourceName }, + CultureInfo.InvariantCulture) as ResourceOperationsBase; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ExtensionResourceContainer.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ExtensionResourceContainer.cs new file mode 100644 index 0000000000000..a04a28023eb26 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ExtensionResourceContainer.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Threading; +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Core +{ + /// + /// Container for extension resources. Because there is no CreateOrUpdate, there is a difference in the input and output model + /// + /// Operations class returned. + /// Input Model. + public abstract class ExtensionResourceContainer : ExtensionResourceOperationsBase + where TOperations : ExtensionResourceOperationsBase + where TInput : class + { + /// + /// Initializes a new instance of the class. + /// Create an ResourceContainer from an operations class or client + /// + /// The operations to copy the client options from. + protected ExtensionResourceContainer(OperationsBase operations) + : base(operations) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The operations to copy the client options from. + /// The resource Id of the parent resource. + protected ExtensionResourceContainer(OperationsBase operations, ResourceIdentifier parentId) + : base(operations, parentId) + { + } + + /// + /// Validate that the given resource Id represents a valid parent for this resource + /// + /// The resource Id of the parent resource. + protected override void Validate(ResourceIdentifier identifier) + { + } + + /// + /// Create a new extension resource at the given scope. Block further execution on the current thread until creation is complete. + /// + /// The name of the created extension resource. + /// The properties of the extension resource. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An Http envelope containing the operations for the given extension. + public abstract ArmResponse Create(string name, TInput resourceDetails, CancellationToken cancellationToken = default); + + /// + /// Create a new extension resource at the given scope without blocking the current thread. + /// Returns a Task that allows control over when or if the thread is blocked. + /// + /// The name of the created extension resource. + /// The properties of the extension resource. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A Task that creates the extension resource. + public abstract Task> CreateAsync(string name, TInput resourceDetails, CancellationToken cancellationToken = default); + + /// + /// Begin Creation of a new extension resource. Block until the creation is accepted by the service. + /// The returned object allows fine-grained control over waiting for creation to complete. + /// + /// The name of the created extension resource. + /// The properties of the extension resource. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An instance of , allowing fine grained control over waiting for creation to complete. + public abstract ArmOperation StartCreate(string name, TInput resourceDetails, CancellationToken cancellationToken = default); + + /// + /// Begin Creation of a new extension resource in a background task. + /// When creation has successfully begin, the object returned from the completed task allows fine-grained control over waiting for creation to complete. + /// + /// The name of the created extension resource. + /// The properties of the extension resource. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns an that allows polling for completion of the operation. + public abstract Task> StartCreateAsync(string name, TInput resourceDetails, CancellationToken cancellationToken = default); + + /// + /// Lists the extension resources at the current scope. Blocks until the first page of results is returned. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An instance of allowing paged or non-paged enumeration of results. + public abstract Pageable ListAtScope(CancellationToken cancellationToken = default); + + /// + /// Lists the extension resources at the current scope asynchronously. The returned task completes when the first page of results is returned. + /// + /// The cancellation token clients can use to cancel any blocking HTTP requests made by this method, including + /// any Http requests that result from enumerating pages of results. + /// An instance of allowing asynchronous paged or non-paged enumeration of results. + public abstract AsyncPageable ListAtScopeAsync(CancellationToken cancellationToken = default); + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ExtensionResourceOperationsBase.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ExtensionResourceOperationsBase.cs new file mode 100644 index 0000000000000..ca83225f60b32 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ExtensionResourceOperationsBase.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Threading; +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Core +{ + /// + /// Base class for all extensions + /// + public abstract class ExtensionResourceOperationsBase : OperationsBase + { + /// + /// Initializes a new instance of the class. + /// + /// The operations to copy the client options from. + protected ExtensionResourceOperationsBase(OperationsBase genericOperations) + : base(genericOperations.ClientOptions, genericOperations.Id, genericOperations.Credential, genericOperations.BaseUri) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The operations to copy the client options from. + /// The identifier of the extension resource. + protected ExtensionResourceOperationsBase(OperationsBase genericOperations, ResourceIdentifier id) + : base(genericOperations.ClientOptions, id, genericOperations.Credential, genericOperations.BaseUri) + { + } + } + + /// + /// Separate Extension resources from non-extension resources + /// + /// The typed operations class for a specific resource. + [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:File may only contain a single type", Justification = "Resource types that differ by Type arguments")] + public abstract class ExtensionResourceOperationsBase : ExtensionResourceOperationsBase + where TOperations : ExtensionResourceOperationsBase + { + /// + /// Initializes a new instance of the class. + /// + /// The operations to copy the client options from. + protected ExtensionResourceOperationsBase(OperationsBase genericOperations) + : base(genericOperations) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The operations to copy the client options from. + /// The identifier of the extension resource. + protected ExtensionResourceOperationsBase(OperationsBase genericOperations, ResourceIdentifier id) + : base(genericOperations, id) + { + } + + /// + /// Get details and operations for this extension resource. This call will block the thread until details are returned from the service. + /// + /// An Http Response containing details and operations for the extension resource. + public abstract ArmResponse Get(); + + /// + /// Get details and operations for this extension resource. This call returns a Task that completes when the details are returned from the service. + /// + /// A token allowing cancellation of the Http call in the task. + /// A Task that retrieves the resource details. When complete, the task will yield an Http Response + /// containing details and operations for the extension resource. + public abstract Task> GetAsync(CancellationToken cancellationToken = default); + + /// + /// Get details for this resource from the service or can be overriden to provide a cached instance. + /// + /// A operation for this resource. + protected virtual TOperations GetResource() + { + return Get().Value; + } + + /// + /// Get details for this resource from the service or can be overriden to provide a cached instance. + /// + /// A that on completion returns a operation for this resource. + protected virtual async Task GetResourceAsync() + { + return (await GetAsync().ConfigureAwait(false)).Value; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/GenericResource.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/GenericResource.cs new file mode 100644 index 0000000000000..9a18087929a64 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/GenericResource.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Threading.Tasks; +using Azure.Core; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing a generic azure resource along with the instance operations that can be performed on it. + /// + public class GenericResource : GenericResourceOperations + { + /// + /// Initializes a new instance of the class. + /// + /// The operations object to copy the client parameters from. + /// The data model representing the generic azure resource. + /// If or is null. + internal GenericResource(ResourceOperationsBase operations, GenericResourceData resource) + : base(operations, resource.Id) + { + Data = resource; + } + + /// + /// Gets the data representing this generic azure resource. + /// + public GenericResourceData Data { get; } + + /// + protected override GenericResource GetResource() + { + return this; + } + + /// + protected override Task GetResourceAsync() + { + return Task.FromResult(this); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/GenericResourceData.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/GenericResourceData.cs new file mode 100644 index 0000000000000..84f62ecfee69e --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/GenericResourceData.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing the generic azure resource data model. + /// + public class GenericResourceData : TrackedResource + { + /// + /// Initializes a new instance of the class. + /// + /// The existing resource model to copy from. + /// + /// is null. + /// + public GenericResourceData(ResourceManager.Resources.Models.GenericResource genericResource) + : base(genericResource.Id, genericResource.Location, genericResource) + { + if (genericResource is null) + throw new ArgumentNullException(nameof(genericResource)); + + Tags = new Dictionary(StringComparer.InvariantCultureIgnoreCase); + Tags.ReplaceWith(genericResource.Tags); + + if (Model.Sku != null) + Sku = new Sku(Model.Sku); + + if (Model.Plan != null) + Plan = new Plan(Model.Plan); + + Kind = Model.Kind; + ManagedBy = Model.ManagedBy; + } + + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the resource that is the target of operations. + public GenericResourceData(ResourceIdentifier id) + : base(id, LocationData.Default, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the resource that is the target of operations. + /// The location of the resource. + public GenericResourceData(ResourceIdentifier id, LocationData location) + : base(id, location, null) + { + } + + /// + public override ResourceIdentifier Id { get; protected set; } + + /// + /// Gets or sets who this resource is managed by. + /// + public string ManagedBy { get; set; } + + /// + /// Gets or sets the sku. + /// + public Sku Sku { get; set; } + + /// + /// Gets or sets the plan. + /// + public Plan Plan { get; set; } + + /// + /// Gets or sets the kind. + /// + public string Kind { get; set; } + + /// + /// Gets the Tags. + /// + public override IDictionary Tags { get; } + + /// + /// Converts from a into the ResourceManager.Resources.Models.GenericResource. + /// + /// The tracked resource convert from. + public static implicit operator ResourceManager.Resources.Models.GenericResource(GenericResourceData other) + { + if (other is null) + return null; + + // Temp code. Following block will be removed + other.Model.Tags.Clear(); + foreach (var tag in other.Tags) + { + other.Model.Tags.Add(tag); + } + + return other.Model; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/GenericResourceOperations.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/GenericResourceOperations.cs new file mode 100644 index 0000000000000..ba5051ee88dbd --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/GenericResourceOperations.cs @@ -0,0 +1,245 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core.Pipeline; +using Azure.ResourceManager.Resources; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing the operations that can be performed over a specific ArmResource. + /// + public class GenericResourceOperations : ResourceOperationsBase, ITaggableResource, IDeletableResource + { + private readonly string _apiVersion; + + /// + /// Initializes a new instance of the class. + /// + /// The resource operations to copy the options from. + /// The identifier of the resource that is the target of operations. + internal GenericResourceOperations(ResourceOperationsBase operations, ResourceIdentifier id) + : base(operations, id) + { + _apiVersion = "BAD VALUE"; + } + + /// + protected override ResourceType ValidResourceType => ResourceGroupOperations.ResourceType; + + private ResourcesOperations Operations => new ResourcesManagementClient( + BaseUri, + Id.Subscription, + Credential, + ClientOptions.Convert()).Resources; + + /// + /// Delete the resource. + /// + /// The status of the delete operation. + public ArmResponse Delete() + { + return new ArmResponse(Operations.StartDeleteById(Id, _apiVersion).WaitForCompletionAsync().EnsureCompleted()); + } + + /// + /// Delete the resource. + /// + /// A token allowing immediate cancellation of any blocking call performed during the deletion. + /// A that on completion returns the status of the delete operation. + public async Task> DeleteAsync(CancellationToken cancellationToken = default) + { + var operation = await Operations.StartDeleteByIdAsync(Id, _apiVersion, cancellationToken).ConfigureAwait(false); + var result = await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + return new ArmResponse(result); + } + + /// + /// Delete the resource. + /// + /// A token allowing immediate cancellation of any blocking call performed during the deletion. + /// A which allows the caller to control polling and waiting for resource deletion. + /// The operation yields the final http response to the delete request when complete. + /// + /// Details on long running operation object. + /// + public ArmOperation StartDelete(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(Operations.StartDeleteById(Id, _apiVersion, cancellationToken)); + } + + /// + /// Delete the resource. This call returns a Task that blocks until the delete operation is accepted on the service. + /// + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// A that on completion returns a which + /// allows the caller to control polling and waiting for resource deletion. + /// The operation yields the final http response to the delete request when complete. + /// + /// Details on long running operation object. + /// + public async Task> StartDeleteAsync(CancellationToken cancellationToken = default) + { + var operation = await Operations.StartDeleteByIdAsync(Id, _apiVersion, cancellationToken).ConfigureAwait(false); + return new ArmVoidOperation(operation); + } + + /// + public ArmResponse AddTag(string key, string value) + { + GenericResource resource = GetResource(); + + // Potential optimization on tags set, remove NOOP to bypass the call. + resource.Data.Tags[key] = value; + return new PhArmResponse( + Operations.StartUpdateById(Id, _apiVersion, resource.Data).WaitForCompletionAsync().EnsureCompleted(), + v => new GenericResource(this, new GenericResourceData(v))); + } + + /// + public async Task> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + GenericResource resource = GetResource(); + resource.Data.Tags[key] = value; + var op = await Operations.StartUpdateByIdAsync(Id, _apiVersion, resource.Data, cancellationToken).ConfigureAwait(false); + return new PhArmResponse( + await op.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false), + v => new GenericResource(this, new GenericResourceData(v))); + } + + /// + public ArmOperation StartAddTag(string key, string value) + { + GenericResource resource = GetResource(); + resource.Data.Tags[key] = value; + return new PhArmOperation( + Operations.StartUpdateById(Id, _apiVersion, resource.Data).WaitForCompletionAsync().EnsureCompleted(), + v => new GenericResource(this, new GenericResourceData(v))); + } + + /// + public async Task> StartAddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + GenericResource resource = GetResource(); + resource.Data.Tags[key] = value; + var op = await Operations.StartUpdateByIdAsync(Id, _apiVersion, resource.Data, cancellationToken).ConfigureAwait(false); + return new PhArmOperation( + await op.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false), + v => new GenericResource(this, new GenericResourceData(v))); + } + + /// + public override ArmResponse Get() + { + return new PhArmResponse( + Operations.GetById(Id, _apiVersion), + v => new GenericResource(this, new GenericResourceData(v))); + } + + /// + public override async Task> GetAsync(CancellationToken cancellationToken = default) + { + return new PhArmResponse( + await Operations.GetByIdAsync(Id, _apiVersion, cancellationToken).ConfigureAwait(false), + v => new GenericResource(this, new GenericResourceData(v))); + } + + /// + protected override void Validate(ResourceIdentifier identifier) + { + // TODO: Reenable after Azure.ResourceManager.Resource model has been regenerated + // Currently test cases uses GenericResourceExpended that does not allow construction + // with id. + // if (identifier is null) + // throw new ArgumentNullException(nameof(identifier)); + } + + /// + public ArmResponse SetTags(IDictionary tags) + { + GenericResource resource = GetResource(); + resource.Data.Tags.ReplaceWith(tags); + return new PhArmResponse( + Operations.StartUpdateById(Id, _apiVersion, resource.Data).WaitForCompletionAsync().EnsureCompleted(), + v => new GenericResource(this, new GenericResourceData(v))); + } + + /// + public async Task> SetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + GenericResource resource = GetResource(); + resource.Data.Tags.ReplaceWith(tags); + var op = await Operations.StartUpdateByIdAsync(Id, _apiVersion, resource.Data, cancellationToken).ConfigureAwait(false); + return new PhArmResponse( + await op.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false), + v => new GenericResource(this, new GenericResourceData(v))); + } + + /// + public ArmOperation StartSetTags(IDictionary tags) + { + GenericResource resource = GetResource(); + resource.Data.Tags.ReplaceWith(tags); + return new PhArmOperation( + Operations.StartUpdateById(Id, _apiVersion, resource.Data).WaitForCompletionAsync().EnsureCompleted(), + v => new GenericResource(this, new GenericResourceData(v))); + } + + /// + public async Task> StartSetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + GenericResource resource = GetResource(); + resource.Data.Tags.ReplaceWith(tags); + var op = await Operations.StartUpdateByIdAsync(Id, _apiVersion, resource.Data, cancellationToken).ConfigureAwait(false); + return new PhArmOperation( + await op.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false), + v => new GenericResource(this, new GenericResourceData(v))); + } + + /// + public ArmResponse RemoveTag(string key) + { + GenericResource resource = GetResource(); + resource.Data.Tags.Remove(key); + return new PhArmResponse( + Operations.StartUpdateById(Id, _apiVersion, resource.Data).WaitForCompletionAsync().EnsureCompleted(), + v => new GenericResource(this, new GenericResourceData(v))); + } + + /// + public async Task> RemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + GenericResource resource = GetResource(); + resource.Data.Tags.Remove(key); + var op = await Operations.StartUpdateByIdAsync(Id, _apiVersion, resource.Data, cancellationToken).ConfigureAwait(false); + return new PhArmResponse( + await op.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false), + v => new GenericResource(this, new GenericResourceData(v))); + } + + /// + public ArmOperation StartRemoveTag(string key) + { + GenericResource resource = GetResource(); + resource.Data.Tags.Remove(key); + return new PhArmOperation( + Operations.StartUpdateById(Id, _apiVersion, resource.Data).WaitForCompletionAsync().EnsureCompleted(), + v => new GenericResource(this, new GenericResourceData(v))); + } + + /// + public async Task> StartRemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + GenericResource resource = GetResource(); + resource.Data.Tags.Remove(key); + var op = await Operations.StartUpdateByIdAsync(Id, _apiVersion, resource.Data, cancellationToken).ConfigureAwait(false); + return new PhArmOperation( + await op.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false), + v => new GenericResource(this, new GenericResourceData(v))); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/IDeletableResource.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/IDeletableResource.cs new file mode 100644 index 0000000000000..19b65bfbc691f --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/IDeletableResource.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Threading; +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Core +{ + /// + /// Interface for operations to delete a resource + /// + public interface IDeletableResource + { + /// + /// Delete the resource. + /// + /// The status of the delete operation. + ArmResponse Delete(); + + /// + /// Delete the resource. + /// + /// A token allowing immediate cancellation of any blocking call performed during the deletion. + /// A that on completion returns the status of the delete operation. + Task> DeleteAsync(CancellationToken cancellationToken = default); + + /// + /// Delete the resource. + /// + /// A token allowing immediate cancellation of any blocking call performed during the deletion. + /// A which allows the caller to control polling and waiting for resource deletion. + /// The operation yields the final http response to the delete request when complete. + /// + /// Details on long running operation object. + /// + ArmOperation StartDelete(CancellationToken cancellationToken = default); + + /// + /// Delete the resource. This call returns a Task that blocks until the delete operation is accepted on the service. + /// + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// A that on completion returns a which + /// allows the caller to control polling and waiting for resource deletion. + /// The operation yields the final http response to the delete request when complete. + /// + /// Details on long running operation object. + /// + Task> StartDeleteAsync(CancellationToken cancellationToken = default); + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ITaggableResource.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ITaggableResource.cs new file mode 100644 index 0000000000000..5008ecd50eef2 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ITaggableResource.cs @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Core +{ + /// + /// Interface for operations that allow manipulating resource tags. + /// + /// The typed operations for a specific resource. + public interface ITaggableResource + where TOperations : ResourceOperationsBase + { + /// + /// Add a tag to the resource. + /// + /// The tag key. + /// The tag value. + /// An that allows the user to control polling and waiting for Tag completion. + ArmResponse AddTag(string key, string value); + + /// + /// Add a tag to the resource. + /// + /// The tag key. + /// The tag value. + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// A that performs the Tag operation. The Task yields an an + /// that allows the user to control polling and waiting for + /// Tag completion. + Task> AddTagAsync( + string key, + string value, + CancellationToken cancellationToken = default); + + /// + /// Add a tag to the resource. + /// + /// The tag key. + /// The tag value. + /// An that allows the user to control polling and waiting for Tag completion. + ArmOperation StartAddTag(string key, string value); + + /// + /// Add a tag to the resource. + /// + /// The tag key. + /// The tag value. + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// A that performs the Tag operation. The Task yields an an + /// that allows the user to control polling and waiting for + /// Tag completion. + Task> StartAddTagAsync( + string key, + string value, + CancellationToken cancellationToken = default); + + /// + /// Set the resource tags. + /// + /// The resource tags. + /// The status of the delete operation. + ArmResponse SetTags(IDictionary tags); + + /// + /// Set the resource tags. + /// + /// The resource tags. + /// A token allowing immediate cancellation of any blocking call performed during the deletion. + /// A that on completion returns the status of the delete operation. + Task> SetTagsAsync( + IDictionary tags, + CancellationToken cancellationToken = default); + + /// + /// Set the resource tags. + /// + /// The resource tags. + /// An that allows the user to control polling and waiting for Tag completion. + ArmOperation StartSetTags(IDictionary tags); + + /// + /// Set the resource tags. + /// + /// The resource tags. + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// A that performs the Tag operation. The Task yields an an + /// that allows the user to control polling and waiting for + /// Tag completion. + Task> StartSetTagsAsync( + IDictionary tags, + CancellationToken cancellationToken = default); + + /// + /// Remove the resource tag. + /// + /// The tag key. + /// The status of the delete operation. + ArmResponse RemoveTag(string key); + + /// + /// Remove the resource tag. + /// + /// The tag key. + /// A token allowing immediate cancellation of any blocking call performed during the deletion. + /// A that on completion returns the status of the delete operation. + Task> RemoveTagAsync( + string key, + CancellationToken cancellationToken = default); + + /// + /// Remove the resource tag. + /// + /// The tag key. + /// An that allows the user to control polling and waiting for Tag completion. + ArmOperation StartRemoveTag(string key); + + /// + /// Remove the resource tag. + /// + /// The tag key. + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// A that performs the Tag operation. The Task yields an an + /// that allows the user to control polling and waiting for + /// Tag completion. + Task> StartRemoveTagAsync( + string key, + CancellationToken cancellationToken = default); + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/OperationsBase.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/OperationsBase.cs new file mode 100644 index 0000000000000..4786be3aa5641 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/OperationsBase.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using Azure.Core; +using Azure.ResourceManager.Resources; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing the operations that can be performed over a specific resource. + /// + public abstract class OperationsBase + { + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + /// A credential used to authenticate to an Azure Service. + /// The base URI of the service. + protected OperationsBase(AzureResourceManagerClientOptions options, ResourceIdentifier id, TokenCredential credential, Uri baseUri) + { + ClientOptions = options; + Id = id; + Credential = credential; + BaseUri = baseUri; + + Validate(id); + } + + /// + /// Gets the resource identifier. + /// + public virtual ResourceIdentifier Id { get; } + + /// + /// Gets the Azure Resource Manager client options. + /// + public virtual AzureResourceManagerClientOptions ClientOptions { get; } + + /// + /// Gets the Azure credential. + /// + public TokenCredential Credential { get; } + + /// + /// Gets the base URI of the service. + /// + public Uri BaseUri { get; } + + /// + /// Gets the valid Azure resource type for the current operations. + /// + /// A valid Azure resource type. + protected abstract ResourceType ValidResourceType { get; } + + /// + /// Gets the resource client. + /// + protected ResourcesManagementClient ResourcesClient => new ResourcesManagementClient(BaseUri, Id.Subscription, Credential); + + /// + /// Validate the resource identifier against current operations. + /// + /// The resource identifier. + protected virtual void Validate(ResourceIdentifier identifier) + { + if (identifier?.Type != ValidResourceType) + throw new ArgumentException($"Invalid resource type {identifier?.Type} expected {ValidResourceType}"); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Placeholder/PhArmOperation.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Placeholder/PhArmOperation.cs new file mode 100644 index 0000000000000..2a90185a65540 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Placeholder/PhArmOperation.cs @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Core +{ + /// + /// A calss representing an arm operation wrapper object. + /// + /// The to convert TModel into. + /// The model returned by existing Operation methods. + public class PhArmOperation : ArmOperation + where TOperations : class + where TModel : class + { + private readonly Func _converter; + private readonly Response _syncWrapped; + private readonly Operation _wrapped; + + /// + /// Initializes a new instance of the class. + /// + /// The results to wrap. + /// The function used to convert from existing type to new type. + public PhArmOperation(Operation wrapped, Func converter) + : base(null) + { + _wrapped = wrapped; + _converter = converter; + } + + /// + /// Initializes a new instance of the class. + /// + /// The results to wrap. + /// The function used to convert from existing type to new type. + public PhArmOperation(Response wrapped, Func converter) + : base(converter(wrapped.Value)) + { + _converter = converter; + _syncWrapped = wrapped; + } + + /// + public override string Id => _wrapped?.Id; + + /// + public override TOperations Value => CompletedSynchronously ? SyncValue : _converter(_wrapped.Value); + + /// + public override bool HasCompleted => CompletedSynchronously || _wrapped.HasCompleted; + + /// + public override bool HasValue => CompletedSynchronously || _wrapped.HasValue; + + /// + public override Response GetRawResponse() + { + return CompletedSynchronously ? _syncWrapped.GetRawResponse() : _wrapped.GetRawResponse(); + } + + /// + public override Response UpdateStatus(CancellationToken cancellationToken = default) + { + return CompletedSynchronously ? _syncWrapped.GetRawResponse() : _wrapped.UpdateStatus(cancellationToken); + } + + /// + public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) + { + return CompletedSynchronously + ? new ValueTask(_syncWrapped.GetRawResponse()) + : _wrapped.UpdateStatusAsync(cancellationToken); + } + + /// + public override async ValueTask> WaitForCompletionAsync( + CancellationToken cancellationToken = default) + { + return CompletedSynchronously + ? new PhArmResponse(_syncWrapped, _converter) + : new PhArmResponse( + await _wrapped.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false), + _converter); + } + + /// + public override async ValueTask> WaitForCompletionAsync( + TimeSpan pollingInterval, + CancellationToken cancellationToken) + { + return CompletedSynchronously + ? new PhArmResponse(_syncWrapped, _converter) + : new PhArmResponse( + await _wrapped.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false), + _converter); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Placeholder/ResourceGroupData.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Placeholder/ResourceGroupData.cs new file mode 100644 index 0000000000000..175310efcb454 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Placeholder/ResourceGroupData.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using Azure.ResourceManager.Resources.Models; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing the ResourceGroup data model. + /// + public class ResourceGroupData : TrackedResource + { + /// + /// Initializes a new instance of the class. + /// + /// The existing resource group model to copy from. + public ResourceGroupData(ResourceManager.Resources.Models.ResourceGroup rg) + : base(rg.Id, rg.Location, rg) + { + } + + /// + public override IDictionary Tags => Model.Tags; + + /// + public override string Name => Model.Name; + + /// + /// Gets or sets the resource group properties + /// + public ResourceGroupProperties Properties + { + get => Model.Properties; + set => Model.Properties = value; + } + + /// + /// Gets or sets who this resource group is managed by + /// + public string ManagedBy + { + get => Model.ManagedBy; + set => Model.ManagedBy = value; + } + + /// + /// Converts from a into the ResourceManager.Resources.Models.ResourceGroup. + /// + /// The tracked resource convert from. + public static implicit operator ResourceManager.Resources.Models.ResourceGroup(ResourceGroupData other) + { + other.Model.Tags.Clear(); + foreach (var tag in other.Tags) + { + other.Model.Tags.Add(tag); + } + + return other.Model; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Placeholder/SubscriptionData.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Placeholder/SubscriptionData.cs new file mode 100644 index 0000000000000..be3b12feeb188 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Placeholder/SubscriptionData.cs @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.ResourceManager.Resources.Models; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing the subscription data model. + /// + public class SubscriptionData : Resource + { + /// + /// Initializes a new instance of the class. + /// + /// The subscription model. + public SubscriptionData(ResourceManager.Resources.Models.Subscription subscription) + { + Name = subscription.DisplayName; + SubscriptionGuid = subscription.SubscriptionId; + DisplayName = subscription.DisplayName; + State = subscription.State; + SubscriptionPolicies = subscription.SubscriptionPolicies; + AuthorizationSource = subscription.AuthorizationSource; + Id = subscription.Id; + ManagedByTenants = subscription.ManagedByTenants; + Tags = subscription.Tags; + } + + /// + /// Gets the subscription id. + /// + public override string Name { get; } + + /// + /// Gets the Id of the Subscription. + /// + public string SubscriptionGuid { get; } + + /// + /// Gets the display name of the subscription. + /// + public string DisplayName { get; } + + /// + /// Gets the state of the subscription. + /// + public SubscriptionState? State { get; } + + /// + /// Gets the policies of the subscription. + /// + public SubscriptionPolicies SubscriptionPolicies { get; } + + /// + /// Gets the authorization source of the subscription. + /// + public string AuthorizationSource { get; } + + /// + public override ResourceIdentifier Id { get; protected set; } + + /// + /// Gets an array containing the tenants managing the subscription. + /// + public IReadOnlyList ManagedByTenants { get; } + + /// + /// Gets the tags attached to the subscription. + /// + public IReadOnlyDictionary Tags { get; } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Properties/AssemblyInfo.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000..9b296c5a8dbe4 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Azure.ResourceManager.Core.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceContainerBase.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceContainerBase.cs new file mode 100644 index 0000000000000..46a89fa6a2b98 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceContainerBase.cs @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing collection of resources and their operations over their parent. + /// + /// The type of the class containing operations for the underlying resource. + /// The type of the class containing properties for the underlying resource. + public abstract class ResourceContainerBase : ContainerBase + where TOperations : ResourceOperationsBase + where TResource : Resource + { + private static readonly object _parentLock = new object(); + private object _parentResource; + + /// + /// Initializes a new instance of the class. + /// + /// The resource representing the parent resource. + protected ResourceContainerBase(ResourceOperationsBase parent) + : base(parent) + { + } + + /// + /// Verify that the input resource Id is a valid container for this type. + /// + /// The input resource Id to check. + /// Resource identifier is not a valid type for this container. + protected override void Validate(ResourceIdentifier identifier) + { + if (identifier.Type != ValidResourceType) + throw new InvalidOperationException($"{identifier.Type} is not a valid container for {Id.Type}"); + } + + /// + /// The operation to create or update a resource. Please note some properties can be set only during creation. + /// + /// The name of the resource. + /// The desired resource configuration. + /// A response with the operation for this resource. + public abstract ArmResponse CreateOrUpdate( + string name, + TResource resourceDetails); + + /// + /// The operation to create or update a resource. Please note some properties can be set only during creation. + /// + /// The name of the resource. + /// The desired resource configuration. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + public abstract Task> CreateOrUpdateAsync( + string name, + TResource resourceDetails, + CancellationToken cancellationToken = default); + + /// + /// The operation to create or update a resource. Please note some properties can be set only during creation. + /// + /// The name of the resource. + /// The desired resource configuration. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An that allows polling for completion of the operation. + /// + /// Details on long running operation object. + /// + public abstract ArmOperation StartCreateOrUpdate( + string name, + TResource resourceDetails, + CancellationToken cancellationToken = default); + + /// + /// The operation to create or update a resource. Please note some properties can be set only during creation. + /// + /// The name of the resource. + /// The desired resource configuration. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns an that allows polling for completion of the operation. + /// + /// Details on long running operation object. + /// + public abstract Task> StartCreateOrUpdateAsync( + string name, + TResource resourceDetails, + CancellationToken cancellationToken = default); + + /// + /// Gets the location of the parent object. + /// + /// The type of the parents full resource object. + /// The type of the parents operations object. + /// The associated with the parent object. + protected TParent GetParentResource() + where TParent : TParentOperations + where TParentOperations : ResourceOperationsBase + { + if (_parentResource is null) + { + lock (_parentLock) + { + if (_parentResource is null) + { + _parentResource = Parent as TParent; + if (_parentResource is null) + { + _parentResource = (Parent as TParentOperations).Get().Value; + } + } + } + } + + return _parentResource as TParent; + } + + /// + /// Gets details for this resource from the service. + /// + /// The name of the resource to get. + /// A response with the operation for this resource. + public abstract ArmResponse Get(string resourceName); + + /// + /// Gets details for this resource from the service. + /// + /// The name of the resource to get. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + public abstract Task> GetAsync(string resourceName, CancellationToken cancellationToken = default); + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceGroup.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceGroup.cs new file mode 100644 index 0000000000000..805ca60f1b27f --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceGroup.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing a ResourceGroup along with the instance operations that can be performed on it. + /// + public class ResourceGroup : ResourceGroupOperations + { + /// + /// Initializes a new instance of the class. + /// + /// The operations to copy the client options from. + /// The ResourceGroupData to use in these operations. + internal ResourceGroup(ResourceOperationsBase operations, ResourceGroupData resource) + : base(operations, resource.Id) + { + Data = resource; + } + + /// + /// Gets the data representing this ResourceGroup. + /// + public ResourceGroupData Data { get; } + + /// + protected override ResourceGroup GetResource() + { + return this; + } + + /// + protected override Task GetResourceAsync() + { + return Task.FromResult(this); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceGroupContainer.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceGroupContainer.cs new file mode 100644 index 0000000000000..8374a6c812561 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceGroupContainer.cs @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Azure.ResourceManager.Resources; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing collection of ResourceGroupContainer and their operations over a ResourceGroup. + /// + public class ResourceGroupContainer : ResourceContainerBase + { + /// + /// Initializes a new instance of the class. + /// + /// The parent subscription. + internal ResourceGroupContainer(SubscriptionOperations subscription) + : base(subscription) + { + } + + /// + protected override ResourceType ValidResourceType => SubscriptionOperations.ResourceType; + + private ResourceGroupsOperations Operations => new ResourcesManagementClient( + BaseUri, + Id.Subscription, + Credential, + ClientOptions.Convert()).ResourceGroups; + + /// + /// Constructs an object used to create a resource group. + /// + /// The location of the resource group. + /// The tags of the resource group. + /// Who the resource group is managed by. + /// A builder with and . + public ArmBuilder Construct(LocationData location, IDictionary tags = default, string managedBy = default) + { + var model = new ResourceManager.Resources.Models.ResourceGroup(location); + if (!(tags is null)) + model.Tags.ReplaceWith(tags); + model.ManagedBy = managedBy; + return new ArmBuilder(this, new ResourceGroupData(model)); + } + + /// + public override ArmResponse CreateOrUpdate(string name, ResourceGroupData resourceDetails) + { + var response = Operations.CreateOrUpdate(name, resourceDetails); + return new PhArmResponse( + response, + g => new ResourceGroup(Parent, new ResourceGroupData(g))); + } + + /// + public override async Task> CreateOrUpdateAsync(string name, ResourceGroupData resourceDetails, CancellationToken cancellationToken = default) + { + var response = await Operations.CreateOrUpdateAsync(name, resourceDetails, cancellationToken).ConfigureAwait(false); + return new PhArmResponse( + response, + g => new ResourceGroup(Parent, new ResourceGroupData(g))); + } + + /// + public override ArmOperation StartCreateOrUpdate(string name, ResourceGroupData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + Operations.CreateOrUpdate(name, resourceDetails, cancellationToken), + g => new ResourceGroup(Parent, new ResourceGroupData(g))); + } + + /// + public override async Task> StartCreateOrUpdateAsync(string name, ResourceGroupData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + await Operations.CreateOrUpdateAsync(name, resourceDetails, cancellationToken).ConfigureAwait(false), + g => new ResourceGroup(Parent, new ResourceGroupData(g))); + } + + /// + /// List the resource groups for this subscription. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of resource operations that may take multiple service requests to iterate over. + public Pageable List(CancellationToken cancellationToken = default) + { + return new PhWrappingPageable( + Operations.List(null, null, cancellationToken), + s => new ResourceGroup(Parent, new ResourceGroupData(s))); + } + + /// + /// List the resource groups for this subscription. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of resource operations that may take multiple service requests to iterate over. + public AsyncPageable ListAsync(CancellationToken cancellationToken = default) + { + return new PhWrappingAsyncPageable( + Operations.ListAsync(null, null, cancellationToken), + s => new ResourceGroup(Parent, new ResourceGroupData(s))); + } + + /// + public override ArmResponse Get(string resourceGroupName) + { + return new PhArmResponse(Operations.Get(resourceGroupName), g => + { + return new ResourceGroup(Parent, new ResourceGroupData(g)); + }); + } + + /// + public override async Task> GetAsync(string resourceGroupName, CancellationToken cancellationToken = default) + { + return new PhArmResponse( + await Operations.GetAsync(resourceGroupName, cancellationToken).ConfigureAwait(false), + g => + { + return new ResourceGroup(Parent, new ResourceGroupData(g)); + }); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceGroupOperations.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceGroupOperations.cs new file mode 100644 index 0000000000000..295abe3e07362 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceGroupOperations.cs @@ -0,0 +1,438 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core.Pipeline; +using Azure.ResourceManager.Resources; +using Azure.ResourceManager.Resources.Models; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing the operations that can be performed over a specific ResourceGroup. + /// + public class ResourceGroupOperations : ResourceOperationsBase, + ITaggableResource, IDeletableResource + { + /// + /// Gets the resource type definition for a ResourceType. + /// + public static readonly ResourceType ResourceType = "Microsoft.Resources/resourceGroups"; + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The name of the resource group to use. + internal ResourceGroupOperations(SubscriptionOperations options, string rgName) + : base(options, $"{options.Id}/resourceGroups/{rgName}") + { + if (rgName.Length > 90) + throw new ArgumentOutOfRangeException(nameof(rgName), "ResourceGroupName cannot be longer than 90 characters."); + + if (!ValidationPattern.IsMatch(rgName)) + throw new ArgumentException("The name of the resource group can include alphanumeric, underscore, parentheses, hyphen, period (except at end), and Unicode characters that match the allowed characters."); + } + + private static readonly Regex ValidationPattern = new Regex(@"^[-\w\._\(\)]+$"); + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + protected ResourceGroupOperations(ResourceOperationsBase options, ResourceIdentifier id) + : base(options, id) + { + } + + /// + protected override ResourceType ValidResourceType => ResourceType; + + private ResourceGroupsOperations Operations => new ResourcesManagementClient( + BaseUri, + Id.Subscription, + Credential, + ClientOptions.Convert()).ResourceGroups; + + /// + /// When you delete a resource group, all of its resources are also deleted. Deleting a resource group deletes all of its template deployments and currently stored operations. + /// + /// A response with the operation for this resource. + public ArmResponse Delete() + { + return new ArmResponse(Operations.StartDelete(Id.Name).WaitForCompletionAsync().EnsureCompleted()); + } + + /// + /// When you delete a resource group, all of its resources are also deleted. Deleting a resource group deletes all of its template deployments and currently stored operations. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + public async Task> DeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmResponse(await Operations.StartDelete(Id.Name, cancellationToken).WaitForCompletionAsync(cancellationToken).ConfigureAwait(false)); + } + + /// + /// When you delete a resource group, all of its resources are also deleted. Deleting a resource group deletes all of its template deployments and currently stored operations. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A response with the operation for this resource. + /// + /// Details on long running operation object. + /// + public ArmOperation StartDelete(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(Operations.StartDelete(Id.Name, cancellationToken)); + } + + /// + /// When you delete a resource group, all of its resources are also deleted. Deleting a resource group deletes all of its template deployments and currently stored operations. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + /// + /// Details on long running operation object. + /// + public async Task> StartDeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(await Operations.StartDeleteAsync(Id.Name, cancellationToken).ConfigureAwait(false)); + } + + /// + public override ArmResponse Get() + { + return new PhArmResponse(Operations.Get(Id.Name), g => + { + return new ResourceGroup(this, new ResourceGroupData(g)); + }); + } + + /// + public override async Task> GetAsync(CancellationToken cancellationToken = default) + { + return new PhArmResponse( + await Operations.GetAsync(Id.Name, cancellationToken).ConfigureAwait(false), + g => + { + return new ResourceGroup(this, new ResourceGroupData(g)); + }); + } + + /// + /// Add a tag to a ResourceGroup. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// A response with the operation for this resource. + /// Key cannot be null or a whitespace. + public ArmResponse AddTag(string key, string value) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentException($"{nameof(key)} provided cannot be null or a whitespace.", nameof(key)); + + var resource = GetResource(); + var patch = new ResourceGroupPatchable(); + patch.Tags.ReplaceWith(resource.Data.Tags); + patch.Tags[key] = value; + return new PhArmResponse(Operations.Update(Id.Name, patch), g => + { + return new ResourceGroup(this, new ResourceGroupData(g)); + }); + } + + /// + /// Add a tag to a ResourceGroup. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + /// Key cannot be null or a whitespace. + public async Task> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentException($"{nameof(key)} provided cannot be null or a whitespace.", nameof(key)); + + var resource = GetResource(); + var patch = new ResourceGroupPatchable(); + patch.Tags.ReplaceWith(resource.Data.Tags); + patch.Tags[key] = value; + return new PhArmResponse( + await Operations.UpdateAsync(Id.Name, patch, cancellationToken).ConfigureAwait(false), g => + { + return new ResourceGroup(this, new ResourceGroupData(g)); + }); + } + + /// + /// Add a tag to a ResourceGroup. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// A response with the operation for this resource. + /// + /// Details on long running operation object. + /// + /// Key cannot be null or a whitespace. + public ArmOperation StartAddTag(string key, string value) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentException($"{nameof(key)} provided cannot be null or a whitespace.", nameof(key)); + + var resource = GetResource(); + var patch = new ResourceGroupPatchable(); + patch.Tags.ReplaceWith(resource.Data.Tags); + patch.Tags[key] = value; + return new PhArmOperation(Operations.Update(Id.Name, patch), g => + { + return new ResourceGroup(this, new ResourceGroupData(g)); + }); + } + + /// + /// Add a tag to a ResourceGroup. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// /// A that on completion returns a response with the operation for this resource. + /// + /// Details on long running operation object. + /// + /// Key cannot be null or a whitespace. + public async Task> StartAddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentException($"{nameof(key)} provided cannot be null or a whitespace.", nameof(key)); + + var resource = GetResource(); + var patch = new ResourceGroupPatchable(); + patch.Tags.ReplaceWith(resource.Data.Tags); + patch.Tags[key] = value; + return new PhArmOperation( + await Operations.UpdateAsync(Id.Name, patch, cancellationToken).ConfigureAwait(false), + g => + { + return new ResourceGroup(this, new ResourceGroupData(g)); + }); + } + + /// + /// Create a resource with a ResourceGroupOperations. + /// + /// A string representing the name of the resource />. + /// The model representing the object to create. />. + /// The type of the class containing the container for the specific resource. + /// The type of the operations class for a specific resource. + /// The type of the class containing properties for the underlying resource. + /// Returns a response with the operation for this resource. + /// Name cannot be null or a whitespace. + /// Model cannot be null. + public ArmResponse CreateResource(string name, TResource model) + where TResource : TrackedResource + where TOperations : ResourceOperationsBase + where TContainer : ResourceContainerBase + { + if (string.IsNullOrWhiteSpace(name)) + throw new ArgumentException($"{nameof(name)} provided cannot be null or a whitespace.", nameof(name)); + if (model is null) + throw new ArgumentNullException(nameof(model)); + + var myResource = model as TrackedResource; + TContainer container = Activator.CreateInstance(typeof(TContainer), ClientOptions, myResource) as TContainer; + + return container.CreateOrUpdate(name, model); + } + + /// + /// Create a resource with a ResourceGroupOperations. + /// + /// A string representing the name of the resource />. + /// The model representing the object to create. />. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// The type of the class containing the container for the specific resource. + /// The type of the operations class for a specific resource. + /// The type of the class containing properties for the underlying resource. + /// A that on completion returns a response with the operation for this resource. + /// Name cannot be null or a whitespace. + /// Model cannot be null. + public Task> CreateResourceAsync(string name, TResource model, CancellationToken cancellationToken = default) + where TResource : TrackedResource + where TOperations : ResourceOperationsBase + where TContainer : ResourceContainerBase + { + if (string.IsNullOrWhiteSpace(name)) + throw new ArgumentException($"{nameof(name)} provided cannot be null or a whitespace.", nameof(name)); + if (model is null) + throw new ArgumentNullException(nameof(model)); + + var myResource = model as TrackedResource; + + TContainer container = Activator.CreateInstance(typeof(TContainer), ClientOptions, myResource) as TContainer; + + return container.CreateOrUpdateAsync(name, model, cancellationToken); + } + + /// + public ArmResponse SetTags(IDictionary tags) + { + if (tags == null) + throw new ArgumentNullException(nameof(tags)); + + var resource = GetResource(); + var patch = new ResourceGroupPatchable(); + patch.Tags.ReplaceWith(tags); + return new PhArmResponse(Operations.Update(Id.Name, patch), g => + { + return new ResourceGroup(this, new ResourceGroupData(g)); + }); + } + + /// + public async Task> SetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + if (tags == null) + throw new ArgumentNullException(nameof(tags)); + + var resource = GetResource(); + var patch = new ResourceGroupPatchable(); + patch.Tags.ReplaceWith(tags); + return new PhArmResponse( + await Operations.UpdateAsync(Id.Name, patch, cancellationToken).ConfigureAwait(false), + g => + { + return new ResourceGroup(this, new ResourceGroupData(g)); + }); + } + + /// + public ArmOperation StartSetTags(IDictionary tags) + { + if (tags == null) + throw new ArgumentNullException(nameof(tags)); + + var resource = GetResource(); + var patch = new ResourceGroupPatchable(); + patch.Tags.ReplaceWith(tags); + return new PhArmOperation(Operations.Update(Id.Name, patch), g => + { + return new ResourceGroup(this, new ResourceGroupData(g)); + }); + } + + /// + public async Task> StartSetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + if (tags == null) + throw new ArgumentNullException(nameof(tags)); + + var resource = GetResource(); + var patch = new ResourceGroupPatchable(); + patch.Tags.ReplaceWith(tags); + return new PhArmOperation( + await Operations.UpdateAsync(Id.Name, patch, cancellationToken).ConfigureAwait(false), + g => + { + return new ResourceGroup(this, new ResourceGroupData(g)); + }); + } + + /// + public ArmResponse RemoveTag(string key) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentException($"{nameof(key)} provided cannot be null or a whitespace.", nameof(key)); + + var resource = GetResource(); + var patch = new ResourceGroupPatchable(); + patch.Tags.ReplaceWith(resource.Data.Tags); + patch.Tags.Remove(key); + return new PhArmResponse(Operations.Update(Id.Name, patch), g => + { + return new ResourceGroup(this, new ResourceGroupData(g)); + }); + } + + /// + public async Task> RemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentException($"{nameof(key)} provided cannot be null or a whitespace.", nameof(key)); + + var resource = GetResource(); + var patch = new ResourceGroupPatchable(); + patch.Tags.ReplaceWith(resource.Data.Tags); + patch.Tags.Remove(key); + return new PhArmResponse( + await Operations.UpdateAsync(Id.Name, patch, cancellationToken).ConfigureAwait(false), + g => + { + return new ResourceGroup(this, new ResourceGroupData(g)); + }); + } + + /// + public ArmOperation StartRemoveTag(string key) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentException($"{nameof(key)} provided cannot be null or a whitespace.", nameof(key)); + + var resource = GetResource(); + var patch = new ResourceGroupPatchable(); + patch.Tags.ReplaceWith(resource.Data.Tags); + patch.Tags.Remove(key); + return new PhArmOperation(Operations.Update(Id.Name, patch), g => + { + return new ResourceGroup(this, new ResourceGroupData(g)); + }); + } + + /// + public async Task> StartRemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentException($"{nameof(key)} provided cannot be null or a whitespace.", nameof(key)); + + var resource = GetResource(); + var patch = new ResourceGroupPatchable(); + patch.Tags.ReplaceWith(resource.Data.Tags); + patch.Tags.Remove(key); + return new PhArmOperation( + await Operations.UpdateAsync(Id.Name, patch, cancellationToken).ConfigureAwait(false), + g => + { + return new ResourceGroup(this, new ResourceGroupData(g)); + }); + } + + /// + /// Lists all available geo-locations. + /// + /// A collection of location that may take multiple service requests to iterate over. + public IEnumerable ListAvailableLocations() + { + return ListAvailableLocations(ResourceType); + } + + /// + /// Lists all available geo-locations. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of location that may take multiple service requests to iterate over. + /// The default subscription id is null. + public async Task> ListAvailableLocationsAsync(CancellationToken cancellationToken = default) + { + return await ListAvailableLocationsAsync(ResourceType, cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceListOperations.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceListOperations.cs new file mode 100644 index 0000000000000..469af5edd69b6 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceListOperations.cs @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.ResourceManager.Core.Adapters; +using Azure.ResourceManager.Core.Resources; +using Azure.ResourceManager.Resources; +using Azure.ResourceManager.Resources.Models; +using System; +using System.Globalization; +using System.Reflection; +using System.Threading; + +namespace Azure.ResourceManager.Core +{ + /// + /// Generic list operations class. This can be extended if a specific RP has more list operations. + /// + public static class ResourceListOperations + { + /// + /// List resources under the a resource context + /// + /// The instance to use for the list. + /// Optional filters for results. + /// The number of results to return. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of resource operations that may take multiple service requests to iterate over. + public static Pageable ListAtContext( + ResourceGroupOperations resourceGroup, + ResourceFilterCollection resourceFilters = null, + int? top = null, + CancellationToken cancellationToken = default) + { + return ListAtContextInternal( + resourceGroup, + resourceGroup.Id.Name, + resourceFilters, + top, + cancellationToken); + } + + /// + /// List resources under the a resource context + /// + /// The instance to use for the list. + /// Optional filters for results. + /// The number of results to return. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of resource operations that may take multiple service requests to iterate over. + public static AsyncPageable ListAtContextAsync( + ResourceGroupOperations resourceGroup, + ResourceFilterCollection resourceFilters = null, + int? top = null, + CancellationToken cancellationToken = default) + { + return ListAtContextInternalAsync( + resourceGroup, + resourceGroup.Id.Name, + resourceFilters, + top, + cancellationToken); + } + + /// + /// List resources under a subscription + /// + /// The instance to use for the list. + /// Optional filters for results. + /// The number of results to return. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of resource operations that may take multiple service requests to iterate over. + public static Pageable ListAtContext( + SubscriptionOperations subscription, + ResourceFilterCollection resourceFilters = null, + int? top = null, + CancellationToken cancellationToken = default) + { + return ListAtContextInternal( + subscription, + null, + resourceFilters, + top, + cancellationToken); + } + + /// + /// List resources under the a resource context + /// + /// The instance to use for the list. + /// Optional filters for results. + /// The number of results to return. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of resource operations that may take multiple service requests to iterate over. + public static AsyncPageable ListAtContextAsync( + SubscriptionOperations subscription, + ResourceFilterCollection resourceFilters = null, + int? top = null, + CancellationToken cancellationToken = default) + { + return ListAtContextInternalAsync( + subscription, + null, + resourceFilters, + top, + cancellationToken); + } + + private static ResourcesManagementClient GetResourcesClient(ResourceOperationsBase resourceOperations) + { + return new ResourcesManagementClient(resourceOperations.BaseUri, resourceOperations.Id.Subscription, resourceOperations.Credential); + } + + private static AsyncPageable ListAtContextInternalAsync( + ResourceOperationsBase resourceOperations, + string scopeFilter, + ResourceFilterCollection resourceFilters = null, + int? top = null, + CancellationToken cancellationToken = default) + { + var armOperations = GetResourcesClient(resourceOperations).Resources; + AsyncPageable result; + if (scopeFilter == null) + { + result = armOperations.ListAsync(resourceFilters?.ToString(), null, top, cancellationToken); + } + else + { + result = armOperations.ListByResourceGroupAsync( + scopeFilter, + resourceFilters?.ToString(), + null, + top, + cancellationToken); + } + + return ConvertResultsAsync(result, resourceOperations); + } + + private static Pageable ListAtContextInternal( + ResourceOperationsBase resourceOperations, + string scopeFilter = null, + ResourceFilterCollection resourceFilters = null, + int? top = null, + CancellationToken cancellationToken = default) + { + var armOperations = GetResourcesClient(resourceOperations).Resources; + Pageable result; + if (scopeFilter == null) + { + result = armOperations.List(resourceFilters?.ToString(), null, top, cancellationToken); + } + else + { + result = armOperations.ListByResourceGroup( + scopeFilter, + resourceFilters?.ToString(), + null, + top, + cancellationToken); + } + + return ConvertResults(result, resourceOperations); + } + + private static Pageable ConvertResults( + Pageable result, + ResourceOperationsBase resourceOperations) + { + return new PhWrappingPageable( + result, + CreateResourceConverter(resourceOperations)); + } + + private static AsyncPageable ConvertResultsAsync( + AsyncPageable result, + ResourceOperationsBase resourceOperations) + { + return new PhWrappingAsyncPageable( + result, + CreateResourceConverter(resourceOperations)); + } + + private static Func CreateResourceConverter(ResourceOperationsBase resourceOperations) + { + return s => + { + var args = new object[] + { + resourceOperations, + Activator.CreateInstance(typeof(GenericResourceData), s as ResourceManager.Resources.Models.GenericResource) as GenericResourceData, + }; + + return Activator.CreateInstance( + typeof(GenericResource), + BindingFlags.Instance | BindingFlags.NonPublic, + null, + args, + CultureInfo.InvariantCulture) as GenericResource; + }; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceOperationsBase.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceOperationsBase.cs new file mode 100644 index 0000000000000..2f0e7c1792b6e --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceOperationsBase.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing the operations that can be performed over a specific resource. + /// + public abstract class ResourceOperationsBase : OperationsBase + { + /// + /// Initializes a new instance of the class. + /// + /// The operations representing the resource. + protected ResourceOperationsBase(ResourceOperationsBase operations) + : base(operations.ClientOptions, operations.Id, operations.Credential, operations.BaseUri) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The operations to copy options from. + /// The resource that is the target of operations. + protected ResourceOperationsBase(ResourceOperationsBase options, ResourceIdentifier resourceId) + : base(options.ClientOptions, resourceId, options.Credential, options.BaseUri) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + /// A credential used to authenticate to an Azure Service. + /// The base URI of the service. + protected ResourceOperationsBase(AzureResourceManagerClientOptions options, ResourceIdentifier resourceId, TokenCredential credential, Uri baseUri) + : base(options, resourceId, credential, baseUri) + { + } + } + + /// + /// Base class for all operations over a resource + /// + /// The type implementing operations over the resource. + [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:File may only contain a single type", Justification = "Types differ by type argument only")] + public abstract class ResourceOperationsBase : ResourceOperationsBase + where TOperations : ResourceOperationsBase + { + /// + /// Initializes a new instance of the class. + /// + /// Generic ARMResourceOperations for this resource type. + protected ResourceOperationsBase(GenericResourceOperations genericOperations) + : base(genericOperations) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The resource representing the parent resource. + /// The identifier of the resource that is the target of operations. + protected ResourceOperationsBase(ResourceOperationsBase parentOperations, ResourceIdentifier id) + : base(parentOperations, id) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + /// A credential used to authenticate to an Azure Service. + /// The base URI of the service. + protected ResourceOperationsBase(AzureResourceManagerClientOptions options, ResourceIdentifier resourceId, TokenCredential credential, Uri baseUri) + : base(options, resourceId, credential, baseUri) + { + } + + /// + /// Gets details for this resource from the service. + /// + /// A response with the operation for this resource. + public abstract ArmResponse Get(); + + /// + /// Gets details for this resource from the service. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + public abstract Task> GetAsync(CancellationToken cancellationToken = default); + + /// + /// Get details for this resource from the service or can be overriden to provide a cached instance. + /// + /// A operation for this resource. + protected virtual TOperations GetResource() + { + return Get().Value; + } + + /// + /// Get details for this resource from the service or can be overriden to provide a cached instance. + /// + /// A that on completion returns a operation for this resource. + protected virtual async Task GetResourceAsync() + { + return (await GetAsync().ConfigureAwait(false)).Value; + } + + /// + /// Lists all available geo-locations. + /// + /// The instance to use for the list. + /// A collection of location that may take multiple service requests to iterate over. + protected IEnumerable ListAvailableLocations(ResourceType resourceType) + { + var pageableProvider = ResourcesClient.Providers.List(expand: "metadata"); + var resourcePageableProvider = pageableProvider.FirstOrDefault(p => string.Equals(p.Namespace, resourceType?.Namespace, StringComparison.InvariantCultureIgnoreCase)); + if (resourcePageableProvider is null) + throw new InvalidOperationException($"{resourceType.Type} not found for {resourceType.Namespace}"); + var theResource = resourcePageableProvider.ResourceTypes.FirstOrDefault(r => resourceType.Type.Equals(r.ResourceType)); + if (theResource is null) + throw new InvalidOperationException($"{resourceType.Type} not found for {resourceType.Type}"); + return theResource.Locations.Select(l => (LocationData)l); + } + + /// + /// Lists all available geo-locations. + /// + /// The instance to use for the list. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of location that may take multiple service requests to iterate over. + protected async Task> ListAvailableLocationsAsync(ResourceType resourceType, CancellationToken cancellationToken = default) + { + var pageableProvider = ResourcesClient.Providers.ListAsync(expand: "metadata", cancellationToken: cancellationToken); + var resourcePageableProvider = await pageableProvider.FirstOrDefaultAsync( + p => string.Equals(p.Namespace, resourceType?.Namespace, StringComparison.InvariantCultureIgnoreCase), + cancellationToken).ConfigureAwait(false); + if (resourcePageableProvider is null) + throw new InvalidOperationException($"{resourceType.Type} not found for {resourceType.Namespace}"); + var theResource = resourcePageableProvider.ResourceTypes.FirstOrDefault(r => resourceType.Type.Equals(r.ResourceType)); + if (theResource is null) + throw new InvalidOperationException($"{resourceType.Type} not found for {resourceType.Type}"); + return theResource.Locations.Select(l => (LocationData)l); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/GenericResourceFilter.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/GenericResourceFilter.cs new file mode 100644 index 0000000000000..7868aed6f4f01 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/GenericResourceFilter.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Core.Resources +{ + /// + /// Syntactic sugar for creating ARM filters + /// + public abstract class GenericResourceFilter + { + /// + /// Gets the filter as a string. + /// + /// The string representation of the filter. + public abstract string GetFilterString(); + + /// + public override string ToString() + { + return GetFilterString(); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/KnownKeys.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/KnownKeys.cs new file mode 100644 index 0000000000000..0494380d72f49 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/KnownKeys.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; + +namespace Azure.ResourceManager.Core +{ + /// + /// Helper class with the known keys in a dictionary for easy access. + /// + internal static class KnownKeys + { + /// + /// Gets the key for Subscription. + /// + public static string Subscription => "subscriptions"; + + /// + /// Gets the key for Tenant. + /// + public static string Tenant => "tenants"; + + /// + /// Gets the key for Resource Group. + /// + public static string ResourceGroup => "resourcegroups"; + + /// + /// Gets the key for Location. + /// + public static string Location => "locations"; + + /// + /// Gets the key for Provider Namespace. + /// + public static string ProviderNamespace => "providers"; + + /// + /// Gets the key for Untracked Subresource. + /// + public static string UntrackedSubResource => Guid.NewGuid().ToString(); + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/LocationContainer.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/LocationContainer.cs new file mode 100644 index 0000000000000..a87b0120127c2 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/LocationContainer.cs @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.ResourceManager.Core.Adapters; +using Azure.ResourceManager.Resources; +using System.Threading; +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Core +{ + /// + /// Represents an Azure geography region where supported resource providers live. + /// + public class LocationContainer : OperationsBase + { + /// + /// Initializes a new instance of the class. + /// + /// The subscription that this location container belongs to. + internal LocationContainer(SubscriptionOperations subscriptionOperations) + : base(subscriptionOperations.ClientOptions, subscriptionOperations.Id, subscriptionOperations.Credential, subscriptionOperations.BaseUri) + { + } + + /// + protected override ResourceType ValidResourceType => SubscriptionOperations.ResourceType; + + /// + /// Gets the subscription client. + /// + private SubscriptionsOperations SubscriptionsClient => ResourcesClient.Subscriptions; + + /// + /// Gets the Azure subscriptions. + /// + /// Subscription container. + public SubscriptionContainer GetSubscriptionContainer() + { + return new SubscriptionContainer(ClientOptions, Credential, BaseUri); + } + + /// + /// Lists all geo-locations. + /// + /// A collection of location data that may take multiple service requests to iterate over. + public Pageable List() + { + return new PhWrappingPageable(SubscriptionsClient.ListLocations(Id.Subscription), s => s.DisplayName); + } + + /// + /// Lists all geo-locations. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of location data that may take multiple service requests to iterate over. + public AsyncPageable ListAsync(CancellationToken token = default(CancellationToken)) + { + return new PhWrappingAsyncPageable(SubscriptionsClient.ListLocationsAsync(Id.Subscription, token), s => s.DisplayName); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/LocationData.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/LocationData.cs new file mode 100644 index 0000000000000..db55f0eef8d20 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/LocationData.cs @@ -0,0 +1,460 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; + +namespace Azure.ResourceManager.Core +{ + /// + /// Represents an Azure geography region where supported resource providers live. + /// + public class LocationData : IEquatable, IComparable + { + #region Public Cloud Locations + + /// + /// Public cloud location for East Asia. + /// + public static readonly LocationData EastAsia = new LocationData { Name = "eastasia", CanonicalName = "east-asia", DisplayName = "East Asia" }; + + /// + /// Public cloud location for Southeast Asia. + /// + public static readonly LocationData SoutheastAsia = new LocationData { Name = "southeastasia", CanonicalName = "southeast-asia", DisplayName = "Southeast Asia" }; + + /// + /// Public cloud location for Central US. + /// + public static readonly LocationData CentralUS = new LocationData { Name = "centralus", CanonicalName = "central-us", DisplayName = "Central US" }; + + /// + /// Public cloud location for East US. + /// + public static readonly LocationData EastUS = new LocationData { Name = "eastus", CanonicalName = "east-us", DisplayName = "East US" }; + + /// + /// Public cloud location for East US 2. + /// + public static readonly LocationData EastUS2 = new LocationData { Name = "eastus2", CanonicalName = "east-us-2", DisplayName = "East US 2" }; + + /// + /// Public cloud location for West US. + /// + public static readonly LocationData WestUS = new LocationData { Name = "westus", CanonicalName = "west-us", DisplayName = "West US" }; + + /// + /// Public cloud location for North Central US. + /// + public static readonly LocationData NorthCentralUS = new LocationData { Name = "northcentralus", CanonicalName = "north-central-us", DisplayName = "North Central US" }; + + /// + /// Public cloud location for South Central US. + /// + public static readonly LocationData SouthCentralUS = new LocationData { Name = "southcentralus", CanonicalName = "south-central-us", DisplayName = "South Central US" }; + + /// + /// Public cloud location for North Europe. + /// + public static readonly LocationData NorthEurope = new LocationData { Name = "northeurope", CanonicalName = "north-europe", DisplayName = "North Europe" }; + + /// + /// Public cloud location for West Europe. + /// + public static readonly LocationData WestEurope = new LocationData { Name = "westeurope", CanonicalName = "west-europe", DisplayName = "West Europe" }; + + /// + /// Public cloud location for Japan West. + /// + public static readonly LocationData JapanWest = new LocationData { Name = "japanwest", CanonicalName = "japan-west", DisplayName = "Japan West" }; + + /// + /// Public cloud location for Japan East. + /// + public static readonly LocationData JapanEast = new LocationData { Name = "japaneast", CanonicalName = "japan-east", DisplayName = "Japan East" }; + + /// + /// Public cloud location for Brazil South. + /// + public static readonly LocationData BrazilSouth = new LocationData { Name = "brazilsouth", CanonicalName = "brazil-south", DisplayName = "Brazil South" }; + + /// + /// Public cloud location for Australia East. + /// + public static readonly LocationData AustraliaEast = new LocationData { Name = "australiaeast", CanonicalName = "australia-east", DisplayName = "Australia East" }; + + /// + /// Public cloud location for Australia Southeast. + /// + public static readonly LocationData AustraliaSoutheast = new LocationData { Name = "australiasoutheast", CanonicalName = "australia-southeast", DisplayName = "Australia Southeast" }; + + /// + /// Public cloud location for South India. + /// + public static readonly LocationData SouthIndia = new LocationData { Name = "southindia", CanonicalName = "south-india", DisplayName = "South India" }; + + /// + /// Public cloud location for Central India. + /// + public static readonly LocationData CentralIndia = new LocationData { Name = "centralindia", CanonicalName = "central-india", DisplayName = "Central India" }; + + /// + /// Public cloud location for West India. + /// + public static readonly LocationData WestIndia = new LocationData { Name = "westindia", CanonicalName = "west-india", DisplayName = "West India" }; + + /// + /// Public cloud location for Canada Central. + /// + public static readonly LocationData CanadaCentral = new LocationData { Name = "canadacentral", CanonicalName = "canada-central", DisplayName = "Canada Central" }; + + /// + /// Public cloud location for Canada East. + /// + public static readonly LocationData CanadaEast = new LocationData { Name = "canadaeast", CanonicalName = "canada-east", DisplayName = "Canada East" }; + + /// + /// Public cloud location for UK South. + /// + public static readonly LocationData UKSouth = new LocationData { Name = "uksouth", CanonicalName = "uk-south", DisplayName = "UK South" }; + + /// + /// Public cloud location for UK West. + /// + public static readonly LocationData UKWest = new LocationData { Name = "ukwest", CanonicalName = "uk-west", DisplayName = "UK West" }; + + /// + /// Public cloud location for West Central US. + /// + public static readonly LocationData WestCentralUS = new LocationData { Name = "westcentralus", CanonicalName = "west-central-us", DisplayName = "West Central US" }; + + /// + /// Public cloud location for West US 2. + /// + public static readonly LocationData WestUS2 = new LocationData { Name = "westus2", CanonicalName = "west-us-2", DisplayName = "West US 2" }; + + /// + /// Public cloud location for Korea Central. + /// + public static readonly LocationData KoreaCentral = new LocationData { Name = "koreacentral", CanonicalName = "korea-central", DisplayName = "Korea Central" }; + + /// + /// Public cloud location for Korea South. + /// + public static readonly LocationData KoreaSouth = new LocationData { Name = "koreasouth", CanonicalName = "korea-south", DisplayName = "Korea South" }; + + /// + /// Public cloud location for France Central. + /// + public static readonly LocationData FranceCentral = new LocationData { Name = "francecentral", CanonicalName = "france-central", DisplayName = "France Central" }; + + /// + /// Public cloud location for France South. + /// + public static readonly LocationData FranceSouth = new LocationData { Name = "francesouth", CanonicalName = "france-south", DisplayName = "France South" }; + + /// + /// Public cloud location for Australia Central. + /// + public static readonly LocationData AustraliaCentral = new LocationData { Name = "australiacentral", CanonicalName = "australia-central", DisplayName = "Australia Central" }; + + /// + /// Public cloud location for Australia Central 2. + /// + public static readonly LocationData AustraliaCentral2 = new LocationData { Name = "australiacentral2", CanonicalName = "australia-central-2", DisplayName = "Australia Central 2" }; + + /// + /// Public cloud location for UAE Central. + /// + public static readonly LocationData UAECentral = new LocationData { Name = "uaecentral", CanonicalName = "uae-central", DisplayName = "UAE Central" }; + + /// + /// Public cloud location for UAE North. + /// + public static readonly LocationData UAENorth = new LocationData { Name = "uaenorth", CanonicalName = "uae-north", DisplayName = "UAE North" }; + + /// + /// Public cloud location for South Africa North. + /// + public static readonly LocationData SouthAfricaNorth = new LocationData { Name = "southafricanorth", CanonicalName = "south-africa-north", DisplayName = "South Africa North" }; + + /// + /// Public cloud location for South Africa West. + /// + public static readonly LocationData SouthAfricaWest = new LocationData { Name = "southafricawest", CanonicalName = "south-africa-west", DisplayName = "South Africa West" }; + + /// + /// Public cloud location for Switzerland North. + /// + public static readonly LocationData SwitzerlandNorth = new LocationData { Name = "switzerlandnorth", CanonicalName = "switzerland-north", DisplayName = "Switzerland North" }; + + /// + /// Public cloud location for Switzerland West. + /// + public static readonly LocationData SwitzerlandWest = new LocationData { Name = "switzerlandwest", CanonicalName = "switzerland-west", DisplayName = "Switzerland West" }; + + /// + /// Public cloud location for Germany North. + /// + public static readonly LocationData GermanyNorth = new LocationData { Name = "germanynorth", CanonicalName = "germany-north", DisplayName = "Germany North" }; + + /// + /// Public cloud location for Germany West Central. + /// + public static readonly LocationData GermanyWestCentral = new LocationData { Name = "germanywestcentral", CanonicalName = "germany-west-central", DisplayName = "Germany West Central" }; + + /// + /// Public cloud location for Norway West. + /// + public static readonly LocationData NorwayWest = new LocationData { Name = "norwaywest", CanonicalName = "norway-west", DisplayName = "Norway West" }; + + /// + /// Public cloud location for Brazil Southeast. + /// + public static readonly LocationData BrazilSoutheast = new LocationData { Name = "brazilsoutheast", CanonicalName = "brazil-southeast", DisplayName = "Brazil Southeast" }; + + #endregion + private static readonly Dictionary PublicCloudLocations = new Dictionary() + { + { "EASTASIA", EastAsia }, + { "SOUTHEASTASIA", SoutheastAsia }, + { "CENTRALUS", CentralUS }, + { "EASTUS", EastUS }, + { "EASTUS2", EastUS2 }, + { "WESTUS", WestUS }, + { "NORTHCENTRALUS", NorthCentralUS }, + { "SOUTHCENTRALUS", SouthCentralUS }, + { "NORTHEUROPE", NorthEurope }, + { "WESTEUROPE", WestEurope }, + { "JAPANWEST", JapanWest }, + { "JAPANEAST", JapanEast }, + { "BRAZILSOUTH", BrazilSouth }, + { "AUSTRALIAEAST", AustraliaEast }, + { "AUSTRALIASOUTHEAST", AustraliaSoutheast }, + { "SOUTHINDIA", SouthIndia }, + { "CENTRALINDIA", CentralIndia }, + { "WESTINDIA", WestIndia }, + { "CANADACENTRAL", CanadaCentral }, + { "CANADAEAST", CanadaEast }, + { "UKSOUTH", UKSouth }, + { "UKWEST", UKWest }, + { "WESTCENTRALUS", WestCentralUS }, + { "WESTUS2", WestUS2 }, + { "KOREACENTRAL", KoreaCentral }, + { "KOREASOUTH", KoreaSouth }, + { "FRANCECENTRAL", FranceCentral }, + { "FRANCESOUTH", FranceSouth }, + { "AUSTRALIACENTRAL", AustraliaCentral }, + { "AUSTRALIACENTRAL2", AustraliaCentral2 }, + { "UAECENTRAL", UAECentral }, + { "UAENORTH", UAENorth }, + { "SOUTHAFRICANORTH", SouthAfricaNorth }, + { "SOUTHAFRICAWEST", SouthAfricaWest }, + { "SWITZERLANDNORTH", SwitzerlandNorth }, + { "SWITZERLANDWEST", SwitzerlandWest }, + { "GERMANYNORTH", GermanyNorth }, + { "GERMANYWESTCENTRAL", GermanyWestCentral }, + { "NORWAYWEST", NorwayWest }, + { "BRAZILSOUTHEAST", BrazilSoutheast }, + }; + + private const string CanonicalPattern = "^[a-z]+(-[a-z]+)+(-[1-9])?$"; + private const string DisplayPattern = "^[A-Z]+[a-z]*( [A-Z]+[a-z]*)+( [1-9])?$"; + private const string RegexDash = @"-"; + private const string RegexWhitespace = @" "; + + private LocationData() + { + } + + private LocationData(string location) + { + switch (DetectNameType(location)) + { + case NameType.Name: + Name = location; + CanonicalName = location; + DisplayName = location; + break; + case NameType.CanonicalName: + Name = GetDefaultNameFromCanonicalName(location); + CanonicalName = location; + DisplayName = GetDisplayNameFromCanonicalName(location); + break; + case NameType.DisplayName: + Name = GetDefaultNameFromDisplayName(location); + CanonicalName = GetCanonicalNameFromDisplayName(location); + DisplayName = location; + break; + } + } + + private enum NameType + { + Name, + CanonicalName, + DisplayName, + } + + /// + /// Gets default Location object: West US. + /// + public static ref readonly LocationData Default => ref WestUS; + + /// + /// Gets a location name consisting of only lowercase characters without white spaces or any separation character between words, e.g. "westus". + /// + public string Name { get; private set; } + + /// + /// Gets a location canonical name consisting of only lowercase chararters with a '-' between words, e.g. "west-us". + /// + public string CanonicalName { get; private set; } + + /// + /// Gets a location display name consisting of titlecase words or alphanumeric characters separated by whitespaces, e.g. "West US" + /// + public string DisplayName { get; private set; } + + /// + /// Creates a new location implicitly from a string. + /// + /// String to be assigned in the Name, CanonicalName or DisplayName form. + public static implicit operator LocationData(string other) + { + if (other == null) + return null; + + var normalizedName = NormalizationUtility(other); + LocationData value; + if (PublicCloudLocations.TryGetValue(normalizedName, out value)) + { + return value; + } + + return new LocationData(other); + } + + /// + /// Creates a string implicitly from a Location object. + /// + /// Location object to be assigned. + public static implicit operator string(LocationData other) + { + if (other == null) + { + return null; + } + + return other.ToString(); + } + + /// + /// Detects if a location object is equal to another location instance or a string representing the location name. + /// + /// Location object or name as a string. + /// True or false. + public bool Equals(LocationData other) + { + if (other == null) + return false; + + return Name == other.Name && CanonicalName == other.CanonicalName && DisplayName == other.DisplayName; + } + + /// + /// Gets the display name of a location object. + /// + /// Display name. + public override string ToString() + { + return DisplayName; + } + + /// + /// Compares this Location name to another Location to expose if it is greater, less or equal than this one. + /// + /// Location object or name as a string. + /// -1 for less than, 0 for equals, 1 for greater than. + public int CompareTo(LocationData other) + { + if (ReferenceEquals(other, null)) + { + return 1; + } + + return string.Compare(Name, other.Name, StringComparison.InvariantCulture); + } + + private static string NormalizationUtility(string value) + { + if (string.IsNullOrEmpty(value)) + { + return value; + } + + var sb = new StringBuilder(value.Length); + for (var index = 0; index < value.Length; ++index) + { + var c = value[index]; + if (char.IsLetterOrDigit(c)) + { + sb.Append(c); + } + } + + return sb.ToString().ToUpperInvariant(); + } + + private static NameType DetectNameType(string location) + { + if (Regex.IsMatch(location, CanonicalPattern)) + { + return NameType.CanonicalName; + } + else if (Regex.IsMatch(location, DisplayPattern)) + { + return NameType.DisplayName; + } + else + { + return NameType.Name; + } + } + + private static string GetCanonicalNameFromDisplayName(string name) + { + return name.Replace(RegexWhitespace, RegexDash).ToLower(CultureInfo.InvariantCulture); + } + + private static string GetDisplayNameFromCanonicalName(string name) + { + char[] chName = name.ToCharArray(); + chName[0] = char.ToUpper(chName[0], CultureInfo.InvariantCulture); + + for (int i = 0; i < chName.Length - 1; i++) + { + if (chName[i] == '-') + { + chName[i] = ' '; + chName[i + 1] = char.ToUpper(chName[i + 1], CultureInfo.InvariantCulture); + } + } + + return new string(chName); + } + + private static string GetDefaultNameFromCanonicalName(string name) + { + return name.Replace(RegexDash, string.Empty); + } + + private static string GetDefaultNameFromDisplayName(string name) + { + return name.Replace(RegexWhitespace, string.Empty).ToLower(CultureInfo.InvariantCulture); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/Plan.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/Plan.cs new file mode 100644 index 0000000000000..6f2186f245b63 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/Plan.cs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; + +namespace Azure.ResourceManager.Core +{ + /// + /// Representation of a publisher plan for marketplace RPs. + /// + public sealed class Plan : IEquatable, IComparable + { + /// + /// Initializes a new instance of the class. + /// + /// Plan's Name. + /// Plan's Publisher. + /// Plan's Product. + /// Plan's Promotion Code. + /// Plan's Version. + internal Plan(string name, string publisher, string product, string promotionCode, string version) + { + Name = name; + Publisher = publisher; + Product = product; + PromotionCode = promotionCode; + Version = version; + } + + /// + /// Initializes a new instance of the class. + /// + /// The plan to copy from. + internal Plan(ResourceManager.Resources.Models.Plan plan) + : this(plan.Name, plan.Publisher, plan.Product, plan.PromotionCode, plan.Version) + { + } + + /// + /// Gets the plan's Name. + /// + public string Name { get; private set; } + + /// + /// Gets the plan's Publisher. + /// + public string Publisher { get; private set; } + + /// + /// Gets the plan's product. + /// + public string Product { get; private set; } + + /// + /// Gets the plan's Promotion Code. + /// + public string PromotionCode { get; private set; } + + /// + /// Gets the plan's version. + /// + public string Version { get; private set; } + + /// + /// Compares this with another instance. + /// + /// object to compare. + /// -1 for less than, 0 for equals, 1 for greater than. + public int CompareTo(Plan other) + { + if (other == null) + return 1; + + if (ReferenceEquals(this, other)) + return 0; + + int compareResult = 0; + if ((compareResult = string.Compare(Name, other.Name, StringComparison.InvariantCultureIgnoreCase)) == 0 && + (compareResult = string.Compare(Product, other.Product, StringComparison.InvariantCultureIgnoreCase)) == 0 && + (compareResult = string.Compare(PromotionCode, other.PromotionCode, StringComparison.InvariantCultureIgnoreCase)) == 0 && + (compareResult = string.Compare(Publisher, other.Publisher, StringComparison.InvariantCultureIgnoreCase)) == 0 && + (compareResult = string.Compare(Version, other.Version, StringComparison.InvariantCultureIgnoreCase)) == 0) + { + return 0; + } + + return compareResult; + } + + /// + /// Compares this instance with another object and determines if they are equals. + /// + /// object to compare. + /// True if they are equals, otherwise false. + public bool Equals(Plan other) + { + if (other == null) + return false; + + if (ReferenceEquals(this, other)) + return true; + + return string.Equals(Name, other.Name, StringComparison.InvariantCultureIgnoreCase) && + string.Equals(Product, other.Product, StringComparison.InvariantCultureIgnoreCase) && + string.Equals(PromotionCode, other.PromotionCode, StringComparison.InvariantCultureIgnoreCase) && + string.Equals(Publisher, other.Publisher, StringComparison.InvariantCultureIgnoreCase) && + string.Equals(Version, other.Version, StringComparison.InvariantCultureIgnoreCase); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/Resource.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/Resource.cs new file mode 100644 index 0000000000000..86a35ac05cf77 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/Resource.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing the base resource used by all azure resources. + /// + public abstract class Resource : IEquatable, IEquatable, IComparable, + IComparable + { + /// + /// Gets or sets the resource identifier. + /// + public abstract ResourceIdentifier Id { get; protected set; } + + /// + /// Gets the name. + /// + public virtual string Name => Id?.Name; + + /// + /// Gets the resource type. + /// + public virtual ResourceType Type => Id?.Type; + + /// + public virtual int CompareTo(Resource other) + { + if (other == null) + return 1; + + if (ReferenceEquals(this, other)) + return 0; + + int compareResult = 0; + if ((compareResult = string.Compare(Id, other.Id, StringComparison.InvariantCultureIgnoreCase)) == 0 && + (compareResult = string.Compare(Name, other.Name, StringComparison.InvariantCultureIgnoreCase)) == 0 && + (compareResult = Type.CompareTo(other.Type)) == 0) + return 0; + + return compareResult; + } + + /// + public virtual int CompareTo(string other) + { + return string.Compare(Id?.Id, other, StringComparison.InvariantCultureIgnoreCase); + } + + /// + public virtual bool Equals(Resource other) + { + if (Id == null) + return false; + + return Id.Equals(other?.Id); + } + + /// + public virtual bool Equals(string other) + { + if (Id == null) + return false; + + return Id.Equals(other); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceFilterCollection.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceFilterCollection.cs new file mode 100644 index 0000000000000..3580836b2a567 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceFilterCollection.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Collections.Generic; + +namespace Azure.ResourceManager.Core.Resources +{ + /// + /// A class representing a collection of arm filters. + /// + public sealed class ResourceFilterCollection + { + /// + /// Initializes a new instance of the class. + /// + public ResourceFilterCollection() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The resource type to filter by. + public ResourceFilterCollection(ResourceType type) + { + ResourceTypeFilter = new ResourceTypeFilter(type); + } + + /// + /// Gets or sets the substring filter to use in the collection. + /// + public ResourceNameFilter SubstringFilter { get; set; } + + /// + /// Gets the resource type filter to use in the collection. + /// + public ResourceTypeFilter ResourceTypeFilter { get; } + + /// + /// Gets or sets the tag filter to use in the collection. + /// + public ResourceTagFilter TagFilter { get; set; } + + /// + public override string ToString() + { + var builder = new List(); + + var substring = ResourceTypeFilter?.GetFilterString(); + if (!string.IsNullOrWhiteSpace(substring)) + { + builder.Add(substring); + } + + substring = SubstringFilter?.GetFilterString(); + if (!string.IsNullOrWhiteSpace(substring)) + { + builder.Add(substring); + } + + substring = TagFilter?.GetFilterString(); + if (!string.IsNullOrWhiteSpace(substring)) + { + builder.Add(substring); + } + + return $"{string.Join(" and ", builder)}"; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceIdentifier.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceIdentifier.cs new file mode 100644 index 0000000000000..1657a5d7ea269 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceIdentifier.cs @@ -0,0 +1,297 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; + +namespace Azure.ResourceManager.Core +{ + /// + /// Canonical Representation of a Resource Identity. + /// + public sealed class ResourceIdentifier : + IEquatable, + IEquatable, + IComparable, + IComparable + { + private readonly IDictionary _partsDictionary = + new Dictionary(StringComparer.OrdinalIgnoreCase); + + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the resource that is the target of operations. + public ResourceIdentifier(string id) + { + Id = id; + Parse(id); + } + + /// + /// Gets the Resource ID. + /// + public string Id { get; private set; } + + /// + /// Gets the Resource Name. + /// + public string Name { get; private set; } + + /// + /// Gets the Resource Type. + /// + public ResourceType Type { get; private set; } + + /// + /// Gets the Subscription. + /// + public string Subscription => _partsDictionary.ContainsKey(KnownKeys.Subscription) + ? _partsDictionary[KnownKeys.Subscription] + : null; + + /// + /// Gets the Resource Group. + /// + public string ResourceGroup => _partsDictionary.ContainsKey(KnownKeys.ResourceGroup) + ? _partsDictionary[KnownKeys.ResourceGroup] + : null; + + /// + /// Gets the Parent. + /// Currently this will contain the identifier for either the parent resource, the resource group, the location, the subscription, or the tenant that is the logical parent of this resource. + /// + public ResourceIdentifier Parent { get; private set; } + + /// + /// Initializes a new instance of the class from a string. + /// + /// String to be implicit converted into a object. + public static implicit operator ResourceIdentifier(string other) + { + if (other is null) + return null; + + return new ResourceIdentifier(other); + } + + /// + /// Creates a new string from a object. + /// + /// object to be implicit converted into an string. + public static implicit operator string(ResourceIdentifier other) + { + if (other is null) + return null; + + return other.Id; + } + + /// + /// Allow static, safe comparisons of resource identifier strings or objects. + /// + /// A resource id. + /// Another resource id. + /// True if the resource ids are equivalent, otherwise False. + public static bool Equals(ResourceIdentifier x, ResourceIdentifier y) + { + if (null == x && null == y) + return true; + + if (null == x || null == y) + return false; + + return x.Equals(y); + } + + /// + /// Allow static null-safe comparisons between resource identifier strings or objects. + /// + /// A resource id. + /// Another resource id. + /// -1 if x < y, 0 if x == y, 1 if x > y. + public static int CompareTo(ResourceIdentifier x, ResourceIdentifier y) + { + if (null == x && null == y) + return 0; + + if (null == x) + return -1; + + if (null == y) + return 1; + + return x.CompareTo(y); + } + + /// + public override int GetHashCode() + { + return Id.GetHashCode(); + } + + /// + public override string ToString() + { + return Id; + } + + /// + /// Compares this instance ID with another instance's ID. + /// + /// object to compare. + /// -1 for less than, 0 for equals, 1 for greater than. + public int CompareTo(ResourceIdentifier other) + { + return string.Compare( + Id?.ToLowerInvariant(), + other?.Id?.ToLowerInvariant(), + StringComparison.InvariantCultureIgnoreCase); + } + + /// + /// Compares this instance ID with another plain text ID. + /// + /// The ID to compare. + /// -1 for less than, 0 for equals, 1 for greater than. + public int CompareTo(string other) + { + return string.Compare( + Id?.ToLowerInvariant(), + other?.ToLowerInvariant(), + StringComparison.InvariantCultureIgnoreCase); + } + + /// + /// Compares this instance ID with another instance's ID and determines if they are equals. + /// + /// object to compare. + /// True if they are equals, otherwise false. + public bool Equals(ResourceIdentifier other) + { + return string.Equals( + Id?.ToLowerInvariant(), + other?.Id?.ToLowerInvariant(), + StringComparison.InvariantCultureIgnoreCase); + } + + /// + /// Compares this instance ID with another plain text ID. and determines if they are equals. + /// + /// The ID to compare. + /// True if they are equals, otherwise false. + public bool Equals(string other) + { + return string.Equals( + Id?.ToLowerInvariant(), + other?.ToLowerInvariant(), + StringComparison.InvariantCultureIgnoreCase); + } + + /// + /// Populate Resource Identity fields from input string. + /// + /// A properly formed resource identity. + private void Parse(string id) + { + // Throw for null, empty, and string without the correct form + if (string.IsNullOrWhiteSpace(id) || !id.Contains('/')) + throw new ArgumentOutOfRangeException($"'{id}' is not a valid resource"); + + // Resource ID paths consist mainly of name/value pairs. Split the uri so we have an array of name/value pairs + var parts = id.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).ToList(); + + // There must be at least one name/value pair for the resource id to be valid + if (parts.Count < 2) + throw new ArgumentOutOfRangeException($"'{id}' is not a valid resource"); + + // This is asserting that resources must start with '/subscriptions', /tenants, or /locations. + // TODO: we will need to update this code to accomodate tenant based resources (which start with /providers) + if (!(KnownKeys.Subscription.Equals(parts[0], StringComparison.InvariantCultureIgnoreCase) || + KnownKeys.Tenant.Equals(parts[0], StringComparison.InvariantCultureIgnoreCase) || + KnownKeys.Location.Equals(parts[0], StringComparison.InvariantCultureIgnoreCase))) + { + throw new ArgumentOutOfRangeException($"'{id}' is not a valid resource"); + } + + Type = new ResourceType(id); + + // In the case that this resource is a singleton proxy resource, the number of parts will be odd, + // where the last part is the type name of the singleton + if (parts.Count % 2 != 0) + { + _partsDictionary.Add(KnownKeys.UntrackedSubResource, parts.Last()); + parts.RemoveAt(parts.Count - 1); + } + + // This spplits into resource that come from a provider (which have the providers keyword) and + // resources that are built in to ARM (e.g. /subscriptions/{sub}, /subscriptions/{sub}/resourceGroups/{rg}) + // TODO: This code will need to be updates for extension resources, which have two providers + if (id.ToLowerInvariant().Contains("providers")) + { + ParseProviderResource(parts); + } + else + { + ParseGenericResource(parts); + } + } + + /// + /// Helper method to parse a built in resource. + /// + /// Resource ID paths consisting of name/value pairs. + private void ParseGenericResource(IList parts) + { + Debug.Assert(parts != null, "Parts parameter is null."); + Debug.Assert(parts.Count > 1, "Parts should be a list containing more than 1 elements."); + + // The resource consists of well-known name-value pairs. Make a resource dictionary + // using the names as keys, and the values as values + for (var i = 0; i < parts.Count - 1; i += 2) + { + _partsDictionary.Add(parts[i], parts[i + 1]); + } + + // resource name is always the last part + Name = parts.Last(); + parts.RemoveAt(parts.Count - 1); + parts.RemoveAt(parts.Count - 1); + + // remove the last key/value pair to arrive at the parent (Count will be zero for /subscriptions/{foo}) + Parent = parts.Count > 1 ? new ResourceIdentifier($"/{string.Join("/", parts)}") : null; + } + + /// + /// Helper method to parse a resource that comes from a provider. + /// + /// Resource ID paths consisting of name/value pairs. + private void ParseProviderResource(IList parts) + { + // The resource consists of name/value pairs, make a dictionary out of it + for (var i = 0; i < parts.Count - 1; i += 2) + { + _partsDictionary[parts[i]] = parts[i + 1]; + } + + Name = parts.Last(); + parts.RemoveAt(parts.Count - 1); + + // remove the type name (there will be no typename if this is a singleton sub resource) + if (parts.Count % 2 == 1) + parts.RemoveAt(parts.Count - 1); + + // If this is a top-level resource, remove the providers/Namespace pair, otherwise continue + if (parts.Count > 2 && string.Equals(parts[parts.Count - 2], KnownKeys.ProviderNamespace)) + { + parts.RemoveAt(parts.Count - 1); + parts.RemoveAt(parts.Count - 1); + } + + // If this is not a top-level resource, it will have a parent + Parent = parts.Count > 1 ? new ResourceIdentifier($"/{string.Join("/", parts)}") : null; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceIdentity.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceIdentity.cs new file mode 100644 index 0000000000000..ecba2a9905c86 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceIdentity.cs @@ -0,0 +1,236 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core; +using System; +using System.Collections.Generic; +using System.Text.Json; + +namespace Azure.ResourceManager.Core +{ + /// + /// Represents a managed identity + /// + public class ResourceIdentity : IEquatable + { + private const string SystemAssigned = "SystemAssigned"; + private const string UserAssigned = "UserAssigned"; + private const string SystemAndUserAssigned = "SystemAssigned, UserAssigned"; + + /// + /// Initializes a new instance of the class. + /// + public ResourceIdentity() + : this(null, false) + { + } // not system or user + + /// + /// Initializes a new instance of the class. + /// + /// Dictionary with a key and a object value. + /// Flag for using or not. + public ResourceIdentity(Dictionary user, bool useSystemAssigned) + { + // check for combination of user and system on the impact to type value + SystemAssignedIdentity = useSystemAssigned ? new SystemAssignedIdentity() : null; + UserAssignedIdentities = new Dictionary(); + if (user != null) + { + foreach (KeyValuePair id in user) + { + UserAssignedIdentities.Add(id.Key, id.Value); + } + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The to use. + /// Dictionary with a key and a object value. + public ResourceIdentity(SystemAssignedIdentity systemAssigned, IDictionary user) + { + // TODO: remove this constructor later + SystemAssignedIdentity = systemAssigned; + if (user == null) + { + UserAssignedIdentities = new Dictionary(); + } + else + { + UserAssignedIdentities = user; + } + } + + /// + /// Gets the SystemAssignedIdentity. + /// + public SystemAssignedIdentity SystemAssignedIdentity { get; private set; } + + /// + /// Gets a dictionary of the User Assigned Identities. + /// + public IDictionary UserAssignedIdentities { get; private set; } + + /// + /// Converts a into an object. + /// + /// A containing an . + /// New Identity object with JSON values. + internal static ResourceIdentity Deserialize(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Undefined) + { + throw new ArgumentException("JsonElement cannot be undefined ", nameof(element)); + } + + Optional systemAssignedIdentity = default; + IDictionary userAssignedIdentities = new Dictionary(); + string type = string.Empty; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("userAssignedIdentities")) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + userAssignedIdentities = null; + continue; + } + + string resourceId = string.Empty; + foreach (var keyValuePair in property.Value.EnumerateObject()) + { + resourceId = keyValuePair.Name; + var userAssignedIdentity = UserAssignedIdentity.Deserialize(keyValuePair.Value); + userAssignedIdentities.Add(resourceId, userAssignedIdentity); + } + + continue; + } + + if (property.NameEquals("type")) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + throw new InvalidOperationException("The type property had a JsonValueKind equal to Null"); + } + + type = property.Value.GetString(); + } + + if (type.Equals(SystemAssigned)) + { + systemAssignedIdentity = SystemAssignedIdentity.Deserialize(element); + continue; + } + + if (type.Equals(SystemAndUserAssigned)) + { + systemAssignedIdentity = SystemAssignedIdentity.Deserialize(element); + continue; + } + } + + return new ResourceIdentity(systemAssignedIdentity, userAssignedIdentities); + } + + /// + /// Converts an object into a . + /// + /// Utf8JsonWriter object to which the output is going to be written. + /// Identity object to be converted. + internal static void Serialize(Utf8JsonWriter writer, ResourceIdentity identity) + { + if (writer == null) + throw new ArgumentNullException(nameof(writer)); + + if (identity == null) + throw new ArgumentNullException(nameof(identity)); + + writer.WriteStartObject(); + writer.WritePropertyName("identity"); + + if (identity.SystemAssignedIdentity == null && identity.UserAssignedIdentities.Count == 0) + { + writer.WriteStringValue("null"); + writer.WriteEndObject(); + writer.Flush(); + return; + } + + writer.WriteStartObject(); + if (identity.SystemAssignedIdentity != null && identity.UserAssignedIdentities.Count != 0) + { + SystemAssignedIdentity.Serialize(writer, identity.SystemAssignedIdentity); + writer.WritePropertyName("kind"); + writer.WriteStringValue(SystemAndUserAssigned); + writer.WritePropertyName("userAssignedIdentities"); + writer.WriteStartObject(); + foreach (var keyValuePair in identity.UserAssignedIdentities) + { + writer.WritePropertyName(keyValuePair.Key); + UserAssignedIdentity.Serialize(writer, keyValuePair.Value); + } + + writer.WriteEndObject(); + } + else if (identity.SystemAssignedIdentity != null) + { + SystemAssignedIdentity.Serialize(writer, identity.SystemAssignedIdentity); + writer.WritePropertyName("kind"); + writer.WriteStringValue(SystemAssigned); + } + else if (identity.UserAssignedIdentities.Count != 0) + { + writer.WritePropertyName("kind"); + writer.WriteStringValue(UserAssigned); + writer.WritePropertyName("userAssignedIdentities"); + writer.WriteStartObject(); + foreach (var keyValuePair in identity.UserAssignedIdentities) + { + writer.WritePropertyName(keyValuePair.Key); + UserAssignedIdentity.Serialize(writer, keyValuePair.Value); + } + + writer.WriteEndObject(); + } + + writer.WriteEndObject(); + writer.WriteEndObject(); + writer.Flush(); + } + + /// + /// Detects if this Identity is equals to another Identity instance. + /// + /// Identity object to compare. + /// True if they are equal, otherwise False. + public bool Equals(ResourceIdentity other) + { + if (other == null) + return false; + + if (UserAssignedIdentities.Count == other.UserAssignedIdentities.Count) + { + foreach (var identity in UserAssignedIdentities) + { + UserAssignedIdentity value; + if (other.UserAssignedIdentities.TryGetValue(identity.Key, out value)) + { + if (!UserAssignedIdentity.Equals(identity.Value, value)) + { + return false; + } + } + else + { + return false; + } + } + } + + return SystemAssignedIdentity.Equals(SystemAssignedIdentity, other.SystemAssignedIdentity); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceNameFilter.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceNameFilter.cs new file mode 100644 index 0000000000000..6f8fe88f4584b --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceNameFilter.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Core.Resources +{ + /// + /// A class representing a substring filter used in Azure API calls. + /// + public class ResourceNameFilter : GenericResourceFilter, IEquatable, IEquatable + { + /// + /// Gets or sets the name. + /// + public string Name { get; set; } + + /// + /// Gets or sets the resource group. + /// + public string ResourceGroup { get; set; } + + /// + /// Converts a string into an . + /// + /// The string that can be match in any part of the resource name. + public static implicit operator ResourceNameFilter(string nameString) + { + if (nameString is null) + return null; + + return new ResourceNameFilter { Name = nameString }; + } + + /// + public bool Equals(string other) + { + if (other is null) + return false; + + return string.Equals(other, Name); + } + + /// + public bool Equals(ResourceNameFilter other) + { + if (other is null) + return false; + + return string.Equals(other.Name, Name); + } + + /// + public override string GetFilterString() + { + var builder = new List(); + if (!string.IsNullOrWhiteSpace(Name)) + { + builder.Add($"substringof('{Name}', name)"); + } + + if (!string.IsNullOrWhiteSpace(ResourceGroup)) + { + builder.Add($"substringof('{ResourceGroup}', name)"); + } + + return string.Join(" and ", builder); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceTagFilter.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceTagFilter.cs new file mode 100644 index 0000000000000..c49c0433fec0b --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceTagFilter.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; + +namespace Azure.ResourceManager.Core.Resources +{ + /// + /// A class representing a tag filter used in Azure API calls. + /// + public class ResourceTagFilter : GenericResourceFilter, IEquatable + { + private readonly Tuple _tag; + + /// + /// Initializes a new instance of the class. + /// + /// The tag to filter by. + public ResourceTagFilter(Tuple tag) + { + if (tag?.Item1 is null || tag?.Item2 is null) + throw new ArgumentNullException(nameof(tag), "The tag, its key, and its value must not be null"); + + _tag = tag; + Key = _tag.Item1; + Value = _tag.Item2; + } + + /// + /// Initializes a new instance of the class. + /// + /// The key of the tag to filter by. + /// The value of the tag to filter by. + public ResourceTagFilter(string tagKey, string tagValue) + : this(new Tuple(tagKey, tagValue)) + { + } + + /// + /// Gets the key to filter by. + /// + public string Key { get; } + + /// + /// Gets the value to filter by. + /// + public string Value { get; } + + /// + public bool Equals(ResourceTagFilter other) + { + if (other is null) + return false; + + return string.Equals(other.Key, Key) && + string.Equals(other.Value, Value); + } + + /// + public override string GetFilterString() + { + return $"tagName eq '{_tag.Item1}' and tagValue eq '{_tag.Item2}'"; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceType.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceType.cs new file mode 100644 index 0000000000000..b4dc44088dfee --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceType.cs @@ -0,0 +1,325 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.ResourceManager.Core +{ + /// + /// Structure respresenting a resource type + /// + public sealed class ResourceType : IEquatable, IEquatable, IComparable, + IComparable + { + /// + /// The "none" resource type + /// + public static readonly ResourceType None = new ResourceType { Namespace = string.Empty, Type = string.Empty }; + + /// + /// Initializes a new instance of the class. + /// + /// Option to provide the Resource Type directly, or a Resource ID from which the type is going to be obtained. + public ResourceType(string resourceIdOrType) + { + if (string.IsNullOrWhiteSpace(resourceIdOrType)) + throw new ArgumentException($"{nameof(resourceIdOrType)} cannot be null or whitespace", nameof(resourceIdOrType)); + + Parse(resourceIdOrType); + } + + private ResourceType() + { + } + + /// + /// Gets the resource type Namespace. + /// + public string Namespace { get; private set; } + + /// + /// Gets the resource Type. + /// + public string Type { get; private set; } + + /// + /// Gets the resource type Parent. + /// + public ResourceType Parent + { + get + { + var parts = Type.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); + + if (parts.Length < 2) + return None; + + var list = new List(parts); + list.RemoveAt(list.Count - 1); + + return new ResourceType($"{Namespace}/{string.Join("/", list.ToArray())}"); + } + } + + /// + /// Implicit operator for initializing a instance from a string. + /// + /// String to be conferted into a object. + public static implicit operator ResourceType(string other) + { + if (other is null) + return null; + + return new ResourceType(other); + } + + /// + /// Compares a object with a . + /// + /// object. + /// String. + /// True if they are equal, otherwise False. + public static bool operator ==(ResourceType source, string target) + { + if (source is null) + return target is null; + + return source.Equals(target); + } + + /// + /// Compares a with a object. + /// + /// String representation of a ResourceType. + /// object. + /// True if they are equal, otherwise False. + public static bool operator ==(string source, ResourceType target) + { + if (target is null) + return source is null; + + return target.Equals(source); + } + + /// + /// Compares two objects. + /// + /// First object. + /// Second object. + /// True if they are equal, otherwise False. + public static bool operator ==(ResourceType source, ResourceType target) + { + if (source is null) + return target is null; + + return source.Equals(target); + } + + /// + /// Compares a object with a . + /// + /// object. + /// String representation of a ResourceType. + /// False if they are equal, otherwise True. + public static bool operator !=(ResourceType source, string target) + { + if (source is null) + return !(target is null); + + return !source.Equals(target); + } + + /// + /// Compares a with a object. + /// + /// String. + /// object. + /// False if they are equal, otherwise True. + public static bool operator !=(string source, ResourceType target) + { + if (target is null) + return !(source is null); + + return !target.Equals(source); + } + + /// + /// Compares two objects. + /// + /// First object. + /// Second object. + /// False if they are equal, otherwise True. + public static bool operator !=(ResourceType source, ResourceType target) + { + if (source is null) + return !(target is null); + + return !source.Equals(target); + } + + /// + /// Compares this with another instance. + /// + /// object to compare. + /// -1 for less than, 0 for equals, 1 for greater than. + public int CompareTo(ResourceType other) + { + if (other is null) + return 1; + + if (ReferenceEquals(this, other)) + return 0; + + int compareResult = 0; + if ((compareResult = string.Compare(Namespace, other.Namespace, StringComparison.InvariantCultureIgnoreCase)) == 0 && + (compareResult = string.Compare(Type, other.Type, StringComparison.InvariantCultureIgnoreCase)) == 0 && + (other.Parent != null)) + { + return Parent.CompareTo(other.Parent); + } + + return compareResult; + } + + /// + /// Compares this with a resource type representation as a string. + /// + /// String to compare. + /// -1 for less than, 0 for equals, 1 for greater than. + public int CompareTo(string other) + { + if (other is null) + return 1; + + return CompareTo(new ResourceType(other)); + } + + /// + /// Compares this instance with another object and determines if they are equals. + /// + /// object to compare. + /// True if they are equals, otherwise false. + public bool Equals(ResourceType other) + { + if (other is null) + return false; + + return string.Equals(ToString(), other.ToString(), StringComparison.InvariantCultureIgnoreCase); + } + + /// + /// Compares this instance with a string and determines if they are equals. + /// + /// String to compare. + /// True if they are equals, otherwise false. + public bool Equals(string other) + { + if (other is null) + return false; + + return string.Equals(ToString(), other, StringComparison.InvariantCultureIgnoreCase); + } + + /// + public override string ToString() + { + return $"{Namespace}/{Type}"; + } + + /// + public override bool Equals(object obj) + { + if (obj is null) + return false; + + var resourceObj = obj as ResourceType; + + if (resourceObj != null) + return Equals(resourceObj); + + var stringObj = obj as string; + + if (stringObj != null) + return Equals(stringObj); + + return base.Equals(obj); + } + + /// + public override int GetHashCode() + { + return ToString().GetHashCode(); + } + + /// + /// Helper method to determine if the given string is a Resource ID or a Type, + /// and then assign the proper values to the class properties. + /// + /// String to be parsed. + private void Parse(string resourceIdOrType) + { + // Note that this code will either parse a resource id to find the type, or a resource type + resourceIdOrType = resourceIdOrType.Trim('/'); + + // split the path into segments + var parts = resourceIdOrType.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).ToList(); + + // There must be at least a namespace and type name + if (parts.Count < 1) + throw new ArgumentOutOfRangeException(nameof(resourceIdOrType)); + + // if the type is just subscriptions, it is a built-in type in the Microsoft.Resources namespace + if (parts.Count == 1) + { + // Simple resource type + Type = parts[0]; + Namespace = "Microsoft.Resources"; + } + + // Handle resource identifiers from RPs (they have the /providers path segment) + if (parts.Contains(KnownKeys.ProviderNamespace)) + { + // it is a resource id from a provider + var index = parts.LastIndexOf(KnownKeys.ProviderNamespace); + for (var i = index; i >= 0; --i) + { + parts.RemoveAt(i); + } + + if (parts.Count < 3) + throw new ArgumentOutOfRangeException(nameof(resourceIdOrType), "Invalid resource id."); + + var type = new List(); + for (var i = 1; i < parts.Count; i += 2) + { + type.Add(parts[i]); + } + + Namespace = parts[0]; + Type = string.Join("/", type); + } + + // Handle resource types (Micsrsoft.Compute/virtualMachines, Microsoft.Network/virtualNetworks/subnets) + else if (parts[0].Contains('.')) + { + // it is a full type name + Namespace = parts[0]; + Type = string.Join("/", parts.Skip(Math.Max(0, 1)).Take(parts.Count - 1)); + } + + // Handle built-in resource ids (e.g. /subscriptions/{sub}, /subscriptions/{sub}/resourceGroups/{rg}) + else if (parts.Count % 2 == 0) + { + // primitive resource manager resource id + Namespace = "Microsoft.Resources"; + Type = parts[parts.Count - 2]; + } + else + { + throw new ArgumentOutOfRangeException(nameof(resourceIdOrType)); + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceTypeFilter.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceTypeFilter.cs new file mode 100644 index 0000000000000..099584c5d3991 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/ResourceTypeFilter.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; + +namespace Azure.ResourceManager.Core.Resources +{ + /// + /// A class representing a resource type filter used in Azure API calls. + /// + public class ResourceTypeFilter : GenericResourceFilter, IEquatable, IEquatable + { + /// + /// Initializes a new instance of the class. + /// + /// The resource type to filter by. + public ResourceTypeFilter(ResourceType resourceType) + { + ResourceType = resourceType; + } + + /// + /// Gets the resource type to filter by. + /// + public ResourceType ResourceType { get; } + + /// + public bool Equals(string other) + { + throw new NotImplementedException(); + } + + /// + public bool Equals(ResourceTypeFilter other) + { + throw new NotImplementedException(); + } + + /// + public override string GetFilterString() + { + return $"resourceType EQ '{ResourceType}'"; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/Sku.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/Sku.cs new file mode 100644 index 0000000000000..25008bfb6f51c --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/Sku.cs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using Azure.ResourceManager.Resources.Models; + +namespace Azure.ResourceManager.Core +{ + /// + /// Representaion of ARM SKU + /// + public sealed class Sku : IEquatable, IComparable + { + /// + /// Initializes a new instance of the class. + /// + /// SKU's name. + /// SKU's tier. + /// SKU's family. + /// SKU's size. + /// SKU's capacity. + internal Sku(string name, string tier, string family, string size, long? capacity = null) + { + Name = name; + Tier = tier; + Family = family; + Size = size; + Capacity = capacity; + } + + /// + /// Initializes a new instance of the class. + /// + /// The sku to copy from. + internal Sku(ResourceManager.Resources.Models.Sku sku) + : this(sku.Name, sku.Tier, sku.Family, sku.Size, sku.Capacity) + { + } + + /// + /// Gets the Name. + /// + public string Name { get; private set; } + + /// + /// Gets the Tier. + /// + public string Tier { get; private set; } + + /// + /// Gets the Family. + /// + public string Family { get; private set; } + + /// + /// Gets the Size. + /// + public string Size { get; private set; } + + /// + /// Gets the Capacity. + /// + public long? Capacity { get; private set; } + + /// + /// Compares this with another instance. + /// + /// object to compare. + /// -1 for less than, 0 for equals, 1 for greater than. + public int CompareTo(Sku other) + { + if (other == null) + return 1; + + if (object.ReferenceEquals(this, other)) + return 0; + + int compareResult = 0; + if ((compareResult = string.Compare(Name, other.Name, StringComparison.InvariantCultureIgnoreCase)) == 0 && + (compareResult = string.Compare(Family, other.Family, StringComparison.InvariantCultureIgnoreCase)) == 0 && + (compareResult = string.Compare(Size, other.Size, StringComparison.InvariantCultureIgnoreCase)) == 0 && + (compareResult = string.Compare(Tier, other.Tier, StringComparison.InvariantCultureIgnoreCase)) == 0) + { + return Nullable.Compare(Capacity, other.Capacity); + } + + return compareResult; + } + + /// + /// Compares this instance with another object and determines if they are equals. + /// + /// object to compare. + /// True if they are equals, otherwise false. + public bool Equals(Sku other) + { + if (other == null) + return false; + + if (object.ReferenceEquals(this, other)) + return true; + + return string.Equals(Name, other.Name, StringComparison.InvariantCultureIgnoreCase) && + string.Equals(Family, other.Family, StringComparison.InvariantCultureIgnoreCase) && + string.Equals(Size, other.Size, StringComparison.InvariantCultureIgnoreCase) && + string.Equals(Tier, other.Tier, StringComparison.InvariantCultureIgnoreCase) && + long.Equals(Capacity, other.Capacity); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/SystemAssignedIdentity.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/SystemAssignedIdentity.cs new file mode 100644 index 0000000000000..e2f7dcbc73219 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/SystemAssignedIdentity.cs @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Azure.ResourceManager.Core +{ + using System; + using System.Text.Json; + using Azure.Core; + + /// + /// A class representing an Identity assigned by the system. + /// + public sealed class SystemAssignedIdentity + { + /// + /// Initializes a new instance of the class with Null properties. + /// + public SystemAssignedIdentity() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// Application TenantId . + /// PrincipalId. + public SystemAssignedIdentity(Guid tenantId, Guid principalId) + { + TenantId = tenantId; + PrincipalId = principalId; + } + + /// + /// Gets the Tenant ID. + /// + public Guid? TenantId { get; private set; } + + /// + /// Gets the Principal ID. + /// + public Guid? PrincipalId { get; private set; } + + /// + /// Converts a into an object. + /// + /// A containing an identity. + /// New object with JSON values. + internal static SystemAssignedIdentity Deserialize(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Undefined) + { + throw new ArgumentException("JsonElement cannot be undefined ", nameof(element)); + } + + Guid principalId = default; + Guid tenantId = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("principalId")) + { + if (property.Value.ValueKind != JsonValueKind.Null) + principalId = Guid.Parse(property.Value.GetString()); + } + + if (property.NameEquals("tenantId")) + { + if (property.Value.ValueKind != JsonValueKind.Null) + tenantId = Guid.Parse(property.Value.GetString()); + } + } + + if (principalId == default(Guid) && tenantId == default(Guid)) + return null; + + if (principalId == default(Guid) || tenantId == default(Guid)) + throw new InvalidOperationException("Either TenantId or PrincipalId were null"); + + return new SystemAssignedIdentity(tenantId, principalId); + } + + /// + /// Converts an object into a . + /// + /// Utf8JsonWriter object to which the output is going to be written. + /// object to be converted. + internal static void Serialize(Utf8JsonWriter writer, SystemAssignedIdentity systemAssignedIdentity) + { + if (systemAssignedIdentity == null) + throw new ArgumentNullException(nameof(systemAssignedIdentity)); + + if (writer == null) + throw new ArgumentNullException(nameof(writer)); + + writer.WritePropertyName("principalId"); + if (!Optional.IsDefined(systemAssignedIdentity.PrincipalId)) + { + writer.WriteStringValue("null"); + } + else + { + writer.WriteStringValue(systemAssignedIdentity.PrincipalId.ToString()); + } + + writer.WritePropertyName("tenantId"); + if (!Optional.IsDefined(systemAssignedIdentity.TenantId)) + { + writer.WriteStringValue("null"); + } + else + { + writer.WriteStringValue(systemAssignedIdentity.TenantId.ToString()); + } + + writer.Flush(); + } + + /// + /// Compares two objects to determine if they are equal. + /// + /// First object to compare. + /// Second object to compare. + /// True if they are equal, otherwise False. + public static bool Equals(SystemAssignedIdentity original, SystemAssignedIdentity other) + { + if (original == null) + return other == null; + + return original.Equals(other); + } + + /// + /// Compares this with another instance. + /// + /// object to compare. + /// -1 for less than, 0 for equals, 1 for greater than. + public int CompareTo(SystemAssignedIdentity other) + { + if (other == null) + return 1; + + int compareResult = 0; + if ((compareResult = TenantId.GetValueOrDefault().CompareTo(other.TenantId.GetValueOrDefault())) == 0 && + (compareResult = PrincipalId.GetValueOrDefault().CompareTo(other.PrincipalId.GetValueOrDefault())) == 0) + return 0; + + return compareResult; + } + + /// + /// Compares this instance with another object and determines if they are equals. + /// + /// object to compare. + /// True if they are equal, otherwise false. + public bool Equals(SystemAssignedIdentity other) + { + if (other == null) + return false; + + return TenantId.Equals(other.TenantId) && PrincipalId.Equals(other.PrincipalId); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/TrackedResource.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/TrackedResource.cs new file mode 100644 index 0000000000000..29a7d114752b2 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/TrackedResource.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Core +{ + /// + /// Generic representation of a tracked resource. All tracked resources should extend this class + /// + public abstract class TrackedResource : Resource + { + /// + /// Gets the tags. + /// + public virtual IDictionary Tags => + new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + /// + /// Gets or sets the location the resource is in. + /// + public virtual LocationData Location { get; protected set; } + + /// + /// Gets or sets the identifier for the resource. + /// + public override ResourceIdentifier Id { get; protected set; } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/UserAssignedIdentity.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/UserAssignedIdentity.cs new file mode 100644 index 0000000000000..3450deff2ff75 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Resources/UserAssignedIdentity.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Azure.ResourceManager.Core +{ + using System; + using System.Text.Json; + using Azure.Core; + + /// + /// A class representing an Identity assigned by the user. + /// + public sealed class UserAssignedIdentity + { + /// + /// Initializes a new instance of the class. + /// + /// ClientId . + /// PrincipalId. + public UserAssignedIdentity(Guid clientId, Guid principalId) + { + ClientId = clientId; + PrincipalId = principalId; + } + + /// + /// Gets or sets the Client ID. + /// + public Guid ClientId { get; set; } + + /// + /// Gets or sets the Principal ID. + /// + public Guid PrincipalId { get; set; } + + /// + /// Converts a into an object. + /// + /// A containing an identity. + /// New object with JSON values. + internal static UserAssignedIdentity Deserialize(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Undefined) + { + throw new ArgumentException("JsonElement is undefined " + nameof(element)); + } + + Guid principalId = default; + Guid clientId = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("principalId")) + { + if (property.Value.ValueKind != JsonValueKind.Null) + principalId = Guid.Parse(property.Value.GetString()); + } + + if (property.NameEquals("clientId")) + { + if (property.Value.ValueKind != JsonValueKind.Null) + clientId = Guid.Parse(property.Value.GetString()); + } + } + + if (principalId == default(Guid) && clientId == default(Guid)) + return null; + + if (principalId == default(Guid) || clientId == default(Guid)) + throw new InvalidOperationException("Either ClientId or PrincipalId were null"); + + return new UserAssignedIdentity(clientId, principalId); + } + + /// + /// Converts an object into a . + /// + /// Utf8JsonWriter object to which the output is going to be written. + /// object to be converted. + internal static void Serialize(Utf8JsonWriter writer, UserAssignedIdentity userAssignedIdentity) + { + if (userAssignedIdentity == null) + throw new ArgumentNullException(nameof(userAssignedIdentity)); + + if (writer == null) + throw new ArgumentNullException(nameof(writer)); + + writer.WriteStartObject(); + + writer.WritePropertyName("clientId"); + writer.WriteStringValue(userAssignedIdentity.ClientId.ToString()); + + writer.WritePropertyName("principalId"); + writer.WriteStringValue(userAssignedIdentity.PrincipalId.ToString()); + + writer.WriteEndObject(); + writer.Flush(); + } + + /// + /// Compares two objects to determine if they are equal. + /// + /// First object to compare. + /// Second object to compare. + /// True if they are equal, otherwise False. + public static bool Equals(UserAssignedIdentity original, UserAssignedIdentity other) + { + if (original == null) + return other == null; + + return original.Equals(other); + } + + /// + /// Compares this with another instance. + /// + /// object to compare. + /// -1 for less than, 0 for equals, 1 for greater than. + public int CompareTo(UserAssignedIdentity other) + { + if (other == null) + return 1; + + int compareResult = 0; + if ((compareResult = ClientId.CompareTo(other.ClientId)) == 0 && + (compareResult = PrincipalId.CompareTo(other.PrincipalId)) == 0) + { + return 0; + } + + return compareResult; + } + + /// + /// Compares this instance with another object and determines if they are equals. + /// + /// object to compare. + /// True if they are equal, otherwise false. + public bool Equals(UserAssignedIdentity other) + { + if (other == null) + return false; + + return ClientId.Equals(other.ClientId) && PrincipalId.Equals(other.PrincipalId); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Subscription.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Subscription.cs new file mode 100644 index 0000000000000..c980886409c99 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Subscription.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing a Subscription along with the instance operations that can be performed on it. + /// + public class Subscription : SubscriptionOperations + { + /// + /// Initializes a new instance of the class. + /// + /// The subscription operations to copy the client options from. + /// The resource data model. + internal Subscription(SubscriptionOperations subscription, SubscriptionData subscriptionData) + : base(subscription, subscriptionData.Id) + { + Data = subscriptionData; + } + + /// + /// Gets the subscription data model. + /// + public SubscriptionData Data { get; } + + /// + protected override Subscription GetResource() + { + return this; + } + + /// + protected override Task GetResourceAsync() + { + return Task.FromResult(this); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/SubscriptionContainer.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/SubscriptionContainer.cs new file mode 100644 index 0000000000000..c4bb2ca123434 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/SubscriptionContainer.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core; +using Azure.ResourceManager.Core.Adapters; +using Azure.ResourceManager.Resources; +using System; +using System.Threading; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing collection of Subscription and their operations + /// + public class SubscriptionContainer : ContainerBase + { + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// A credential used to authenticate to an Azure Service. + /// The base URI of the service. + internal SubscriptionContainer(AzureResourceManagerClientOptions options, TokenCredential credential, Uri baseUri) + : base(options, null, credential, baseUri) + { + } + + /// + /// Gets the valid resource type associated with the container. + /// + protected override ResourceType ValidResourceType => SubscriptionOperations.ResourceType; + + /// + /// Gets the operations that can be performed on the container. + /// + private SubscriptionsOperations Operations => new ResourcesManagementClient( + BaseUri, + Guid.NewGuid().ToString(), + Credential, + ClientOptions.Convert()).Subscriptions; + + /// + /// Lists all subscriptions in the current container. + /// + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// A collection of resource operations that may take multiple service requests to iterate over. + public Pageable List(CancellationToken cancellationToken = default) + { + return new PhWrappingPageable( + Operations.List(cancellationToken), + Converter()); + } + + /// + /// Lists all subscriptions in the current container. + /// + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// An async collection of resource operations that may take multiple service requests to iterate over. + public AsyncPageable ListAsync(CancellationToken cancellationToken = default) + { + return new PhWrappingAsyncPageable( + Operations.ListAsync(cancellationToken), + Converter()); + } + + /// + /// Validate the resource identifier is supported in the current container. + /// + /// The identifier of the resource. + protected override void Validate(ResourceIdentifier identifier) + { + if (identifier != null) + throw new ArgumentException("Invalid parent for subscription container"); + } + + /// + /// Get an instance of the operations this container holds. + /// + /// The guid of the subscription to be found. + /// An instance of . + protected override ResourceOperationsBase GetOperation(string subscriptionGuid) + { + return new SubscriptionOperations(ClientOptions, subscriptionGuid, Credential, BaseUri); + } + + private Func Converter() + { + return s => new Subscription(new SubscriptionOperations(ClientOptions, s.SubscriptionId, Credential, BaseUri), new SubscriptionData(s)); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/SubscriptionOperations.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/SubscriptionOperations.cs new file mode 100644 index 0000000000000..58d527f3c6f42 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/SubscriptionOperations.cs @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.ResourceManager.Resources; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class representing the operations that can be performed over a specific subscription. + /// + public class SubscriptionOperations : ResourceOperationsBase + { + /// + /// The resource type for subscription + /// + public static readonly ResourceType ResourceType = "Microsoft.Resources/subscriptions"; + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The Id of the subscription. + /// A credential used to authenticate to an Azure Service. + /// The base URI of the service. + internal SubscriptionOperations(AzureResourceManagerClientOptions options, string subscriptionId, TokenCredential credential, Uri baseUri) + : base(options, $"/subscriptions/{subscriptionId}", credential, baseUri) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The subscription operations to copy client options from. + /// The identifier of the subscription. + protected SubscriptionOperations(SubscriptionOperations subscription, ResourceIdentifier id) + : base(subscription.ClientOptions, id, subscription.Credential, subscription.BaseUri) + { + } + + /// + /// Gets the valid resource type for this operation class + /// + protected override ResourceType ValidResourceType => ResourceType; + + private SubscriptionsOperations SubscriptionsClient => new ResourcesManagementClient( + BaseUri, + Guid.NewGuid().ToString(), + Credential, + ClientOptions.Convert()).Subscriptions; + + /// + /// Gets the resource group operations for a given resource group. + /// + /// The name of the resource group. + /// The resource group operations. + /// resourceGroupName must be at least one character long and cannot be longer than 90 characters. + /// The name of the resource group can include alphanumeric, underscore, parentheses, hyphen, period (except at end), and Unicode characters that match the allowed characters. + public ResourceGroupOperations GetResourceGroupOperations(string resourceGroupName) + { + return new ResourceGroupOperations(this, resourceGroupName); + } + + /// + /// Gets the resource group container under this subscription + /// + /// The resource group container. + public ResourceGroupContainer GetResourceGroupContainer() + { + return new ResourceGroupContainer(this); + } + + /// + /// Gets the location group container under this subscription + /// + /// The resource group container. + public LocationContainer GetLocationContainer() + { + return new LocationContainer(this); + } + + /// + public override ArmResponse Get() + { + return new PhArmResponse( + SubscriptionsClient.Get(Id.Name), + Converter()); + } + + /// + public override async Task> GetAsync(CancellationToken cancellationToken = default) + { + return new PhArmResponse( + await SubscriptionsClient.GetAsync(Id.Name, cancellationToken).ConfigureAwait(false), + Converter()); + } + + private Func Converter() + { + return s => new Subscription(this, new SubscriptionData(s)); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/src/Utils/UtilityExtensions.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Utils/UtilityExtensions.cs new file mode 100644 index 0000000000000..6da86bd8fd7d3 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/src/Utils/UtilityExtensions.cs @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Collections.Generic; + +namespace Azure.ResourceManager.Core +{ + /// + /// A class containing utility extensions + /// + public static class UtilityExtensions + { + /// + /// An extension method for supporting replacing one dictionary content with another one. + /// This is used to support resource tags. + /// + /// The destination dictionary in which the content will be replaced. + /// The source dictionary from which the content is copied from. + /// The destination dictionary that has been altered. + public static IDictionary ReplaceWith(this IDictionary dest, IDictionary src) + { + dest.Clear(); + foreach (var kv in src) + { + dest.Add(kv.Key, kv.Value); + } + + return dest; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ApiVersionsBaseTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ApiVersionsBaseTests.cs new file mode 100644 index 0000000000000..827ca1a28e02f --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ApiVersionsBaseTests.cs @@ -0,0 +1,216 @@ +using NUnit.Framework; +using System; + +namespace Azure.ResourceManager.Core.Tests +{ + public class ApiVersionsBaseTests + { + [TestCase] + public void VersionToString() + { + AzureResourceManagerClientOptions options = new AzureResourceManagerClientOptions(); + Assert.AreEqual("2020-06-01", options.FakeRpApiVersions().FakeResourceVersion); + } + + [TestCase] + public void EqualsOperator() + { + AzureResourceManagerClientOptions options1 = new AzureResourceManagerClientOptions(); + AzureResourceManagerClientOptions options2 = new AzureResourceManagerClientOptions(); + + Assert.IsTrue(options1.FakeRpApiVersions().FakeResourceVersion == options2.FakeRpApiVersions().FakeResourceVersion); + } + + [TestCase] + public void EqualsOperatorString() + { + AzureResourceManagerClientOptions options = new AzureResourceManagerClientOptions(); + + Assert.IsTrue(FakeResourceApiVersions.Default == options.FakeRpApiVersions().FakeResourceVersion); + } + + [TestCase] + public void EqualsOperatorStringFirstNull() + { + AzureResourceManagerClientOptions options = new AzureResourceManagerClientOptions(); + + Assert.IsFalse(null == options.FakeRpApiVersions().FakeResourceVersion); + } + + [TestCase] + public void EqualsOperatorStringSecondNull() + { + AzureResourceManagerClientOptions options = new AzureResourceManagerClientOptions(); + + Assert.IsFalse(options.FakeRpApiVersions().FakeResourceVersion == null); + } + + [TestCase] + public void EqualsOperatorStringBothNull() + { + FakeResourceApiVersions v1 = null; + + Assert.IsTrue(v1 == null); + } + + [TestCase] + public void NotEqualsOperator() + { + AzureResourceManagerClientOptions options1 = new AzureResourceManagerClientOptions(); + AzureResourceManagerClientOptions options2 = new AzureResourceManagerClientOptions(); + + Assert.IsFalse(options1.FakeRpApiVersions().FakeResourceVersion != options2.FakeRpApiVersions().FakeResourceVersion); + } + + [TestCase] + public void NotEqualsOperatorStringFirstNull() + { + AzureResourceManagerClientOptions options = new AzureResourceManagerClientOptions(); + + Assert.IsTrue(null != options.FakeRpApiVersions().FakeResourceVersion); + } + + [TestCase] + public void NotEqualsOperatorStringSecondNull() + { + AzureResourceManagerClientOptions options = new AzureResourceManagerClientOptions(); + + Assert.IsTrue(options.FakeRpApiVersions().FakeResourceVersion != null); + } + + [TestCase] + public void NotEqualsOperatorStringBothNull() + { + FakeResourceApiVersions v1 = null; + + Assert.IsFalse(v1 != null); + } + + [TestCase] + public void EqualsMethod() + { + AzureResourceManagerClientOptions options1 = new AzureResourceManagerClientOptions(); + AzureResourceManagerClientOptions options2 = new AzureResourceManagerClientOptions(); + + Assert.IsTrue(options1.FakeRpApiVersions().FakeResourceVersion.Equals(options2.FakeRpApiVersions().FakeResourceVersion)); + } + + [TestCase] + public void EqualsMethodVersionNull() + { + AzureResourceManagerClientOptions options = new AzureResourceManagerClientOptions(); + FakeResourceApiVersions version = null; + Assert.IsFalse(options.FakeRpApiVersions().FakeResourceVersion.Equals(version)); + } + + [TestCase] + public void EqualsMethodStringNull() + { + AzureResourceManagerClientOptions options = new AzureResourceManagerClientOptions(); + string version = null; + Assert.IsFalse(options.FakeRpApiVersions().FakeResourceVersion.Equals(version)); + } + + [TestCase] + public void EqualsMethodAsObject() + { + AzureResourceManagerClientOptions options1 = new AzureResourceManagerClientOptions(); + AzureResourceManagerClientOptions options2 = new AzureResourceManagerClientOptions(); + + object obj = options2.FakeRpApiVersions().FakeResourceVersion; + Assert.IsTrue(options1.FakeRpApiVersions().FakeResourceVersion.Equals(obj)); + } + + [TestCase] + public void EqualsMethodAsObjectThatIsString() + { + AzureResourceManagerClientOptions options1 = new AzureResourceManagerClientOptions(); + AzureResourceManagerClientOptions options2 = new AzureResourceManagerClientOptions(); + + object obj = options2.FakeRpApiVersions().FakeResourceVersion.ToString(); + Assert.IsTrue(options1.FakeRpApiVersions().FakeResourceVersion.Equals(obj)); + } + + [TestCase] + public void EqualsMethodAsObjectThatIsInt() + { + AzureResourceManagerClientOptions options = new AzureResourceManagerClientOptions(); + + object obj = 1; + Assert.IsFalse(options.FakeRpApiVersions().FakeResourceVersion.Equals(obj)); + } + + [TestCase] + public void ImplicitToString() + { + AzureResourceManagerClientOptions options = new AzureResourceManagerClientOptions(); + options.FakeRpApiVersions().FakeResourceVersion = FakeResourceApiVersions.V2019_12_01; + string version = options.FakeRpApiVersions().FakeResourceVersion; + Assert.IsTrue(version == "2019-12-01"); + } + + [TestCase(-1, "2019-12-01", "2020-06-01")] + [TestCase(0, "2019-12-01", "2019-12-01")] + [TestCase(1, "2020-06-01", "2019-12-01")] + [TestCase(1, "2020-06-01", null)] + public void CompareToMethodString(int expected, string version1, string version2) + { + FakeResourceApiVersions v1 = version1 == "2019-12-01" ? FakeResourceApiVersions.V2019_12_01 : FakeResourceApiVersions.V2020_06_01; + Assert.AreEqual(expected, v1.CompareTo(version2)); + } + + private FakeResourceApiVersions ConvertFromString(string version) + { + switch(version) + { + case "2019-12-01": + return FakeResourceApiVersions.V2019_12_01; + case "2020-06-01": + return FakeResourceApiVersions.V2020_06_01; + case "2019-12-01-preview": + return FakeResourceApiVersions.V2019_12_01_preview; + case "2019-12-01-preview-1": + return FakeResourceApiVersions.V2019_12_01_preview_1; + case "2019-12-01-foobar": + return FakeResourceApiVersions.V2019_12_01_foobar; + default: + throw new ArgumentException($"Version ({version}) was not valid"); + } + } + + [TestCase(-1, "2019-12-01", "2020-06-01")] + [TestCase(-1, "2019-12-01-preview", "2020-06-01")] + [TestCase(1, "2020-06-01", "2019-12-01-preview")] + [TestCase(0, "2019-12-01", "2019-12-01")] + [TestCase(-1, "2019-12-01-foobar", "2019-12-01-preview")] + [TestCase(1, "2019-12-01-preview", "2019-12-01-foobar")] + [TestCase(1, "2019-12-01-preview-1", "2019-12-01-preview")] + [TestCase(-1, "2019-12-01-preview", "2019-12-01-preview-1")] + [TestCase(0, "2019-12-01-preview", "2019-12-01-preview")] + [TestCase(-1, "2019-12-01-preview", "2019-12-01")] + [TestCase(1, "2019-12-01", "2019-12-01-preview")] + [TestCase(1, "2020-06-01", "2019-12-01")] + [TestCase(1, "2020-06-01", null)] + public void CompareToMethodVersionObject(int expected, string version1, string version2) + { + FakeResourceApiVersions v1 = ConvertFromString(version1); + FakeResourceApiVersions v2 = null; + if (version2 != null) + v2 = ConvertFromString(version2); + Assert.AreEqual(expected, v1.CompareTo(v2)); + } + + [TestCase] + public void ToStringTest() + { + Assert.AreEqual("2020-06-01", FakeResourceApiVersions.Default.ToString()); + } + + [TestCase] + public void GetHashCodeTest() + { + FakeResourceApiVersions version = FakeResourceApiVersions.Default; + Assert.AreEqual(version.ToString().GetHashCode(), version.GetHashCode()); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ArmClientOptionsTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ArmClientOptionsTests.cs new file mode 100644 index 0000000000000..7ce6a32f5a405 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ArmClientOptionsTests.cs @@ -0,0 +1,25 @@ +using NUnit.Framework; + +namespace Azure.ResourceManager.Core.Tests +{ + public class AzureResourceManagerClientOptionsTests + { + [TestCase] + public void VersionIsDefault() + { + AzureResourceManagerClientOptions options = new AzureResourceManagerClientOptions(); + Assert.AreEqual(FakeResourceApiVersions.Default, options.FakeRpApiVersions().FakeResourceVersion); + } + + [TestCase] + public void MultiClientSeparateVersions() + { + AzureResourceManagerClientOptions options1 = new AzureResourceManagerClientOptions(); + AzureResourceManagerClientOptions options2 = new AzureResourceManagerClientOptions(); + + options2.FakeRpApiVersions().FakeResourceVersion = FakeResourceApiVersions.V2019_12_01; + Assert.AreEqual(FakeResourceApiVersions.Default, options1.FakeRpApiVersions().FakeResourceVersion); + Assert.AreEqual(FakeResourceApiVersions.V2019_12_01, options2.FakeRpApiVersions().FakeResourceVersion); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ArmClientTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ArmClientTests.cs new file mode 100644 index 0000000000000..04b52e63ba373 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ArmClientTests.cs @@ -0,0 +1,15 @@ +using NUnit.Framework; + +namespace Azure.ResourceManager.Core.Tests +{ + public class ArmClientTests + { + [TestCase] + public void CreateResourceFromId() + { + //TODO: 4622 needs complete with a Mocked example to fill in this test + //public ArmResponse CreateResource(string subscription, string resourceGroup, string name, TResource model, azure_proto_core.Location location = default) + Assert.Ignore(); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/Azure.ResourceManager.Core.Tests.csproj b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/Azure.ResourceManager.Core.Tests.csproj new file mode 100644 index 0000000000000..b45d1b35adf6c --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/Azure.ResourceManager.Core.Tests.csproj @@ -0,0 +1,32 @@ + + + + $(DefineConstants);RESOURCES_RP + ; + + + SA1649;SA1633;SA1000;SA1028;SA1400;SA1508 + + + + + + + + + + + + Always + + + Always + + + Always + + + Always + + + diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/IdentityTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/IdentityTests.cs new file mode 100644 index 0000000000000..c21977993ee47 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/IdentityTests.cs @@ -0,0 +1,457 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using NUnit.Framework; + +namespace Azure.ResourceManager.Core.Tests +{ + public class IdentityTests + { + [TestCase] + public void CheckNoParamConstructor() + { + ResourceIdentity identity = new ResourceIdentity(); + Assert.IsNotNull(identity); + Assert.IsTrue(identity.UserAssignedIdentities.Count == 0); + Assert.IsNull(identity.SystemAssignedIdentity); + } + + [TestCase ("/subscriptions/6b085460-5f00-477e-ba44-1035046e9101/resourceGroups/tester/providers/Microsoft.Web/sites/autotest", false)] + [TestCase ("", true)] + [TestCase (" ", true)] + [TestCase (null, true)] + public void CheckUserTrueConstructor(string resourceID, bool invalidParameter) + { + var dict1 = new Dictionary(); + + if (invalidParameter) + { + if (resourceID is null) + Assert.Throws(() => { dict1[resourceID] = new UserAssignedIdentity(Guid.Empty, Guid.Empty); }); + else + Assert.Throws(() => { dict1[resourceID] = new UserAssignedIdentity(Guid.Empty, Guid.Empty); }); + } + else + { + dict1[resourceID] = new UserAssignedIdentity(Guid.Empty, Guid.Empty); + ResourceIdentity identity = new ResourceIdentity(dict1, true); + Assert.IsNotNull(identity); + Assert.IsNotNull(identity.UserAssignedIdentities); + Assert.IsTrue(identity.UserAssignedIdentities.Count == 1); + Assert.IsNotNull(identity.SystemAssignedIdentity); + Assert.IsNull(identity.SystemAssignedIdentity.TenantId); + Assert.IsNull(identity.SystemAssignedIdentity.PrincipalId); + } + } + + [TestCase ("/subscriptions/6b085460-5f00-477e-ba44-1035046e9101/resourceGroups/tester/providers/Microsoft.Web/sites/autotest", false)] + [TestCase("", true)] + [TestCase(" ", true)] + [TestCase(null, true)] + public void CheckUserFalseConstructor(string resourceID, bool invalidParameter) + { + var dict1 = new Dictionary(); + + if(invalidParameter) + { + if (resourceID is null) + Assert.Throws(() => { dict1[resourceID] = new UserAssignedIdentity(Guid.Empty, Guid.Empty); }); + else + Assert.Throws(() => { dict1[resourceID] = new UserAssignedIdentity(Guid.Empty, Guid.Empty); }); + } + else + { + dict1[resourceID] = new UserAssignedIdentity(Guid.Empty, Guid.Empty); + var system = new SystemAssignedIdentity(Guid.Empty, Guid.Empty); + ResourceIdentity identity = new ResourceIdentity(system, dict1); + Assert.IsNotNull(identity); + Assert.IsNotNull(identity.UserAssignedIdentities); + Assert.IsTrue(identity.UserAssignedIdentities.Count == 1); + Assert.IsNotNull(identity.SystemAssignedIdentity); + Assert.IsTrue(identity.SystemAssignedIdentity.TenantId.Equals(Guid.Empty)); + Assert.IsTrue(identity.SystemAssignedIdentity.PrincipalId.Equals(Guid.Empty)); + } + } + + [TestCase] + public void EqualsNullOtherTestFalse() + { + ResourceIdentity identity = new ResourceIdentity(); + ResourceIdentity other = null; + Assert.IsFalse(identity.Equals(other)); + } + + [TestCase] + public void EqualsNullOtherTest() + { + ResourceIdentity identity = new ResourceIdentity(); + ResourceIdentity other = new ResourceIdentity(); + Assert.IsTrue(identity.Equals(other)); + } + + [TestCase] + public void EqualsReferenceTestTrue() + { + var dict1 = new Dictionary(); + dict1["/subscriptions/6b085460-5vbg-477e-ba44-1035046e9101/resourceGroups/tester/providers/Microsoft.Web/sites/autotest"] = new UserAssignedIdentity(Guid.Empty, Guid.Empty); + var system = new SystemAssignedIdentity(Guid.Empty, Guid.Empty); + ResourceIdentity identity = new ResourceIdentity(system, dict1); + ResourceIdentity identity1 = identity; + Assert.IsTrue(identity.Equals(identity1)); + } + + [TestCase] + public void EqualsTestTrue() + { + var dict1 = new Dictionary(); + dict1["/subscriptions/6b085460-5f21-477e-ba44-1035046e9000/resourceGroups/tester/providers/Microsoft.Web/sites/autotest"] = new UserAssignedIdentity(Guid.Empty, Guid.Empty); + var system = new SystemAssignedIdentity(Guid.Empty, Guid.Empty); + ResourceIdentity identity = new ResourceIdentity(system, dict1); + var dict2 = new Dictionary(); + dict2["/subscriptions/6b085460-5f21-477e-ba44-1035046e9000/resourceGroups/tester/providers/Microsoft.Web/sites/autotest"] = new UserAssignedIdentity(Guid.Empty, Guid.Empty); + var system2 = new SystemAssignedIdentity(Guid.Empty, Guid.Empty); + ResourceIdentity identity1 = new ResourceIdentity(system2, dict2); + Assert.IsTrue(identity.Equals(identity1)); + } + + [TestCase] + public void EqualsTestFalse() + { + var dict1 = new Dictionary(); + dict1["/subscriptions/6b085460-5f21-477e-ba44-1035nbhs9101/resourceGroups/tester/providers/Microsoft.Web/sites/autotest"] = new UserAssignedIdentity(Guid.Empty, Guid.Empty); + var system = new SystemAssignedIdentity(Guid.Empty, Guid.Empty); + ResourceIdentity identity = new ResourceIdentity(system, dict1); + var dict2 = new Dictionary(); + dict2["/subscriptions/6b08dfsg-5f21-475e-ba44-1035046e9101/resourceGroups/tester/providers/Microsoft.Web/sites/autotest"] = new UserAssignedIdentity(Guid.Empty, Guid.Empty); + var system2 = new SystemAssignedIdentity(Guid.Empty, Guid.Empty); + ResourceIdentity identity1 = new ResourceIdentity(system2, dict2); + Assert.IsFalse(identity.Equals(identity1)); + } + + [TestCase] + public void EqualsTestFalseSameKey() + { + var dict1 = new Dictionary(); + dict1["/subscriptions/6b085460-5f21-477e-ba44-10ancd6e9101/resourceGroups/tester/providers/Microsoft.Web/sites/autotest"] = new UserAssignedIdentity(Guid.Empty, Guid.Empty); + var system = new SystemAssignedIdentity(Guid.Empty, Guid.Empty); + ResourceIdentity identity = new ResourceIdentity(system, dict1); + var dict2 = new Dictionary(); + dict2["/subscriptions/6b085460-5f21-477e-ba44-10ancd6e9101/resourceGroups/tester/providers/Microsoft.Web/sites/autotest"] = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), Guid.Empty); + var system2 = new SystemAssignedIdentity(Guid.Empty, Guid.Empty); + ResourceIdentity identity1 = new ResourceIdentity(system2, dict2); + Assert.IsFalse(identity.Equals(identity1)); + } + + [TestCase] + public void TestDeserializerInvalidDefaultJson() + { + JsonElement invalid = default(JsonElement); + Assert.Throws(delegate { ResourceIdentity.Deserialize(invalid); }); + } + + public JsonProperty DeserializerHelper(string filename) + { + var json = File.ReadAllText(Path.Combine(TestContext.CurrentContext.TestDirectory, "TestAssets", "Identity", filename)); + JsonDocument document = JsonDocument.Parse(json); + JsonElement rootElement = document.RootElement; + return rootElement.EnumerateObject().First(); + } + + [TestCase] + public void TestDeserializerInvalidNullType() + { + var identityJsonProperty = DeserializerHelper("InvalidTypeIsNull.json"); + Assert.Throws(delegate { ResourceIdentity.Deserialize(identityJsonProperty.Value); }); + } + + [TestCase] + public void TestDeserializerValidSystemAndUserAssigned() + { + var identityJsonProperty = DeserializerHelper("SystemAndUserAssignedValid.json"); + ResourceIdentity back = ResourceIdentity.Deserialize(identityJsonProperty.Value); + Assert.IsTrue("22fdaec1-8b9f-49dc-bd72-ddaf8f215577".Equals(back.SystemAssignedIdentity.PrincipalId.ToString())); + Assert.IsTrue("72f988af-86f1-41af-91ab-2d7cd011db47".Equals(back.SystemAssignedIdentity.TenantId.ToString())); + var user = back.UserAssignedIdentities; + Assert.AreEqual("/subscriptions/db1ab6f0-4769-4aa7-930e-01e2ef9c123c/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity", user.Keys.First().ToString()); + Assert.AreEqual("9a9eaa6a-b49c-4c63-afb5-3b72e3e65422", user.Values.First().ClientId.ToString()); + Assert.AreEqual("77563a98-c9d9-407b-a7af-592d21fa2153", user.Values.First().PrincipalId.ToString()); + } + + [TestCase] + public void TestDeserializerInvalidType() + { + var identityJsonProperty = DeserializerHelper("InvalidType.json"); + ResourceIdentity back = ResourceIdentity.Deserialize(identityJsonProperty.Value); + var user = back.UserAssignedIdentities; + Assert.AreEqual("/subscriptions/db1ab6f0-4769-tgds-930e-01e2ef9c123c/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity", user.Keys.First().ToString()); + Assert.AreEqual("9a2eaa6a-b49c-4a63-afb5-3b72e3e65422", user.Values.First().ClientId.ToString()); + Assert.AreEqual("77563a98-c9d9-4f7b-a7af-592d21fa2153", user.Values.First().PrincipalId.ToString()); + } + + [TestCase] + public void TestDeserializerValidInnerExtraField() + { + var identityJsonProperty = DeserializerHelper("SystemAndUserAssignedInnerExtraField.json"); + ResourceIdentity back = ResourceIdentity.Deserialize(identityJsonProperty.Value); + Assert.IsTrue("22fddec1-8b9f-49dc-bd72-ddaf8f215577".Equals(back.SystemAssignedIdentity.PrincipalId.ToString())); + Assert.IsTrue("72f988bf-86f1-41af-91ab-2d7cd011db47".Equals(back.SystemAssignedIdentity.TenantId.ToString())); + var user = back.UserAssignedIdentities; + Assert.AreEqual("/subscriptions/db1ab6f0-4769-4b27-9dde-01e2ef9c123c/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity", user.Keys.First().ToString()); + Assert.AreEqual("9a9eaa6a-b49c-4c63-afb5-3b72e3e65422", user.Values.First().ClientId.ToString()); + Assert.AreEqual("77563a98-c9d9-407b-a7af-592d21fa2153", user.Values.First().PrincipalId.ToString()); + } + + [TestCase] + public void TestDeserializerValidMiddleExtraField() + { + var identityJsonProperty = DeserializerHelper("SystemAndUserAssignedMiddleExtraField.json"); + ResourceIdentity back = ResourceIdentity.Deserialize(identityJsonProperty.Value); + Assert.IsTrue("22fddec1-8b9f-49dc-bd72-ddaf8f215577".Equals(back.SystemAssignedIdentity.PrincipalId.ToString())); + Assert.IsTrue("72f988bf-86f1-41af-91ab-2d7cd011db47".Equals(back.SystemAssignedIdentity.TenantId.ToString())); + var user = back.UserAssignedIdentities; + Assert.AreEqual("/subscriptions/db1ab6f0-4769-4b27-9dde-01e2ef9c123c/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity", user.Keys.First().ToString()); + Assert.AreEqual("9a9eaa6a-b49c-4c63-afb5-3b72e3e65422", user.Values.First().ClientId.ToString()); + Assert.AreEqual("77563a98-c9d9-407b-a7af-592d21fa2153", user.Values.First().PrincipalId.ToString()); + } + + [TestCase] + public void TestDeserializerValidOuterExtraField() + { + var json = File.ReadAllText(Path.Combine(TestContext.CurrentContext.TestDirectory, "TestAssets", "Identity", "SystemAndUserAssignedOuterExtraField.json")); + JsonDocument document = JsonDocument.Parse(json); + JsonElement rootElement = document.RootElement; + var identityJsonProperty = rootElement.EnumerateObject().ElementAt(1); + ResourceIdentity back = ResourceIdentity.Deserialize(identityJsonProperty.Value); + Assert.IsTrue("22fddec1-8b9f-49dc-bd72-ddaf8f215577".Equals(back.SystemAssignedIdentity.PrincipalId.ToString())); + Assert.IsTrue("72f988bf-86f1-41af-91ab-2d7cd011db47".Equals(back.SystemAssignedIdentity.TenantId.ToString())); + var user = back.UserAssignedIdentities; + Assert.AreEqual("/subscriptions/db1ab6f0-3466-4b27-930e-01e2ef9c123c/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity", user.Keys.First().ToString()); + Assert.AreEqual("9a2eaa6b-b49c-4c63-afb5-3b72e3e65422", user.Values.First().ClientId.ToString()); + Assert.AreEqual("7756fa98-c9d9-477b-a7af-592d21fa2153", user.Values.First().PrincipalId.ToString()); + } + + [TestCase] + public void TestDeserializerValidSystemAndMultUser() + { + var identityJsonProperty = DeserializerHelper("SystemAndUserAssignedValidMultIdentities.json"); + ResourceIdentity back = ResourceIdentity.Deserialize(identityJsonProperty.Value); + Assert.IsTrue("22fddec1-8b9f-49dc-bd72-ddaf8f215570".Equals(back.SystemAssignedIdentity.PrincipalId.ToString())); + Assert.IsTrue("72f988bf-86f1-41af-91ab-2d7cd011db40".Equals(back.SystemAssignedIdentity.TenantId.ToString())); + var user = back.UserAssignedIdentities; + Assert.AreEqual("/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123z/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity0", user.Keys.First().ToString()); + Assert.AreEqual("9a2eaa6a-b49c-4c63-afb5-3b72e3e65422", user.Values.First().ClientId.ToString()); + Assert.AreEqual("77563a98-c9d9-477b-a7af-592d21fa2153", user.Values.First().PrincipalId.ToString()); + Assert.AreEqual("/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9cfrgh/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity1", user.Keys.ElementAt(1).ToString()); + Assert.AreEqual("9a2eaa6a-b49c-4c63-afb5-3b72e3c65420", user.Values.ElementAt(1).ClientId.ToString()); + Assert.AreEqual("77563a98-c9d9-477b-a7af-592d2bfa2150", user.Values.ElementAt(1).PrincipalId.ToString()); + } + + [TestCase] + public void TestDeserializerValidSystemAssigned() + { + var identityJsonProperty = DeserializerHelper("SystemAssigned.json"); + ResourceIdentity back = ResourceIdentity.Deserialize(identityJsonProperty.Value); + Assert.IsTrue("22fddec1-8b9f-49dc-bd72-ddaf8f215577".Equals(back.SystemAssignedIdentity.PrincipalId.ToString())); + Assert.IsTrue("72f988bf-86f1-41af-91ab-2d7cd011db47".Equals(back.SystemAssignedIdentity.TenantId.ToString())); + Assert.IsTrue(back.UserAssignedIdentities.Count == 0); + } + + [TestCase] + public void TestDeserializerValidUserAssigned() + { + var identityJsonProperty = DeserializerHelper("UserAssigned.json"); + ResourceIdentity back = ResourceIdentity.Deserialize(identityJsonProperty.Value); + Assert.IsNull(back.SystemAssignedIdentity); + var user = back.UserAssignedIdentities; + Assert.AreEqual("/subscriptions/db1ab6f0-4769-4b2e-930e-01e2ef9c123c/resourceGroups/tester-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity", user.Keys.First().ToString()); + Assert.AreEqual("9a2eaa6a-b49c-4c63-afb5-3b72e3e65422", user.Values.First().ClientId.ToString()); + Assert.AreEqual("77563a98-c9d9-477b-a7af-592d21fa2153", user.Values.First().PrincipalId.ToString()); + } + + [TestCase] + public void TestSerializerValidSystemAndUser() + { + SystemAssignedIdentity systemAssignedIdentity = new SystemAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + UserAssignedIdentity userAssignedIdentity = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + var dict1 = new Dictionary(); + dict1["/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport"] = userAssignedIdentity; + ResourceIdentity identity = new ResourceIdentity(systemAssignedIdentity, dict1); + string system = "\"principalId\":\"de29bab1-49e1-4705-819b-4dfddceaaa98\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\""; + string user = "{\"clientId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\",\"principalId\":\"de29bab1-49e1-4705-819b-4dfddceaaa98\"}"; + string expected = "{\"identity\":{" + + system + "," + + "\"kind\":\"SystemAssigned, UserAssigned\"," + + "\"userAssignedIdentities\":" + + "{" + "\"/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport\":" + + user + "}}}"; + string actual = ""; + using (Stream stream = new MemoryStream()) + { + using (StreamReader streamReader = new StreamReader(stream)) + { + var writer = new Utf8JsonWriter(stream); + ResourceIdentity.Serialize(writer, identity); + stream.Seek(0, SeekOrigin.Begin); + actual = streamReader.ReadToEnd(); + } + } + Assert.AreEqual(expected, actual); + } + + [TestCase] + public void TestSerializerValidSystemAndMultUser() + { + SystemAssignedIdentity systemAssignedIdentity = new SystemAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + UserAssignedIdentity userAssignedIdentity1 = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + UserAssignedIdentity userAssignedIdentity2 = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011cb47"), new Guid("de29bab1-49e1-4705-819b-4dfddcebaa98")); + var dict1 = new Dictionary(); + dict1["/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport1"] = userAssignedIdentity1; + dict1["/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport2"] = userAssignedIdentity2; + ResourceIdentity identity = new ResourceIdentity(systemAssignedIdentity, dict1); + string system = "\"principalId\":\"de29bab1-49e1-4705-819b-4dfddceaaa98\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\""; + string user = "{\"clientId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\",\"principalId\":\"de29bab1-49e1-4705-819b-4dfddceaaa98\"}"; + string user2 = "{\"clientId\":\"72f988bf-86f1-41af-91ab-2d7cd011cb47\",\"principalId\":\"de29bab1-49e1-4705-819b-4dfddcebaa98\"}"; + string expected = "{\"identity\":{" + + system + "," + + "\"kind\":\"SystemAssigned, UserAssigned\"," + + "\"userAssignedIdentities\":" + + "{" + "\"/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport1\":" + + user + "," + + "\"/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport2\":" + + user2 + "}}}"; + string actual = ""; + using (Stream stream = new MemoryStream()) + { + using (StreamReader streamReader = new StreamReader(stream)) + { + var writer = new Utf8JsonWriter(stream); + ResourceIdentity.Serialize(writer, identity); + stream.Seek(0, SeekOrigin.Begin); + actual = streamReader.ReadToEnd(); + } + } + Assert.AreEqual(expected, actual); + } + + [TestCase] + public void TestSerializerValidSystemOnly() + { + SystemAssignedIdentity systemAssignedIdentity = new SystemAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + ResourceIdentity identity = new ResourceIdentity(systemAssignedIdentity, null); + string system = "\"principalId\":\"de29bab1-49e1-4705-819b-4dfddceaaa98\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\""; + string expected = "{\"identity\":{" + + system + "," + + "\"kind\":\"SystemAssigned\"}}"; + string actual = ""; + using (Stream stream = new MemoryStream()) + { + using (StreamReader streamReader = new StreamReader(stream)) + { + var writer = new Utf8JsonWriter(stream); + ResourceIdentity.Serialize(writer, identity); + stream.Seek(0, SeekOrigin.Begin); + actual = streamReader.ReadToEnd(); + } + } + Assert.AreEqual(expected, actual); + } + + [TestCase] + public void TestSerializerValidUserEmptySystem() + { + UserAssignedIdentity userAssignedIdentity = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + var dict1 = new Dictionary(); + dict1["/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport"] = userAssignedIdentity; + ResourceIdentity identity = new ResourceIdentity(dict1, true); + string system = "\"principalId\":\"null\",\"tenantId\":\"null\""; + string user = "{\"clientId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\",\"principalId\":\"de29bab1-49e1-4705-819b-4dfddceaaa98\"}"; + string expected = "{\"identity\":{" + + system + "," + + "\"kind\":\"SystemAssigned, UserAssigned\"," + + "\"userAssignedIdentities\":" + + "{" + "\"/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport\":" + + user + "}}}"; + string actual = ""; + using (Stream stream = new MemoryStream()) + { + using (StreamReader streamReader = new StreamReader(stream)) + { + var writer = new Utf8JsonWriter(stream); + ResourceIdentity.Serialize(writer, identity); + stream.Seek(0, SeekOrigin.Begin); + actual = streamReader.ReadToEnd(); + } + } + Assert.AreEqual(expected, actual); + } + + [TestCase] + public void TestSerializerValidUserNullSystem() + { + UserAssignedIdentity userAssignedIdentity = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + var dict1 = new Dictionary(); + dict1["/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport"] = userAssignedIdentity; + ResourceIdentity identity = new ResourceIdentity(dict1, false); + string user = "{\"clientId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\",\"principalId\":\"de29bab1-49e1-4705-819b-4dfddceaaa98\"}"; + string expected = "{\"identity\":{" + + "\"kind\":\"UserAssigned\"," + + "\"userAssignedIdentities\":" + + "{" + "\"/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport\":" + + user + "}}}"; + string actual = ""; + using (Stream stream = new MemoryStream()) + { + using (StreamReader streamReader = new StreamReader(stream)) + { + var writer = new Utf8JsonWriter(stream); + ResourceIdentity.Serialize(writer, identity); + stream.Seek(0, SeekOrigin.Begin); + actual = streamReader.ReadToEnd(); + } + } + Assert.AreEqual(expected, actual); + } + + [TestCase] + public void TestSerializerValidIdentityNull() + { + ResourceIdentity identity = new ResourceIdentity(); + string expected = "{\"identity\":\"null\"}"; + string actual = ""; + using (Stream stream = new MemoryStream()) + { + using (StreamReader streamReader = new StreamReader(stream)) + { + var writer = new Utf8JsonWriter(stream); + ResourceIdentity.Serialize(writer, identity); + stream.Seek(0, SeekOrigin.Begin); + actual = streamReader.ReadToEnd(); + } + } + Assert.AreEqual(expected, actual); + } + + [TestCase] + public void TestSerializerInvalidNullWriter() + { + ResourceIdentity identity = new ResourceIdentity(); + using (Stream stream = new MemoryStream()) + { + Assert.Throws(delegate { ResourceIdentity.Serialize(null, identity); }); + } + } + + [TestCase] + public void TestSerializerInvalidNullIdentity() + { + ResourceIdentity identity = null; + using (Stream stream = new MemoryStream()) + { + var writer = new Utf8JsonWriter(stream); + Assert.Throws(delegate { ResourceIdentity.Serialize(writer, identity); }); + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/LocationTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/LocationTests.cs new file mode 100644 index 0000000000000..84d6f686573fc --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/LocationTests.cs @@ -0,0 +1,225 @@ +using NUnit.Framework; +using System; + +namespace Azure.ResourceManager.Core.Tests +{ + public class LocationTests + { + [TestCase("westus", "westus", "west-us", "West US")] + [TestCase("west-us", "westus", "west-us", "West US")] + [TestCase("West US", "westus", "west-us", "West US")] + [TestCase("privatecloud", "privatecloud", "privatecloud", "privatecloud")] + [TestCase("private-cloud", "privatecloud", "private-cloud", "Private Cloud")] + [TestCase("Private Cloud", "privatecloud", "private-cloud", "Private Cloud")] + [TestCase("@$!()*&", "@$!()*&", "@$!()*&", "@$!()*&")] + [TestCase("W3$t U$ 2", "W3$t U$ 2", "W3$t U$ 2", "W3$t U$ 2")] + [TestCase("", "", "", "")] + [TestCase(" ", " ", " ", " ")] + [TestCase(null, null, null, null)] + public void CanCreateLocation(string name, string expectedName, string expectedCanonincalName, string expectedDisplayName) + { + LocationData location = name; + if (name == null) + { + Assert.IsNull(location); + } + else + { + Assert.AreEqual(expectedName, location.Name); + Assert.AreEqual(expectedCanonincalName, location.CanonicalName); + Assert.AreEqual(expectedDisplayName, location.DisplayName); + } + } + + [TestCase("USNorth")] + [TestCase("Us West 12")] + [TestCase("Us West 1a")] + [TestCase(" Us West 1")] + [TestCase("Us West 1 ")] + [TestCase("*Us West")] + [TestCase("Us *West")] + [TestCase("Us West *")] + [TestCase("")] + public void NameTypeIsName(string location) + { + LocationData loc = location; + Assert.IsTrue(loc.Name == loc.DisplayName && loc.Name == loc.CanonicalName); + } + + [TestCase("us-west")] + [TestCase("us-west-west")] + [TestCase("us-west-2")] + [TestCase("us-west-west-2")] + [TestCase("a-b-c-5")] + public void NameTypeIsCanonical(string location) + { + LocationData loc = location; + Assert.IsTrue(loc.CanonicalName == location && loc.Name != location && loc.DisplayName != location); + } + + [TestCase("Us West")] + [TestCase("US West")] + [TestCase("USa West")] + [TestCase("West US")] + [TestCase("West USa")] + [TestCase("Us West West")] + [TestCase("Us West 2")] + [TestCase("Us West West 2")] + [TestCase("A B C 5")] + public void NameTypeIsDisplayName(string location) + { + LocationData loc = location; + Assert.IsTrue(loc.DisplayName == location && loc.Name != location && loc.CanonicalName != location); + } + + [TestCase(true, "West Us", "West Us")] + [TestCase(true, "West Us", "WestUs")] + [TestCase(true, "!#()@(#@", "!#()@(#@")] + [TestCase(true, "W3$t U$", "W3$t U$")] + [TestCase(true, "1234567890", "1234567890")] + [TestCase(false, "West Us", "WestUs2")] + [TestCase(false, "West US", "")] + [TestCase(false, "West US", "!#()@(#@")] + [TestCase(false, "West US", "W3$t U$")] + [TestCase(false, "West US", null)] + public void EqualsToObject(bool expected, string left, string right) + { + LocationData loc1 = left; + LocationData loc2 = right; + Assert.AreEqual(expected, loc1.Equals(loc2)); + + if (expected) + { + Assert.AreEqual(0, loc1.CompareTo(loc2)); + } + else + { + Assert.AreNotEqual(0, loc1.CompareTo(loc2)); + } + } + + [TestCase(true, "West Us", "West Us")] + [TestCase(true, "West Us", "WestUs")] + [TestCase(true, "!#()@(#@", "!#()@(#@")] + [TestCase(true, "W3$t U$", "W3$t U$")] + [TestCase(true, "1234567890", "1234567890")] + [TestCase(false, "West Us", "WestUs2")] + [TestCase(false, "West Us", "")] + [TestCase(false, "West Us", "!#()@(#@")] + [TestCase(false, "West Us", "W3$t U$")] + [TestCase(false, "West Us", null)] + public void EqualsToString(bool expected, string left, string right) + { + LocationData location = left; + Assert.AreEqual(expected, location.Equals(right)); + + if (expected) + { + Assert.AreEqual(0, location.CompareTo(right)); + } + else + { + Assert.AreNotEqual(0, location.CompareTo(right)); + } + } + + [TestCase("", "")] + [TestCase("West US", "West US")] + [TestCase("west-us", "West US")] + [TestCase("westus2", "West US 2")] + [TestCase("private-cloud", "Private Cloud")] + public void CanParseToString(string name, string expected) + { + LocationData location1 = name; + Assert.AreEqual(expected, location1.ToString()); + } + + [TestCase("West US", "West US", 0)] + [TestCase("West US", "west-us", 0)] + [TestCase("West US", "westus", 0)] + [TestCase("Central Europe", "Central Europe", 0)] + [TestCase("Central Europe", "central-europe", 0)] + [TestCase("Central Europe", "centraleurope", 0)] + [TestCase("South US", "East US", 1)] + [TestCase("South US", "east-us", 1)] + [TestCase("South US", "West US", -1)] + [TestCase("South US", "west-us", -1)] + [TestCase("South US", null, 1)] + public void CompareToObject(string left, string right, int expected) + { + LocationData location1 = left; + LocationData location2 = right; + Assert.AreEqual(expected, location1.CompareTo(location2)); + if (right != null) + { + Assert.AreEqual(expected * -1, location2.CompareTo(location1)); + } + } + + [TestCase("West US", "West US", 0)] + [TestCase("West US", "west-us", 0)] + [TestCase("West US", "westus", 0)] + [TestCase("Central Europe", "Central Europe", 0)] + [TestCase("Central Europe", "central-europe", 0)] + [TestCase("Central Europe", "centraleurope", 0)] + [TestCase("South US", "East US", 1)] + [TestCase("South US", "east-us", 1)] + [TestCase("South US", "West US", -1)] + [TestCase("South US", "west-us", -1)] + [TestCase("South US", null, 1)] + public void CompareToString(string left, string right, int expected) + { + LocationData location1 = left; + Assert.AreEqual(expected, location1.CompareTo(right)); + if (right != null) + { + location1 = right; + Assert.AreEqual(expected * -1, location1.CompareTo(left)); + } + } + + [TestCase("West US", "West US")] + [TestCase("west-us", "West US")] + [TestCase("westus", "West US")] + [TestCase("Private Cloud", "Private Cloud")] + [TestCase("private-cloud", "Private Cloud")] + [TestCase("privatecloud", "privatecloud")] + [TestCase("1$S#@$%^", "1$S#@$%^")] + [TestCase("", "")] + [TestCase(" ", " ")] + [TestCase(null, null)] + public void CanCastLocationToString(string name, string expected) + { + LocationData location = name; + string strLocation = location; + Assert.AreEqual(expected, strLocation); + } + + [TestCase ("West US", "West US")] + [TestCase ("west-us", "West US")] + [TestCase ("westus", "West US")] + [TestCase ("Private Cloud", "Private Cloud")] + [TestCase ("private-cloud", "Private Cloud")] + [TestCase ("privatecloud", "privatecloud")] + [TestCase ("1$S#@$%^", "1$S#@$%^")] + [TestCase ("","")] + [TestCase (" ", " ")] + [TestCase (null,null)] + public void CanCastStringToLocation(string name, string expected) + { + LocationData location1 = name; + if (name == null) + Assert.Throws(()=> { string x = location1.DisplayName; }); + else + Assert.AreEqual(expected, location1.DisplayName); + } + + [Test] + public void CanAccessDefaultLocation() + { + Assert.IsNotNull(LocationData.Default); + LocationData location = LocationData.Default; + Assert.IsTrue(location.Equals(LocationData.Default)); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/PlanTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/PlanTests.cs new file mode 100644 index 0000000000000..0eea99ed7984b --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/PlanTests.cs @@ -0,0 +1,232 @@ +using NUnit.Framework; + +namespace Azure.ResourceManager.Core.Tests +{ + class PlanTests + { + [TestCase(0, "name", "name")] + [TestCase(0, "Name", "name")] + [TestCase(0, null, null)] + [TestCase(1, "name", null)] + [TestCase(-1, null, "name")] + [TestCase(0, "${?/>._`", "${?/>._`")] + [TestCase(1, "${?/>._`", "")] + public void CompareToName(int expected, string name1, string name2) + { + Plan plan1 = new Plan(name1, null, null, null, null); + Plan plan2 = new Plan(name2, null, null, null, null); + Assert.AreEqual(expected, plan1.CompareTo(plan2)); + } + + [TestCase(0, "product", "product")] + [TestCase(0, "Product", "product")] + [TestCase(0, null, null)] + [TestCase(1, "product", null)] + [TestCase(-1, null, "product")] + [TestCase(0, "${?/>._`", "${?/>._`")] + [TestCase(1, "${?/>._`", "")] + public void CompareToProduct(int expected, string product1, string product2) + { + Plan plan1 = new Plan(null, null, product1, null, null); + Plan plan2 = new Plan(null, null, product2, null, null); + Assert.AreEqual(expected, plan1.CompareTo(plan2)); + } + + [TestCase(0, "promotionCode", "promotionCode")] + [TestCase(0, "PromotionCode", "promotionCode")] + [TestCase(0, null, null)] + [TestCase(1, "promotionCode", null)] + [TestCase(-1, null, "promotionCode")] + [TestCase(0, "${?/>._`", "${?/>._`")] + [TestCase(1, "${?/>._`", "")] + public void CompareToPromotionCode(int expected, string promotionCode1, string promotionCode2) + { + Plan plan1 = new Plan(null, null, null, promotionCode1, null); + Plan plan2 = new Plan(null, null, null, promotionCode2, null); + Assert.AreEqual(expected, plan1.CompareTo(plan2)); + } + + [TestCase(0, "publisher", "publisher")] + [TestCase(0, "Publisher", "publisher")] + [TestCase(0, null, null)] + [TestCase(1, "publisher", null)] + [TestCase(-1, null, "publisher")] + [TestCase(0, "${?/>._`", "${?/>._`")] + [TestCase(1, "${?/>._`", "")] + public void CompareToPublisher(int expected, string publisher1, string publisher2) + { + Plan plan1 = new Plan(null, publisher1, null, null, null); + Plan plan2 = new Plan(null, publisher2, null, null, null); + Assert.AreEqual(expected, plan1.CompareTo(plan2)); + } + + [TestCase(0, "version", "version")] + [TestCase(0, "Version", "version")] + [TestCase(0, null, null)] + [TestCase(1, "version", null)] + [TestCase(-1, null, "version")] + [TestCase(0, "${?/>._`", "${?/>._`")] + [TestCase(1, "${?/>._`", "")] + public void CompareToVersion(int expected, string version1, string version2) + { + Plan plan1 = new Plan(null, null, null, null, version1); + Plan plan2 = new Plan(null, null, null, null, version2); + Assert.AreEqual(expected, plan1.CompareTo(plan2)); + } + + [Test] + public void CompareToNullPlan() + { + Plan plan1 = new Plan(null, null, null, null, null); + Plan plan2 = null; + Assert.AreEqual(1, plan1.CompareTo(plan2)); + } + + [Test] + public void CompareToSamePlans() + { + Plan plan1 = new Plan(null, null, null, null, null); + Plan plan2 = plan1; + Assert.AreEqual(0, plan1.CompareTo(plan2)); + } + + [TestCase(1, "Nameb", "namea", "versiona", "Versionb")] + [TestCase(1, "Nameb", "namea", "versiona", "versiona")] + [TestCase(-1, "namea", "Nameb", "Versionb", "versiona")] + public void CompareToMore(int expected, string name1, string name2, string version1, string version2) + { + Plan plan1 = new Plan(name1, null, null, null, version1); + Plan plan2 = new Plan(name2, null, null, null, version2); + Assert.AreEqual(expected, plan1.CompareTo(plan2)); + } + + [TestCase(true, "name", "name")] + [TestCase(true, "Name", "name")] + [TestCase(true, null, null)] + [TestCase(false, "name", null)] + [TestCase(false, null, "name")] + [TestCase(true, "${?/>._`", "${?/>._`")] + [TestCase(false, "${?/>._`", "")] + public void EqualsToName(bool expected, string name1, string name2) + { + Plan plan1 = new Plan(name1, null, null, null, null); + Plan plan2 = new Plan(name2, null, null, null, null); + if (expected) + { + Assert.IsTrue(plan1.Equals(plan2)); + } + else + { + Assert.IsFalse(plan1.Equals(plan2)); + } + } + + [TestCase(true, "product", "product")] + [TestCase(true, "Product", "product")] + [TestCase(true, null, null)] + [TestCase(false, "product", null)] + [TestCase(false, null, "product")] + [TestCase(true, "${?/>._`", "${?/>._`")] + [TestCase(false, "${?/>._`", "")] + public void EqualsToProduct(bool expected, string product1, string product2) + { + Plan plan1 = new Plan(null, null, product1, null, null); + Plan plan2 = new Plan(null, null, product2, null, null); + if (expected) + { + Assert.IsTrue(plan1.Equals(plan2)); + } + else + { + Assert.IsFalse(plan1.Equals(plan2)); + } + } + + [TestCase(true, "promotionCode", "promotionCode")] + [TestCase(true, "PromotionCode", "promotionCode")] + [TestCase(true, null, null)] + [TestCase(false, "promotionCode", null)] + [TestCase(false, null, "promotionCode")] + [TestCase(true, "${?/>._`", "${?/>._`")] + [TestCase(false, "${?/>._`", "")] + public void EqualsToPromotionCode(bool expected, string promotionCode1, string promotionCode2) + { + Plan plan1 = new Plan(null, null, null, promotionCode1, null); + Plan plan2 = new Plan(null, null, null, promotionCode2, null); + if (expected) + { + Assert.IsTrue(plan1.Equals(plan2)); + } + else + { + Assert.IsFalse(plan1.Equals(plan2)); + } + } + + [TestCase(true, "publisher", "publisher")] + [TestCase(true, "Publisher", "publisher")] + [TestCase(true, null, null)] + [TestCase(false, "publisher", null)] + [TestCase(false, null, "publisher")] + [TestCase(true, "${?/>._`", "${?/>._`")] + [TestCase(false, "${?/>._`", "")] + public void EqualsToPublisher(bool expected, string publisher1, string publisher2) + { + Plan plan1 = new Plan(null, publisher1, null, null, null); + Plan plan2 = new Plan(null, publisher2, null, null, null); + if (expected) + { + Assert.IsTrue(plan1.Equals(plan2)); + } + else + { + Assert.IsFalse(plan1.Equals(plan2)); + } + } + + [TestCase(true, "version", "version")] + [TestCase(true, "Version", "version")] + [TestCase(true, null, null)] + [TestCase(false, "version", null)] + [TestCase(false, null, "version")] + [TestCase(true, "${?/>._`", "${?/>._`")] + [TestCase(false, "${?/>._`", "")] + public void EqualsToVersion(bool expected, string version1, string version2) + { + Plan plan1 = new Plan(null, null, null, null, version1); + Plan plan2 = new Plan(null, null, null, null, version2); + if (expected) + { + Assert.IsTrue(plan1.Equals(plan2)); + } + else + { + Assert.IsFalse(plan1.Equals(plan2)); + } + } + + [Test] + public void EqualsToNullPlan() + { + Plan plan1 = new Plan(null, null, null, null, null); + Plan plan2 = null; + Assert.IsFalse(plan1.Equals(plan2)); + } + + [Test] + public void EqualsToObject() + { + Plan plan1 = new Plan(null, null, null, null, null); + object plan2 = "random"; + Assert.IsFalse(plan1.Equals(plan2)); + } + + [Test] + public void EqualsToSamePlans() + { + Plan plan1 = new Plan(null, null, null, null, null); + Plan plan2 = plan1; + Assert.IsTrue(plan1.Equals(plan2)); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/README.MD b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/README.MD new file mode 100644 index 0000000000000..36d54fd1c2eed --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/README.MD @@ -0,0 +1,16 @@ +# azure-proto-core-test + +To run test: ```dotnet test``` + +To run test with code coverage and auto generate an html report: ```dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura``` + +Coverage report will be placed in your path relative to azure-proto-core-test in```/coverage``` in html format for viewing + +Reports can also be viewed VS or VsCode with the proper viewer plugin + +A terse report will also be displayed on the command line when running. + + +## run test with single file or test + +To run test with code coverage and auto generate an html report with just a single test: ```dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura --filter ``` \ No newline at end of file diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/Resource/TestResource.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/Resource/TestResource.cs new file mode 100644 index 0000000000000..8bb221bae37e7 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/Resource/TestResource.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Azure.ResourceManager.Core.Tests +{ + public class TestResource : Resource + { + public TestResource(string id) + { + Id = id; + } + + public override ResourceIdentifier Id { get; protected set; } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceGroupOperationsTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceGroupOperationsTests.cs new file mode 100644 index 0000000000000..14b573e26a5f8 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceGroupOperationsTests.cs @@ -0,0 +1,23 @@ +using NUnit.Framework; + +namespace Azure.ResourceManager.Core.Tests +{ + public class ResourceGroupOperationsTests + { + [TestCase] + public void CreateResourceFromModel() + { + //TODO: 4622 needs complete with a Mocked example to fill in this test + //public ArmResponse CreateResource(string name, TResource model, azure_proto_core.Location location = default) + Assert.Ignore(); + } + + [TestCase] + public void CreateResourceFromModelAsync() + { + //TODO: 4622 needs complete with a Mocked example to fill in this test + //public ArmResponse CreateResource(string name, TResource model, azure_proto_core.Location location = default) + Assert.Ignore(); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceIdentifierTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceIdentifierTests.cs new file mode 100644 index 0000000000000..d3763223a8715 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceIdentifierTests.cs @@ -0,0 +1,240 @@ +using NUnit.Framework; +using System; + +namespace Azure.ResourceManager.Core.Tests +{ + public class ResourceIdentifierTests + { + const string TrackedResourceId = + "/subscriptions/0c2f6471-1bf0-4dda-aec3-cb9272f09575/resourceGroups/myRg/providers/Microsoft.Compute/virtualMachines/myVm"; + const string ChildResourceId = + "/subscriptions/0c2f6471-1bf0-4dda-aec3-cb9272f09575/resourceGroups/myRg/providers/Microsoft.Network/vortualNetworks/myNet/subnets/mySubnet"; + const string ResourceGroupResourceId = "/subscriptions/0c2f6471-1bf0-4dda-aec3-cb9272f09575/resourceGroups/myRg"; + const string LocationResourceId = "/subscriptions/0c2f6471-1bf0-4dda-aec3-cb9272f09575/locations/MyLocation"; + const string SubscriptionResourceId = "/subscriptions/0c2f6471-1bf0-4dda-aec3-cb9272f09575"; + + [SetUp] + public void Setup() + { + } + + [TestCase("")] + [TestCase(" ")] + [TestCase("asdfghj")] + [TestCase("123456")] + [TestCase("!@#$%^&*/")] + [TestCase("/subscriptions/")] + [TestCase("/0c2f6471-1bf0-4dda-aec3-cb9272f09575/myRg/")] + public void InvalidRPIds(string invalidID) + { + Assert.Throws(() => { ResourceIdentifier subject = invalidID; }); + Assert.Throws(() => { ResourceIdentifier subject = new ResourceIdentifier(invalidID); }); + } + + [TestCase (null)] + [TestCase (TrackedResourceId)] + [TestCase(ChildResourceId)] + [TestCase(ResourceGroupResourceId)] + [TestCase(LocationResourceId)] + [TestCase(SubscriptionResourceId)] + public void ImplicitConstructor(string resourceProviderID) + { + string x = resourceProviderID; + string y; + ResourceIdentifier z; + + z = x; + y = z; + + if (resourceProviderID is null) + { + Assert.IsNull(z); + Assert.IsNull(y); + } + else + { + Assert.AreEqual(resourceProviderID, y); + } + } + + [TestCase (TrackedResourceId)] + [TestCase (ChildResourceId)] + [TestCase (ResourceGroupResourceId)] + [TestCase (LocationResourceId)] + [TestCase (SubscriptionResourceId)] + [TestCase(null)] + public void PublicConstructor(string resourceProviderID) + { + if (resourceProviderID is null) + { + Assert.Throws(() => { ResourceIdentifier myResource = new ResourceIdentifier(resourceProviderID); }); + } + else + { + ResourceIdentifier myResource = new ResourceIdentifier(resourceProviderID); + Assert.AreEqual(myResource.ToString(), resourceProviderID); + } + } + + [TestCase("0c2f6471-1bf0-4dda-aec3-cb9272f09575", "myRg", "Microsoft.Compute", "virtualMachines", "myVM")] + [TestCase("0c2f6471-1bf0-4dda-aec3-cb9272f09575", "!@#$%^&*()-_+=;:'\",<.>/?", "Microsoft.Network", "virtualNetworks", "MvVM_vnet")] + [TestCase("0c2f6471-1bf0-4dda-aec3-cb9272f09575", "myRg", "Microsoft.Network", "publicIpAddresses", "!@#$%^&*()-_+=;:'\",<.>/?")] + public void CanParseRPIds(string subscription, string resourceGroup, string provider, string type, string name) + { + var resourceId = $"/subscriptions/{subscription}/resourceGroups/{Uri.EscapeDataString(resourceGroup)}/providers/{provider}/{type}/{Uri.EscapeDataString(name)}"; + ResourceIdentifier subject = resourceId; + Assert.AreEqual(subject.ToString(), resourceId); + Assert.AreEqual(subject.Subscription, subscription); + Assert.AreEqual(Uri.UnescapeDataString(subject.ResourceGroup), resourceGroup); + Assert.AreEqual(subject.Type.Namespace, provider); + Assert.AreEqual(subject.Type.Type, type); + Assert.AreEqual(Uri.UnescapeDataString(subject.Name), name); + } + + [TestCase(TrackedResourceId, "Microsoft.Authorization", "roleAssignments", "myRa")] + [TestCase(ChildResourceId, "Microsoft.Authorization", "roleAssignments", "myRa")] + [TestCase(ResourceGroupResourceId, "Microsoft.Authorization", "roleAssignments", "myRa")] + [TestCase(LocationResourceId, "Microsoft.Authorization", "roleAssignments", "myRa")] + [TestCase(SubscriptionResourceId, "Microsoft.Authorization", "roleAssignments", "myRa")] + public void CanParseExtensionResourceIds(string baseId, string extensionNamespace, string extensionType, string extensionName) + { + ResourceIdentifier targetResourceId = baseId; + ResourceIdentifier subject = $"{baseId}/providers/{extensionNamespace}/{extensionType}/{extensionName}"; + ResourceType expectedType = $"{extensionNamespace}/{extensionType}"; + Assert.AreNotEqual(targetResourceId.Type, subject.Type); + Assert.AreEqual(expectedType, subject.Type); + Assert.NotNull(subject.Parent); + Assert.AreEqual(targetResourceId, subject.Parent); + } + + [TestCase ("0c2f6471-1bf0-4dda-aec3-cb9272f09575", "myRg", "Microsoft.Web","appServices/myApp/config", "appServices/config")] + public void CanParseProxyResource(string subscription, string rg, string resourceNamespace, string resource, string type) + { + string id = $"/subscriptions/{subscription}/resourceGroups/{rg}/providers/{resourceNamespace}/{resource}"; + ResourceIdentifier subject = id; + Assert.AreEqual(subject.ToString(), id); + Assert.AreEqual(subject.Subscription, subscription); + Assert.AreEqual(subject.Type.Namespace, resourceNamespace); + Assert.AreEqual(subject.Type.Type, type); + } + + [Test] + public void CanParseSubscriptions() + { + ResourceIdentifier subject = "/subscriptions/0c2f6471-1bf0-4dda-aec3-cb9272f09575"; + Assert.AreEqual(subject.ToString(), "/subscriptions/0c2f6471-1bf0-4dda-aec3-cb9272f09575"); + Assert.AreEqual(subject.Subscription, "0c2f6471-1bf0-4dda-aec3-cb9272f09575"); + Assert.AreEqual(subject.Type.Namespace, "Microsoft.Resources"); + Assert.AreEqual(subject.Type.Type, "subscriptions"); + } + + [Test] + public void CanParseResourceGroups() + { + ResourceIdentifier subject = "/subscriptions/0c2f6471-1bf0-4dda-aec3-cb9272f09575/resourceGroups/myRg"; + Assert.AreEqual(subject.ToString(), "/subscriptions/0c2f6471-1bf0-4dda-aec3-cb9272f09575/resourceGroups/myRg"); + Assert.AreEqual(subject.Subscription, "0c2f6471-1bf0-4dda-aec3-cb9272f09575"); + Assert.AreEqual(subject.ResourceGroup, "myRg"); + Assert.AreEqual(subject.Type.Namespace, "Microsoft.Resources"); + Assert.AreEqual(subject.Type.Type, "resourceGroups"); + } + + [TestCase("MyVnet", "MySubnet")] + [TestCase("!@#$%^&*()-_+=;:'\",<.>/?", "MySubnet")] + [TestCase("MyVnet", "!@#$%^&*()-_+=;:'\",<.>/?")] + public void CanParseChildResources(string parentName, string name) + { + var resourceId = $"/subscriptions/0c2f6471-1bf0-4dda-aec3-cb9272f09575/resourceGroups/myRg/providers/Microsoft.Network/virtualNetworks/{Uri.EscapeDataString(parentName)}/subnets/{Uri.EscapeDataString(name)}"; + ResourceIdentifier subject = resourceId; + Assert.AreEqual(subject.ToString(), resourceId); + Assert.AreEqual(subject.Subscription, "0c2f6471-1bf0-4dda-aec3-cb9272f09575"); + Assert.AreEqual(Uri.UnescapeDataString(subject.ResourceGroup), "myRg"); + Assert.AreEqual(subject.Type.Namespace, "Microsoft.Network"); + Assert.AreEqual(subject.Type.Parent.Type, "virtualNetworks"); + Assert.AreEqual(subject.Type.Type, "virtualNetworks/subnets"); + Assert.AreEqual(Uri.UnescapeDataString(subject.Name), name); + + // check parent type parsing + var parentResource = $"/subscriptions/0c2f6471-1bf0-4dda-aec3-cb9272f09575/resourceGroups/myRg/providers/Microsoft.Network/virtualNetworks/{Uri.EscapeDataString(parentName)}"; + Assert.AreEqual(subject.Parent, parentResource); + Assert.AreEqual(subject.Parent.ToString(), parentResource); + Assert.AreEqual(subject.Parent.Subscription, "0c2f6471-1bf0-4dda-aec3-cb9272f09575"); + Assert.AreEqual(Uri.UnescapeDataString(subject.Parent.ResourceGroup), "myRg"); + Assert.AreEqual(subject.Parent.Type.Namespace, "Microsoft.Network"); + Assert.AreEqual(subject.Parent.Type.Type, "virtualNetworks"); + Assert.AreEqual(Uri.UnescapeDataString(subject.Parent.Name), parentName); + } + + [TestCase("UnformattedString", Description ="Too Few Elements")] + [TestCase("/subs/sub1/rgs/rg1/", Description = "No known parts")] + [TestCase("/subscriptions/sub1/resourceGroups", Description = "Too few parts")] + public void ThrowsOnInvalidUri(string resourceId) + { + Assert.Throws(new TestDelegate(() => ConvertToResourceId(resourceId))); + } + + public ResourceIdentifier ConvertToResourceId(string resourceId) + { + ResourceIdentifier subject = resourceId; + return subject; + } + + [TestCase(true, "/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport", "/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport")] + [TestCase(false, "/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport2", "/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport")] + [TestCase(false, "/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test/providers/Microsoft.Web/sites/autoreport", "/subscriptions/6b085460-5f21-477e-ba44-1035046e9101/resourceGroups/nbhatia_test")] + public void CheckHashCode(bool expected, string resourceId1, string resourceId2) + { + ResourceIdentifier resourceIdentifier1 = new ResourceIdentifier(resourceId1); + ResourceIdentifier resourceIdentifier2 = new ResourceIdentifier(resourceId2); + Assert.AreEqual(expected, resourceIdentifier1.GetHashCode() == resourceIdentifier2.GetHashCode()); + } + + [TestCase(TrackedResourceId, TrackedResourceId, true)] + [TestCase(ChildResourceId, ChildResourceId, true)] + [TestCase(null, null, true)] + [TestCase(TrackedResourceId, ChildResourceId, false)] + [TestCase(ChildResourceId, TrackedResourceId, false)] + [TestCase(null, TrackedResourceId, false)] + public void Equals(string resourceProviderID1, string resourceProviderID2, bool expected) + { + ResourceIdentifier a = resourceProviderID1; + ResourceIdentifier b = resourceProviderID2; + if(a != null) + Assert.AreEqual(expected, a.Equals(b)); + + Assert.AreEqual(expected, ResourceIdentifier.Equals(a,b)); + } + + [TestCase(TrackedResourceId, TrackedResourceId, 0)] + [TestCase(TrackedResourceId, ChildResourceId, -1)] + [TestCase(ChildResourceId, TrackedResourceId, 1)] + [TestCase(TrackedResourceId, null, 1)] + [TestCase(null, TrackedResourceId, -1)] + [TestCase(null, null, 0)] + public void CompareToResourceProvider(string resourceProviderID1, string resourceProviderID2, int expected) + { + ResourceIdentifier a = resourceProviderID1; + ResourceIdentifier b = resourceProviderID2; + if (a != null) + Assert.AreEqual(expected, a.CompareTo(b)); + + Assert.AreEqual(expected, ResourceIdentifier.CompareTo(a, b)); + } + + [TestCase(TrackedResourceId, TrackedResourceId, 0)] + [TestCase(TrackedResourceId, ChildResourceId, -1)] + [TestCase(ChildResourceId, TrackedResourceId, 1)] + [TestCase(TrackedResourceId, null, 1)] + [TestCase(null, TrackedResourceId, -1)] + [TestCase(null, null, 0)] + public void CompareToString(string resourceProviderID1, string resourceProviderID2, int expected) + { + ResourceIdentifier a = resourceProviderID1; + string b = resourceProviderID2; + if (a != null) + Assert.AreEqual(expected, a.CompareTo(b)); + + Assert.AreEqual(expected, ResourceIdentifier.CompareTo(a, b)); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceListOperationsTest.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceListOperationsTest.cs new file mode 100644 index 0000000000000..2794fbf7573f1 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceListOperationsTest.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using Azure.Identity; +using Azure.ResourceManager.Resources.Models; +using NUnit.Framework; + +namespace Azure.ResourceManager.Core.Tests +{ + public class ResourceListOperationsTest + { + [TestCase] + public void TestArmResponseArmResource() + { + var expected = GetGenericResource(); + var asArmOp = (GenericResource)TestListActivator(expected); + + Assert.IsNotNull(asArmOp.Data.Sku); + Assert.AreEqual(expected.Sku.Capacity, asArmOp.Data.Sku.Capacity); + Assert.AreEqual(expected.Sku.Family, asArmOp.Data.Sku.Family); + Assert.AreEqual(expected.Sku.Name, asArmOp.Data.Sku.Name); + Assert.AreEqual(expected.Sku.Size, asArmOp.Data.Sku.Size); + Assert.AreEqual(expected.Sku.Tier, asArmOp.Data.Sku.Tier); + + Assert.IsNotNull(asArmOp.Data.Plan); + Assert.AreEqual(expected.Plan.Name, asArmOp.Data.Plan.Name); + Assert.AreEqual(expected.Plan.Product, asArmOp.Data.Plan.Product); + Assert.AreEqual(expected.Plan.PromotionCode, asArmOp.Data.Plan.PromotionCode); + Assert.AreEqual(expected.Plan.Publisher, asArmOp.Data.Plan.Publisher); + Assert.AreEqual(expected.Plan.Version, asArmOp.Data.Plan.Version); + + Assert.IsTrue(expected.Location == asArmOp.Data.Location); + Assert.AreEqual(expected.Kind, asArmOp.Data.Kind); + Assert.AreEqual(expected.ManagedBy, asArmOp.Data.ManagedBy); + } + + private static ResourceManager.Resources.Models.Plan GetPlan() + { + var plan = new ResourceManager.Resources.Models.Plan(); + plan.Name = "name"; + plan.Product = "product"; + plan.Publisher = "publisher"; + plan.PromotionCode = "promo"; + plan.Version = "version"; + return plan; + } + + private static ResourceManager.Resources.Models.Sku GetSku() + { + var sku = new ResourceManager.Resources.Models.Sku(); + sku.Capacity = 10; + sku.Family = "family"; + sku.Name = "name"; + sku.Size = "size"; + sku.Tier = "tier"; + return sku; + } + + [TestCase] + public void TestArmResourceActivator() + { + var expected = GetGenericResource(); + var actual = Activator.CreateInstance(typeof(GenericResourceData), expected as ResourceManager.Resources.Models.GenericResource) as GenericResourceData; + + Assert.IsNotNull(actual.Sku); + Assert.AreEqual(expected.Sku.Capacity, actual.Sku.Capacity); + Assert.AreEqual(expected.Sku.Family, actual.Sku.Family); + Assert.AreEqual(expected.Sku.Name, actual.Sku.Name); + Assert.AreEqual(expected.Sku.Size, actual.Sku.Size); + Assert.AreEqual(expected.Sku.Tier, actual.Sku.Tier); + + Assert.IsNotNull(actual.Plan); + Assert.AreEqual(expected.Plan.Name, actual.Plan.Name); + Assert.AreEqual(expected.Plan.Product, actual.Plan.Product); + Assert.AreEqual(expected.Plan.PromotionCode, actual.Plan.PromotionCode); + Assert.AreEqual(expected.Plan.Publisher, actual.Plan.Publisher); + Assert.AreEqual(expected.Plan.Version, actual.Plan.Version); + + Assert.IsTrue(expected.Location == actual.Location); + Assert.AreEqual(expected.Kind, actual.Kind); + Assert.AreEqual(expected.ManagedBy, actual.ManagedBy); + + } + + private static object TestListActivator(GenericResourceExpanded genericResource) + { + var createResourceConverterMethod = typeof(ResourceListOperations).GetMethod("CreateResourceConverter", BindingFlags.Static | BindingFlags.NonPublic); + ResourceGroupOperations rgOp = GetResourceGroupOperations(); + var activatorFunction = (Func)createResourceConverterMethod.Invoke(null, new object[] { rgOp }); + return activatorFunction.DynamicInvoke(new object[] { genericResource }); + } + + private static ResourceGroupOperations GetResourceGroupOperations() + { + var rgOp = new ResourceGroupOperations( + new SubscriptionOperations( + new AzureResourceManagerClientOptions(), + Guid.Empty.ToString(), + new DefaultAzureCredential(), //should make a fake credential creation + new Uri("http://foo.com")), + "rgName"); + return rgOp; + } + + private static GenericResourceExpanded GetGenericResource() + { + return GetGenereicResource( + new Dictionary { { "tag1", "value1" } }, + GetSku(), + GetPlan(), + "UserAssigned", + "test", + "Japan East"); + } + + private static GenericResourceExpanded GetGenereicResource( + Dictionary tags, + ResourceManager.Resources.Models.Sku sku, + ResourceManager.Resources.Models.Plan plan, + string kind, + string managedBy, + string location) + { + var resource = new GenericResourceExpanded(); + + // See TODO in GenericResourceOperations.Valide(). + // resource.Id = "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup"; + resource.Location = location; + resource.Tags.ReplaceWith(tags ?? new Dictionary()); + resource.Sku = sku; + resource.Plan = plan; + resource.Kind = kind; + resource.ManagedBy = managedBy; + return resource; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceNameFilterTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceNameFilterTests.cs new file mode 100644 index 0000000000000..5e029cef396d2 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceNameFilterTests.cs @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.ResourceManager.Core.Resources; +using NUnit.Framework; + +namespace Azure.ResourceManager.Core.Tests +{ + public class ResourceNameFilterTests + { + [TestCase("filter")] + [TestCase("")] + [TestCase(")(@#$)&!)(@")] + public void ImplicitCast(string filter) + { + ResourceNameFilter nameFilter = filter; + Assert.AreEqual(nameFilter.Name, filter); + } + + [TestCase] + public void ImplicitCastNull() + { + string filter = null; + ResourceNameFilter nameFilter = filter; + Assert.IsNull(nameFilter); + } + + [TestCase(true, "foo", "foo")] + [TestCase(false, "foo", "")] + [TestCase(false, "foo", null)] + [TestCase(true, ")(@#$)&!)(@", ")(@#$)&!)(@")] + [TestCase(true, "", "")] + [TestCase(false, "foo", "bar")] + public void EqualsWithString(bool expected, string left, string right) + { + ResourceNameFilter leftFilter = left; + Assert.AreEqual(expected, leftFilter.Equals(right)); + } + + [TestCase(true, "foo", "foo")] + [TestCase(false, "foo", "")] + [TestCase(false, "foo", null)] + [TestCase(true, ")(@#$)&!)(@", ")(@#$)&!)(@")] + [TestCase(true, "", "")] + [TestCase(false, "foo", "bar")] + public void EqualsWithResourceNameFilter(bool expected, string left, string right) + { + ResourceNameFilter leftFilter = left; + ResourceNameFilter rightFilter = right; + Assert.AreEqual(expected, leftFilter.Equals(rightFilter)); + } + + [TestCase("substringof('filter', name)", "filter")] + [TestCase("", "")] + [TestCase("substringof(')(@#$)&!)(@', name)", ")(@#$)&!)(@")] + public void GetFilterString(string expected, string filter) + { + ResourceNameFilter nameFilter = filter; + Assert.AreEqual(expected, nameFilter.GetFilterString()); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceTagFilterTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceTagFilterTests.cs new file mode 100644 index 0000000000000..a3be301ead6a1 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceTagFilterTests.cs @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.ResourceManager.Core.Resources; +using NUnit.Framework; +using System; + +namespace Azure.ResourceManager.Core.Tests +{ + public class ResourceTagFilterTests + { + [TestCase] + public void ConstructNullTuple() + { + Assert.Throws(() => new ResourceTagFilter(null)); + } + + [TestCase] + public void ConstructNullTupleKey() + { + string key = null; + Assert.Throws(() => new ResourceTagFilter(Tuple.Create(key, ""))); + } + + [TestCase] + public void ConstructNullTupleValue() + { + string value = null; + Assert.Throws(() => new ResourceTagFilter(Tuple.Create("", value))); + } + + [TestCase] + public void ConstructNullKey() + { + Assert.Throws(() => new ResourceTagFilter(null, "")); + } + + [TestCase] + public void ConstructNullValue() + { + Assert.Throws(() => new ResourceTagFilter("", null)); + } + + [TestCase(true, "key", "value", "key", "value")] + [TestCase(false, "key", "value", "key1", "value")] + [TestCase(false, "key", "value", "key", "value1")] + [TestCase(false, "key1", "value", "key", "value")] + [TestCase(false, "key", "value1", "key", "value")] + [TestCase(false, "key", "value", "key1", "value1")] + [TestCase(false, "key", "value", "", "value")] + [TestCase(false, "key", "value", "key", "")] + public void Equals(bool expected, string leftKey, string leftValue, string rightKey, string rightValue) + { + ResourceTagFilter leftFilter = new ResourceTagFilter(leftKey, leftValue); + ResourceTagFilter rightFilter = new ResourceTagFilter(rightKey, rightValue); + Assert.AreEqual(expected, leftFilter.Equals(rightFilter)); + } + + [TestCase("tagName eq 'key' and tagValue eq 'value'", "key", "value")] + [TestCase("tagName eq ')(@#$)&!)(@' and tagValue eq ')#$)(USkjao'", ")(@#$)&!)(@", ")#$)(USkjao")] + public void GetFilterString(string expected, string key, string value) + { + ResourceTagFilter tagFilter = new ResourceTagFilter(key, value); + Assert.AreEqual(expected, tagFilter.GetFilterString()); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceTests.cs new file mode 100644 index 0000000000000..7daa8db050283 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceTests.cs @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using NUnit.Framework; + +namespace Azure.ResourceManager.Core.Tests +{ + public class ResourceTests + { + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1")] + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.classicStorage/storageAccounts/account1")] + [TestCase(-1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.DiffSpace/storageAccounts/account2")] + [TestCase(1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.DiffSpace/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account2")] + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.${?>._`/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.${?>._`/storageAccounts/account1")] + [TestCase(-1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/${?>._`", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account2")] + public void CompareToObject(int expected, string id1, string id2) + { + TestResource resource1 = new TestResource(id1); + TestResource resource2 = new TestResource(id2); + Assert.AreEqual(expected, resource1.CompareTo(resource2)); + } + + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1")] + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.classicStorage/storageAccounts/account1")] + [TestCase(-1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.DiffSpace/storageAccounts/account2")] + [TestCase(1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.DiffSpace/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account2")] + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.${?>._`/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.${?>._`/storageAccounts/account1")] + [TestCase(-1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/${?>._`", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account2")] + public void CompareToString(int expected, string id1, string id2) + { + TestResource resource1 = new TestResource(id1); + Assert.AreEqual(expected, resource1.CompareTo(id2)); + } + + [Test] + public void CompareToNull() + { + TestResource resource1 = new TestResource("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1"); + TestResource resource2 = null; + Assert.AreEqual(1, resource1.CompareTo(resource2)); + Assert.AreEqual(1, resource1.CompareTo((string)null)); + } + + [Test] + public void CompareToSame() + { + TestResource resource1 = new TestResource("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1"); + TestResource resource2 = resource1; + Assert.AreEqual(0, resource1.CompareTo(resource2)); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceTypeTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceTypeTests.cs new file mode 100644 index 0000000000000..24663714320c5 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/ResourceTypeTests.cs @@ -0,0 +1,233 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using NUnit.Framework; +using System; + +namespace Azure.ResourceManager.Core.Tests +{ + public class ResourceTypeTests + { + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account2")] + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.classicStorage/storageAccounts/account2")] + [TestCase(-1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.DiffSpace/storageAccounts/account2")] + [TestCase(1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.DiffSpace/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account2")] + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.${?>._`/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.${?>._`/storageAccounts/account2")] + [TestCase(-1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.${?>._`/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account2")] + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1", + "Microsoft.ClassicStorage/storageAccounts")] + [TestCase(0, "Microsoft.classicStorage/storageAccounts", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1")] + [TestCase(-1, "Microsoft.ClassicStorage/storageAccounts", "Microsoft.DiffSpace/storageAccounts")] + [TestCase(1, "Microsoft.ClassicStorage/storageAccounts", "Microsoft.${?>._`/storageAccounts")] + public void CompateToNamespace(int expected, string resource1, string resource2) + { + ResourceType resourceType1 = new ResourceType(resource1); + ResourceType resourceType2 = new ResourceType(resource2); + Assert.AreEqual(expected, resourceType1.CompareTo(resourceType2)); + } + + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/StorageAccounts/account2")] + [TestCase(1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/diffaccount/account2")] + [TestCase(-1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/diffaccount/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account2")] + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/${?>._`/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/${?>._`/account2")] + [TestCase(-1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/${?>._`/account1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account2")] + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1", + "Microsoft.ClassicStorage/StorageAccounts")] + [TestCase(0, "Microsoft.classicStorage/storageAccounts", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/StorageAccounts/account2")] + [TestCase(-1, "Microsoft.ClassicStorage/diffaccount", "Microsoft.ClassicStorage/storageAccounts")] + [TestCase(1, "Microsoft.ClassicStorage/storageAccounts", "Microsoft.ClassicStorage/${?>._`")] + public void CompateToType(int expected, string resource1, string resource2) + { + ResourceType resourceType1 = new ResourceType(resource1); + ResourceType resourceType2 = new ResourceType(resource2); + Assert.AreEqual(expected, resourceType1.CompareTo(resourceType2)); + } + + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network/virtualNetworks/Testvnet/subnets/default1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network/virtualNetworks/Testvnet/subnets/default2")] + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network/virtualNetworks/Testvnet/subnets/default1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network/virtualnetworks/Testvnet/subnets/default2")] + [TestCase(1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network/virtualNetworks/Testvnet/subnets/default1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network/parentTest/Testvnet/subnets/default2")] + [TestCase(-1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network/parentTest/Testvnet/subnets/default1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network/virtualNetworks/Testvnet/subnets/default2")] + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network/${?>._`/Testvnet/${?>._`/default1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network/${?>._`/Testvnet/${?>._`/default2")] + [TestCase(-1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network/${?>._`/Testvnet/subnets/default1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network/virtualNetworks/Testvnet/${?>._`/default2")] + [TestCase(0, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network/virtualNetworks/Testvnet/subnets/default1", + "Microsoft.Network/virtualNetworks/subnets")] + [TestCase(0, "Microsoft.Network/virtualNetworks/subnets", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network/virtualNetworks/Testvnet/subnets/default2")] + [TestCase(-1, "Microsoft.Network/parentTest/subnets", "Microsoft.Network/virtualNetworks/subnets")] + [TestCase(1, "Microsoft.Network/virtualNetworks/subnets", "Microsoft.Network/${?>._`/subnets")] + public void CompateToParent(int expected, string resource1, string resource2) + { + ResourceType resourceType1 = new ResourceType(resource1); + ResourceType resourceType2 = new ResourceType(resource2); + Assert.AreEqual(expected, resourceType1.CompareTo(resourceType2)); + } + + [Test] + public void CompateToSameResourceTypes() + { + ResourceType resourceType1 = new ResourceType("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1"); + ResourceType resourceType2 = resourceType1; + Assert.AreEqual(0, resourceType1.CompareTo(resourceType2)); + } + + [Test] + public void CompateToNull() + { + ResourceType resourceType1 = new ResourceType("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.ClassicStorage/storageAccounts/account1"); + ResourceType resourceType2 = null; + Assert.AreEqual(1, resourceType1.CompareTo(resourceType2)); + } + + [TestCase(-1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network1/virtualNetworks2/Testvnet/subnets/default1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.network2/virtualNetworks1/Testvnet/Subnets/default2")] + [TestCase(1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.network2/VirtualNetworks2/Testvnet/subnets2/default1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network1/virtualNetworks1/Testvnet/Subnets1/default2")] + [TestCase(1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.network2/VirtualNetworks2/Testvnet/Subnets2/default1", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.network1/virtualNetworks1/Testvnet/Subnets1/default2")] + [TestCase(1, "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.network2/VirtualNetworks2/Testvnet/Subnets2/default1", + "Microsoft.network1/parentTest/subnets1")] + [TestCase(-1, "Microsoft.Network1/VirtualNetworks1/subnets2", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testRg/providers/Microsoft.Network1/VirtualNetworks2/Testvnet/subnets1/default2")] + [TestCase(1, "Microsoft.network1/virtualvetworks1/Subnets2", "Microsoft.Network1/VirtualNetworks2/subnets1")] + public void CompateToMore(int expected, string resource1, string resource2) + { + ResourceType resourceType1 = new ResourceType(resource1); + ResourceType resourceType2 = new ResourceType(resource2); + Assert.AreEqual(expected, resourceType1.CompareTo(resourceType2)); + } + + [TestCase("")] + [TestCase("\n")] + [TestCase("\t")] + [TestCase(" ")] + [TestCase("\r")] + [TestCase(null)] + public void InvalidConstructorParam(string input) + { + Assert.Throws(() => new ResourceType(input)); + } + + [TestCase] + public void NullImplicitFromString() + { + string from = null; + ResourceType to = from; + + Assert.IsNull(to); + } + + [TestCase(false, null, "Microsoft.Network1/VirtualNetworks2/subnets1")] + [TestCase(false, "Microsoft.Network1/VirtualNetworks2/subnets1", null)] + [TestCase(true, null, null)] + [TestCase(true, "Microsoft.Network1/VirtualNetworks2/subnets1", "Microsoft.Network1/VirtualNetworks2/subnets1")] + public void EqualsOpResourceTypeToString(bool expected, string left, string right) + { + ResourceType leftResource = left; + Assert.AreEqual(expected, leftResource == right); + } + + [TestCase(false, null, "Microsoft.Network1/VirtualNetworks2/subnets1")] + [TestCase(false, "Microsoft.Network1/VirtualNetworks2/subnets1", null)] + [TestCase(true, null, null)] + [TestCase(true, "Microsoft.Network1/VirtualNetworks2/subnets1", "Microsoft.Network1/VirtualNetworks2/subnets1")] + public void EqualsOpStringToResourceType(bool expected, string left, string right) + { + ResourceType rightResource = right; + Assert.AreEqual(expected, left == rightResource); + } + + [TestCase(false, null, "Microsoft.Network1/VirtualNetworks2/subnets1")] + [TestCase(false, "Microsoft.Network1/VirtualNetworks2/subnets1", null)] + [TestCase(true, null, null)] + [TestCase(true, "Microsoft.Network1/VirtualNetworks2/subnets1", "Microsoft.Network1/VirtualNetworks2/subnets1")] + public void EqualsOpResourceTypeToResourceType(bool expected, string left, string right) + { + ResourceType leftResource = left; + ResourceType rightResource = right; + Assert.AreEqual(expected, leftResource == rightResource); + } + + [TestCase(true, null, "Microsoft.Network1/VirtualNetworks2/subnets1")] + [TestCase(true, "Microsoft.Network1/VirtualNetworks2/subnets1", null)] + [TestCase(false, null, null)] + [TestCase(false, "Microsoft.Network1/VirtualNetworks2/subnets1", "Microsoft.Network1/VirtualNetworks2/subnets1")] + public void NotEqualsOpResourceTypeToString(bool expected, string left, string right) + { + ResourceType leftResource = left; + Assert.AreEqual(expected, leftResource != right); + } + + [TestCase(true, null, "Microsoft.Network1/VirtualNetworks2/subnets1")] + [TestCase(true, "Microsoft.Network1/VirtualNetworks2/subnets1", null)] + [TestCase(false, null, null)] + [TestCase(false, "Microsoft.Network1/VirtualNetworks2/subnets1", "Microsoft.Network1/VirtualNetworks2/subnets1")] + public void NotEqualsOpStringToResourceType(bool expected, string left, string right) + { + ResourceType rightResource = right; + Assert.AreEqual(expected, left != rightResource); + } + + [TestCase(true, null, "Microsoft.Network1/VirtualNetworks2/subnets1")] + [TestCase(true, "Microsoft.Network1/VirtualNetworks2/subnets1", null)] + [TestCase(false, null, null)] + [TestCase(false, "Microsoft.Network1/VirtualNetworks2/subnets1", "Microsoft.Network1/VirtualNetworks2/subnets1")] + public void NotEqualsOpResourceTypeToResourceType(bool expected, string left, string right) + { + ResourceType leftResource = left; + ResourceType rightResource = right; + Assert.AreEqual(expected, leftResource != rightResource); + } + + [TestCase] + public void CompareToNulString() + { + string other = null; + ResourceType rt = "Microsoft.Network1/VirtualNetworks2/subnets1"; + Assert.AreEqual(1, rt.CompareTo(other)); + } + + [TestCase] + public void ParseArgumentException() + { + Assert.Throws(() => { ResourceType rt = "/"; }); + } + + [TestCase(false, "Microsoft.Network1/VirtualNetworks2/subnets1", null)] + [TestCase(true, "Microsoft.Network1/VirtualNetworks2/subnets1", "Microsoft.Network1/VirtualNetworks2/subnets1")] + public void EqualsWithObjectResourceType(bool expected, string left, string right) + { + ResourceType rt = left; + ResourceType rightRt = right; + object rightObject = rightRt; + Assert.AreEqual(expected, rt.Equals(rightObject)); + } + + [TestCase(false, "Microsoft.Network1/VirtualNetworks2/subnets1", null)] + [TestCase(true, "Microsoft.Network1/VirtualNetworks2/subnets1", "Microsoft.Network1/VirtualNetworks2/subnets1")] + public void EqualsWithObjectString(bool expected, string left, string right) + { + ResourceType rt = left; + object rightObject = right; + Assert.AreEqual(expected, rt.Equals(rightObject)); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/RpImplementations/ArmClientOptionsExtensions.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/RpImplementations/ArmClientOptionsExtensions.cs new file mode 100644 index 0000000000000..fbced51f6a655 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/RpImplementations/ArmClientOptionsExtensions.cs @@ -0,0 +1,10 @@ +namespace Azure.ResourceManager.Core.Tests +{ + public static class AzureResourceManagerClientOptionsExtensions + { + public static FakeRpApiVersions FakeRpApiVersions(this AzureResourceManagerClientOptions AzureResourceManagerClientOptions) + { + return AzureResourceManagerClientOptions.GetOverrideObject(() => new FakeRpApiVersions()) as FakeRpApiVersions; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/RpImplementations/FakeResourceApiVersions.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/RpImplementations/FakeResourceApiVersions.cs new file mode 100644 index 0000000000000..376a2d84b9a8b --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/RpImplementations/FakeResourceApiVersions.cs @@ -0,0 +1,21 @@ +namespace Azure.ResourceManager.Core.Tests +{ + public class FakeResourceApiVersions : ApiVersionsBase + { + public static readonly FakeResourceApiVersions V2020_06_01 = new FakeResourceApiVersions("2020-06-01"); + public static readonly FakeResourceApiVersions V2019_12_01 = new FakeResourceApiVersions("2019-12-01"); + public static readonly FakeResourceApiVersions V2019_12_01_preview = new FakeResourceApiVersions("2019-12-01-preview"); + public static readonly FakeResourceApiVersions V2019_12_01_preview_1 = new FakeResourceApiVersions("2019-12-01-preview-1"); + public static readonly FakeResourceApiVersions V2019_12_01_foobar = new FakeResourceApiVersions("2019-12-01-foobar"); + public static readonly FakeResourceApiVersions Default = V2020_06_01; + + private FakeResourceApiVersions(string value) : base(value) { } + + public static implicit operator string(FakeResourceApiVersions version) + { + if (version == null) + return null; + return version.ToString(); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/RpImplementations/FakeRpApiVersions.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/RpImplementations/FakeRpApiVersions.cs new file mode 100644 index 0000000000000..1e3e6dc21bb34 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/RpImplementations/FakeRpApiVersions.cs @@ -0,0 +1,12 @@ +namespace Azure.ResourceManager.Core.Tests +{ + public class FakeRpApiVersions + { + internal FakeRpApiVersions() + { + FakeResourceVersion = FakeResourceApiVersions.Default; + } + + public FakeResourceApiVersions FakeResourceVersion { get; set; } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/SkuTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/SkuTests.cs new file mode 100644 index 0000000000000..e12ef2fcd5e2e --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/SkuTests.cs @@ -0,0 +1,228 @@ +using NUnit.Framework; + +namespace Azure.ResourceManager.Core.Tests +{ + class SkuTests + { + [TestCase(0, "name", "name")] + [TestCase(0, "Name", "name")] + [TestCase(0, null, null)] + [TestCase(1, "name", null)] + [TestCase(-1, null, "name")] + [TestCase(0, "${?/>._`", "${?/>._`")] + [TestCase(1, "${?/>._`", "")] + public void CompareToName(int expected, string name1, string name2) + { + Sku sku1 = new Sku(name1, null, null, null); + Sku sku2 = new Sku(name2, null, null, null); + Assert.AreEqual(expected, sku1.CompareTo(sku2)); + } + + [TestCase(0, "family", "family")] + [TestCase(0, "Family", "family")] + [TestCase(0, null, null)] + [TestCase(1, "family", null)] + [TestCase(-1, null, "family")] + [TestCase(0, "${?/>._`", "${?/>._`")] + [TestCase(1, "${?/>._`", "")] + public void CompareToFamily(int expected, string family1, string family2) + { + Sku sku1 = new Sku(null, null, family1, null); + Sku sku2 = new Sku(null, null, family2, null); + Assert.AreEqual(expected, sku1.CompareTo(sku2)); + } + + [TestCase(0, "size", "size")] + [TestCase(0, "Size", "size")] + [TestCase(0, null, null)] + [TestCase(1, "size", null)] + [TestCase(-1, null, "size")] + [TestCase(0, "${?/>._`", "${?/>._`")] + [TestCase(1, "${?/>._`", "")] + public void CompareToSize(int expected, string size1, string size2) + { + Sku sku1 = new Sku(null, null, null, size1); + Sku sku2 = new Sku(null, null, null, size2); + Assert.AreEqual(expected, sku1.CompareTo(sku2)); + } + + [TestCase(0, "tier", "tier")] + [TestCase(0, "Tier", "tier")] + [TestCase(0, null, null)] + [TestCase(1, "tier", null)] + [TestCase(-1, null, "tier")] + [TestCase(0, "${?/>._`", "${?/>._`")] + [TestCase(1, "${?/>._`", "")] + public void CompareToTier(int expected, string tier1, string tier2) + { + Sku sku1 = new Sku(null, tier1, null, null); + Sku sku2 = new Sku(null, tier2, null, null); + Assert.AreEqual(expected, sku1.CompareTo(sku2)); + } + + [TestCase(0, 1, 1)] + [TestCase(1, 1, -1)] + [TestCase(0, null, null)] + [TestCase(1, -1, null)] + [TestCase(-1, null, 1)] + public void CompareToCapacity(int expected, long? capacity1, long? capacity2) + { + Sku sku1 = capacity1 == null ? new Sku(null, null, null, null) : new Sku(null, null, null, null, capacity1); + Sku sku2 = capacity2 == null ? new Sku(null, null, null, null) : new Sku(null, null, null, null, capacity2); + Assert.AreEqual(expected, sku1.CompareTo(sku2)); + } + + [Test] + public void CompareToNullSku() + { + Sku sku1 = new Sku(null, null, null, null); + Sku sku2 = null; + Assert.AreEqual(1, sku1.CompareTo(sku2)); + } + + [Test] + public void CompareToSameSkus() + { + Sku sku1 = new Sku(null, null, null, null); + Sku sku2 = sku1; + Assert.AreEqual(0, sku1.CompareTo(sku2)); + } + + [TestCase(1, "Nameb", "namea", "familya", "Familyb")] + [TestCase(1, "Nameb", "namea", "familya", "familya")] + [TestCase(-1, "namea", "Nameb", "Familyb", "familya")] + public void CompareToMore(int expected, string name1, string name2, string family1, string family2) + { + Sku sku1 = new Sku(name1, null, family1, null); + Sku sku2 = new Sku(name2, null, family2, null); + Assert.AreEqual(expected, sku1.CompareTo(sku2)); + } + + [TestCase(true, "name", "name")] + [TestCase(true, "Name", "name")] + [TestCase(true, null, null)] + [TestCase(false, "name", null)] + [TestCase(false, null, "name")] + [TestCase(true, "${?/>._`", "${?/>._`")] + [TestCase(false, "${?/>._`", "")] + public void EqualsToName(bool expected, string name1, string name2) + { + Sku sku1 = new Sku(name1, null, null, null); + Sku sku2 = new Sku(name2, null, null, null); + if (expected) + { + Assert.IsTrue(sku1.Equals(sku2)); + } + else + { + Assert.IsFalse(sku1.Equals(sku2)); + } + } + + [TestCase(true, "family", "family")] + [TestCase(true, "Family", "family")] + [TestCase(true, null, null)] + [TestCase(false, "family", null)] + [TestCase(false, null, "family")] + [TestCase(true, "${?/>._`", "${?/>._`")] + [TestCase(false, "${?/>._`", "")] + public void EqualsToFamily(bool expected, string family1, string family2) + { + Sku sku1 = new Sku(null, null, family1, null); + Sku sku2 = new Sku(null, null, family2, null); + if (expected) + { + Assert.IsTrue(sku1.Equals(sku2)); + } + else + { + Assert.IsFalse(sku1.Equals(sku2)); + } + } + + [TestCase(true, "size", "size")] + [TestCase(true, "Size", "size")] + [TestCase(true, null, null)] + [TestCase(false, "size", null)] + [TestCase(false, null, "size")] + [TestCase(true, "${?/>._`", "${?/>._`")] + [TestCase(false, "${?/>._`", "")] + public void EqualsToSize(bool expected, string size1, string size2) + { + Sku sku1 = new Sku(null, null, null, size1); + Sku sku2 = new Sku(null, null, null, size2); + if (expected) + { + Assert.IsTrue(sku1.Equals(sku2)); + } + else + { + Assert.IsFalse(sku1.Equals(sku2)); + } + } + + [TestCase(true, "tier", "tier")] + [TestCase(true, "Tier", "tier")] + [TestCase(true, null, null)] + [TestCase(false, "tier", null)] + [TestCase(false, null, "tier")] + [TestCase(true, "${?/>._`", "${?/>._`")] + [TestCase(false, "${?/>._`", "")] + public void EqualsToTier(bool expected, string tier1, string tier2) + { + Sku sku1 = new Sku(null, tier1, null, null); + Sku sku2 = new Sku(null, tier2, null, null); + if (expected) + { + Assert.IsTrue(sku1.Equals(sku2)); + } + else + { + Assert.IsFalse(sku1.Equals(sku2)); + } + } + + [TestCase(true, 1, 1)] + [TestCase(false, 1, 0)] + [TestCase(true, null, null)] + [TestCase(false, 1, null)] + [TestCase(false, null, 1)] + public void EqualsToCapacity(bool expected, long? capacity1, long? capacity2) + { + Sku sku1 = capacity1 == null ? new Sku(null, null, null, null) : new Sku(null, null, null, null, capacity1); + Sku sku2 = capacity2 == null ? new Sku(null, null, null, null) : new Sku(null, null, null, null, capacity2); + if (expected) + { + Assert.IsTrue(sku1.Equals(sku2)); + } + else + { + Assert.IsFalse(sku1.Equals(sku2)); + } + } + + [Test] + public void EqualsToNullSku() + { + Sku sku1 = new Sku(null, null, null, null); + Sku sku2 = null; + Assert.IsFalse(sku1.Equals(sku2)); + } + + [Test] + public void EqualsToObject() + { + Sku sku1 = new Sku(null, null, null, null); + object sku2 = "random"; + Assert.IsFalse(sku1.Equals(sku2)); + } + + [Test] + public void EqualsToSameSkus() + { + Sku sku1 = new Sku(null, null, null, null); + Sku sku2 = sku1; + Assert.IsTrue(sku1.Equals(sku2)); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/SubscriptionOperationsTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/SubscriptionOperationsTests.cs new file mode 100644 index 0000000000000..9489d4925482f --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/SubscriptionOperationsTests.cs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using NUnit.Framework; +using System; + +namespace Azure.ResourceManager.Core.Tests +{ + public class SubscriptionOperationsTests + { + [TestCase(null)] + [TestCase("")] + [Ignore("Will remove after ADO 5122")] + public void TestGetResourceGroupOpsArgNullException(string resourceGroupName) + { + var client = new AzureResourceManagerClient(); + var subOps = client.DefaultSubscription; + Assert.Throws(delegate { subOps.GetResourceGroupOperations(resourceGroupName); }); + } + + [TestCase("te%st")] + [TestCase("test ")] + [TestCase("te$st")] + [TestCase("te#st")] + [TestCase("te#st")] + [Ignore("Will remove after ADO 5122")] + public void TestGetResourceGroupOpsArgException(string resourceGroupName) + { + var client = new AzureResourceManagerClient(); + var subOps = client.DefaultSubscription; + Assert.Throws(delegate { subOps.GetResourceGroupOperations(resourceGroupName); }); + } + + [TestCase("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")] + [Ignore("Will remove after ADO 5122")] + public void TestGetResourceGroupOpsOutOfRangeArgException(string resourceGroupName) + { + var client = new AzureResourceManagerClient(); + var subOps = client.DefaultSubscription; + Assert.Throws(delegate { subOps.GetResourceGroupOperations(resourceGroupName); }); + } + + [TestCase("te.st")] + [TestCase("te")] + [TestCase("t")] + [TestCase("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")] + [TestCase("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")] + [Ignore("Will remove after ADO 5122")] + public void TestGetResourceGroupOpsValid(string resourceGroupName) + { + var client = new AzureResourceManagerClient(); + var subOps = client.DefaultSubscription; + Assert.DoesNotThrow(delegate { subOps.GetResourceGroupOperations(resourceGroupName); }); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/SystemAssignedIdentityTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/SystemAssignedIdentityTests.cs new file mode 100644 index 0000000000000..90b7a7c8b9dca --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/SystemAssignedIdentityTests.cs @@ -0,0 +1,339 @@ +using Azure.Core.TestFramework; +using NUnit.Framework; +using System; +using System.IO; +using System.Linq; +using System.Text.Json; + +namespace Azure.ResourceManager.Core.Tests +{ + public class SystemAssignedIdentityTests + { + [TestCase(0, null, null, null, null)] + [TestCase(0, "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + + [TestCase(1, "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98", null, null)] + [TestCase(1, "72f988bf-86f1-41af-91ab-2d7cd011db48", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + [TestCase(1, "72f988bf-86f1-41af-91ab-2d7cd011db48", "de29bab1-49e1-4705-819b-4dfddceaaa97", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + [TestCase(1, "72f988bf-86f1-41af-91ab-2d7cd011db48", "de29bab1-49e1-4705-819b-4dfddceaaa99", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + [TestCase(1, "72f988bf-86f1-41af-91ab-2d7cd011eb47", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + + [TestCase(-1, null, null, "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + [TestCase(-1, "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db48", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + [TestCase(-1, "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db48", "de29bab1-49e1-4705-819b-4dfddceaaa99")] + [TestCase(-1, "72f988bf-86f1-41af-91ab-2d7cd011db46", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db48", "de29bab1-49e1-4705-819b-4dfddceaaa97")] + [TestCase(-1, "72f988bf-86f1-41af-91ab-2d7cd011db46", "de29bab1-49e1-4705-819b-4dfdbceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db46", "de29bab1-49e1-4705-819b-4dfddceaaa99")] + public void CompareTo(int answer, string tenantId1, string principalId1, string tenantId2, string principalId2) + { + SystemAssignedIdentity identity1; + SystemAssignedIdentity identity2; + if (tenantId1 == null) + { + identity1 = new SystemAssignedIdentity(); + } + else + { + identity1 = new SystemAssignedIdentity(new Guid(tenantId1), new Guid(principalId1)); + } + + if (tenantId2 == null) + { + identity2 = new SystemAssignedIdentity(); + } + else + { + identity2 = new SystemAssignedIdentity(new Guid(tenantId2), new Guid(principalId2)); + } + + Assert.AreEqual(answer, identity1.CompareTo(identity2)); + Assert.AreEqual(answer * -1, identity2.CompareTo(identity1)); + } + + [TestCase(null, null, null, null)] + [TestCase("72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + public void EqualsMethodTrue(string tenantId1, string principalId1, string tenantId2, string principalId2) + { + SystemAssignedIdentity identity1; + SystemAssignedIdentity identity2; + if (tenantId1 == null) + { + identity1 = new SystemAssignedIdentity(); + } + else + { + identity1 = new SystemAssignedIdentity(new Guid(tenantId1), new Guid(principalId1)); + } + + if (tenantId2 == null) + { + identity2 = new SystemAssignedIdentity(); + } + else + { + identity2 = new SystemAssignedIdentity(new Guid(tenantId2), new Guid(principalId2)); + } + + Assert.IsTrue(identity1.Equals(identity2)); + } + + [TestCase(null, null, "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + [TestCase("72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98", null, null)] + [TestCase("72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db44", "de29bab1-49e1-4705-819b-4dfddceaaa94")] + [TestCase("72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa93", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa91")] + [TestCase("72f988bf-86f1-41af-91ab-2d7cd011db49", "de29bab1-49e1-4705-819b-4dfddceaaa91", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa91")] + public void EqualsMethodFalse(string tenantId1, string principalId1, string tenantId2, string principalId2) + { + SystemAssignedIdentity identity1; + SystemAssignedIdentity identity2; + if (tenantId1 == null) + { + identity1 = new SystemAssignedIdentity(); + } + else + { + identity1 = new SystemAssignedIdentity(new Guid(tenantId1), new Guid(principalId1)); + } + + if (tenantId2 == null) + { + identity2 = new SystemAssignedIdentity(); + } + else + { + identity2 = new SystemAssignedIdentity(new Guid(tenantId2), new Guid(principalId2)); + } + + Assert.IsFalse(identity1.Equals(identity2)); + } + + [TestCase] + public void EqualsMethodBothIdentitiesEmpty() + { + SystemAssignedIdentity identity1 = new SystemAssignedIdentity(); + SystemAssignedIdentity identity2 = new SystemAssignedIdentity(); + Assert.IsTrue(identity1.Equals(identity2)); + } + + [TestCase] + public void EqualsMethodOneIdentityNull() + { + SystemAssignedIdentity identity1 = new SystemAssignedIdentity(); + SystemAssignedIdentity identity2 = null; + Assert.IsFalse(identity1.Equals(identity2)); + } + + [TestCase] + public void CompareToMethodBothIdentitiesEmpty() + { + SystemAssignedIdentity identity1 = new SystemAssignedIdentity(); + SystemAssignedIdentity identity2 = new SystemAssignedIdentity(); + Assert.AreEqual(0, identity1.CompareTo(identity2)); + } + + [TestCase] + public void CompareToMethodOneIdentityNull() + { + SystemAssignedIdentity identity1 = new SystemAssignedIdentity(); + SystemAssignedIdentity identity2 = null; + Assert.AreEqual(1, identity1.CompareTo(identity2)); + } + + public JsonProperty DeserializerHelper(string filename) + { + string json = GetFileText(filename); + JsonDocument document = JsonDocument.Parse(json); + JsonElement rootElement = document.RootElement; + return rootElement.EnumerateObject().First(); + } + + private static string GetFileText(string filename) + { + return File.ReadAllText(Path.Combine(TestContext.CurrentContext.TestDirectory, "TestAssets", "SystemAssignedIdentity", filename)); + } + + [TestCase] + public void TestDeserializerDefaultJson() + { + JsonElement invalid = default(JsonElement); + Assert.Throws(delegate { SystemAssignedIdentity.Deserialize(invalid); }); + } + + [TestCase] + public void TestDeserializerValid() + { + var identityJsonProperty = DeserializerHelper("SystemAssignedValid.json"); + SystemAssignedIdentity back = SystemAssignedIdentity.Deserialize(identityJsonProperty.Value); + Assert.IsTrue("de29bab1-49e1-4705-819b-4dfddceaaa98".Equals(back.PrincipalId.ToString())); + Assert.IsTrue("72f988bf-86f1-41af-91ab-2d7cd011db47".Equals(back.TenantId.ToString())); + } + + [TestCase] + public void TestDeserializerValidExtraField() + { + var json = GetFileText("SystemAssignedValidExtraField.json"); + JsonDocument document = JsonDocument.Parse(json); + JsonElement rootElement = document.RootElement; + var identityJsonProperty = rootElement.EnumerateObject().ElementAt(1); + SystemAssignedIdentity back = SystemAssignedIdentity.Deserialize(identityJsonProperty.Value); + Assert.IsTrue("de29bab1-49e1-4705-819b-4dfddceaaa98".Equals(back.PrincipalId.ToString())); + Assert.IsTrue("72f988bf-86f1-41af-91ab-2d7cd011db47".Equals(back.TenantId.ToString())); + } + + [TestCase] + public void TestDeserializerBothValuesNull() + { + var identityJsonProperty = DeserializerHelper("SystemAssignedBothValuesNull.json"); + var back = SystemAssignedIdentity.Deserialize(identityJsonProperty.Value); + Assert.IsNull(back); + } + + [TestCase] + public void TestDeserializerBothEmptyString() + { + var identityJsonProperty = DeserializerHelper("SystemAssignedBothEmptyString.json"); + Assert.Throws(delegate { SystemAssignedIdentity.Deserialize(identityJsonProperty.Value); }); + } + + [TestCase] + public void TestDeserializerOneEmptyString() + { + var identityJsonProperty = DeserializerHelper("SystemAssignedOneEmptyString.json"); + Assert.Throws(delegate { SystemAssignedIdentity.Deserialize(identityJsonProperty.Value); }); + } + + [TestCase] + public void TestDeserializerTenantIdValueNull() + { + var identityJsonProperty = DeserializerHelper("SystemAssignedOneValueNull.json"); + Assert.Throws(delegate { SystemAssignedIdentity.Deserialize(identityJsonProperty.Value); }); + } + + [TestCase] + public void TestDeserializerPrincipalIdValueNull() + { + var identityJsonProperty = DeserializerHelper("SystemAssignedOneOtherValueNull.json"); + Assert.Throws(delegate { SystemAssignedIdentity.Deserialize(identityJsonProperty.Value); }); + } + + [TestCase] + public void TestDeserializerTenantIdInvalid() + { + var identityJsonProperty = DeserializerHelper("SystemAssignedInvalid.json"); + Assert.Throws(delegate { SystemAssignedIdentity.Deserialize(identityJsonProperty.Value); }); + } + + [TestCase] + public void TestSerializerValidIdentity() + { + SystemAssignedIdentity systemAssignedIdentity = new SystemAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + string actual = ""; + using (Stream stream = new MemoryStream()) + { + using (StreamReader streamReader = new StreamReader(stream)) + { + var writer = new Utf8JsonWriter(stream); + writer.WriteStartObject(); + SystemAssignedIdentity.Serialize(writer, systemAssignedIdentity); + writer.WriteEndObject(); + writer.Flush(); + stream.Seek(0, SeekOrigin.Begin); + actual = streamReader.ReadToEnd(); + } + } + string expected = "{\"principalId\":\"de29bab1-49e1-4705-819b-4dfddceaaa98\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"}"; + Assert.AreEqual(expected, actual); + } + + [TestCase] + public void TestSerializerEmptyIdentity() + { + SystemAssignedIdentity systemAssignedIdentity = new SystemAssignedIdentity(); + string actual = ""; + using (Stream stream = new MemoryStream()) + { + using (StreamReader streamReader = new StreamReader(stream)) + { + var writer = new Utf8JsonWriter(stream); + writer.WriteStartObject(); + SystemAssignedIdentity.Serialize(writer, systemAssignedIdentity); + writer.WriteEndObject(); + writer.Flush(); + stream.Seek(0, SeekOrigin.Begin); + actual = streamReader.ReadToEnd(); + } + } + string expected = "{\"principalId\":\"null\",\"tenantId\":\"null\"}"; + Assert.AreEqual(expected, actual); + } + + [TestCase] + public void TestSerializerNullIdentity() + { + SystemAssignedIdentity systemAssignedIdentity = null; + using (Stream stream = new MemoryStream()) + { + var writer = new Utf8JsonWriter(stream); + writer.WriteStartObject(); + Assert.Throws(delegate { SystemAssignedIdentity.Serialize(writer, systemAssignedIdentity); }); + } + } + + [TestCase] + public void TestSerializerNullWriter() + { + SystemAssignedIdentity systemAssignedIdentity = new SystemAssignedIdentity(); + using (Stream stream = new MemoryStream()) + { + Assert.Throws(delegate { SystemAssignedIdentity.Serialize(null, systemAssignedIdentity); }); + } + } + + [TestCase] + public void TestEqualsBothIdentitiesNull() + { + SystemAssignedIdentity identity1 = null; + SystemAssignedIdentity identity2 = null; + Assert.IsTrue(SystemAssignedIdentity.Equals(identity1, identity2)); + } + + [TestCase] + public void TestEqualsOneIdentityNull() + { + SystemAssignedIdentity identity1 = null; + SystemAssignedIdentity identity2 = new SystemAssignedIdentity(); + Assert.IsFalse(SystemAssignedIdentity.Equals(identity1, identity2)); + } + + [TestCase] + public void TestEqualsOtherIdentityNull() + { + SystemAssignedIdentity identity1 = new SystemAssignedIdentity(); + SystemAssignedIdentity identity2 = null; + Assert.IsFalse(SystemAssignedIdentity.Equals(identity1, identity2)); + } + + [TestCase] + public void TestEqualsReference() + { + SystemAssignedIdentity identity1 = new SystemAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + SystemAssignedIdentity identity2 = identity1; + Assert.IsTrue(SystemAssignedIdentity.Equals(identity1, identity2)); + } + + [TestCase] + public void TestEqualsTrue() + { + SystemAssignedIdentity identity1 = new SystemAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + SystemAssignedIdentity identity2 = new SystemAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + Assert.IsTrue(SystemAssignedIdentity.Equals(identity1, identity2)); + } + + [TestCase] + public void TestEqualsFalse() + { + SystemAssignedIdentity identity1 = new SystemAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + SystemAssignedIdentity identity2 = new SystemAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db42"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + Assert.IsFalse(SystemAssignedIdentity.Equals(identity1, identity2)); + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TaggableResourceTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TaggableResourceTests.cs new file mode 100644 index 0000000000000..028930db4fbbd --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TaggableResourceTests.cs @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using NUnit.Framework; + +namespace Azure.ResourceManager.Core.Tests +{ + [Ignore("Will remove after ADO 5122")] + [TestFixture] + public class TaggableResourceTests + { + private static readonly IDictionary UpdateTags = new Dictionary { { "UpdateKey1", "UpdateValue1" }, { "UpdateKey2", "UpdateValue2" } }; + private static readonly IDictionary OriTags = new Dictionary { { "key1", "value1" }, { "key2", "value2" } }; + + private ResourceGroup _rg; + + [SetUp] + public void GlobalSetUp() + { + var armClient = new AzureResourceManagerClient(); + _rg = armClient.DefaultSubscription.GetResourceGroupContainer().Construct(LocationData.WestUS2).CreateOrUpdate($"{Environment.UserName}-rg-{Environment.TickCount}").Value; + + _rg = _rg.AddTag("key1", "value1"); + _rg = _rg.AddTag("key2", "value2"); + } + + [TearDown] + public void GlobalTearDown() + { + _rg.StartDelete(); + } + + [Test] + public void TestSetTagsActivator() + { + var result = _rg.SetTags(UpdateTags); + Assert.AreEqual(result.Value.Data.Tags, UpdateTags); + } + + [Test] + public async Task TestSetTagsAsyncActivator() + { + var result = await _rg.SetTagsAsync(UpdateTags); + Assert.AreEqual(result.Value.Data.Tags, UpdateTags); + } + + [Test] + public void TestStartSetTagsActivator() + { + var result = _rg.StartSetTags(UpdateTags).WaitForCompletionAsync().Result; + Assert.AreEqual(result.Value.Data.Tags, UpdateTags); + } + + [Test] + public async Task TestStartSetTagsAsyncActivator() + { + var result = await _rg.StartSetTagsAsync(UpdateTags); + Assert.AreEqual(result.Value.Data.Tags, UpdateTags); + } + + [TestCaseSource(nameof(TagSource))] + public void TestRemoveTagActivator(string key, IDictionary tags) + { + var result = _rg.RemoveTag(key); + Assert.AreEqual(result.Value.Data.Tags, tags); + } + + [TestCaseSource(nameof(TagSource))] + public async Task TestRemoveTagAsyncActivator(string key, IDictionary tags) + { + var result = await _rg.RemoveTagAsync(key); + Assert.AreEqual(result.Value.Data.Tags, tags); + } + + [TestCaseSource(nameof(TagSource))] + public void TestStartRemoveTagActivator(string key, IDictionary tags) + { + var result = _rg.StartRemoveTag(key).WaitForCompletionAsync().Result; + Assert.AreEqual(result.Value.Data.Tags, tags); + } + + [TestCaseSource(nameof(TagSource))] + public async Task TestStartRemoveTagAsyncActivator(string key, IDictionary tags) + { + var result = await _rg.StartRemoveTagAsync(key); + Assert.AreEqual(result.Value.Data.Tags, tags); + } + + static IEnumerable TagSource() + { + IDictionary OriKey1 = new Dictionary { { "key1", "value1" } }; + IDictionary OriKey2 = new Dictionary { { "key2", "value2" } }; + + return new[] { new object[] {"key1", OriKey2 }, + new object[] {"key2", OriKey1 }, + new object[] {"NullKey", OriTags } + }; + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/InvalidType.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/InvalidType.json new file mode 100644 index 0000000000000..88dc49b9af0e7 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/InvalidType.json @@ -0,0 +1,13 @@ +{ + "identity": { + "principalId": "22fddec1-8b9f-49dc-bd72-ddaf8f215577", + "tenantId": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "type": "Test", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-tgds-930e-01e2ef9c123c/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": "9a2eaa6a-b49c-4a63-afb5-3b72e3e65422", + "principalId": "77563a98-c9d9-4f7b-a7af-592d21fa2153" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/InvalidTypeIsNull.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/InvalidTypeIsNull.json new file mode 100644 index 0000000000000..2fd197d51a488 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/InvalidTypeIsNull.json @@ -0,0 +1,13 @@ +{ + "identity": { + "principalId": "22fddec1-8a9f-49dc-bd72-ddaf8f215577", + "tenantId": "72f988bf-86f1-4aaf-91ab-2d7cd011db47", + "type": null, + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c1b3c/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": "9a2eaa6a-b4ac-4c63-afb5-3b72e3e65422", + "principalId": "77563a98-c9a9-477b-a7af-592d21fa2153" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedInnerExtraField.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedInnerExtraField.json new file mode 100644 index 0000000000000..ccdfa20449ddc --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedInnerExtraField.json @@ -0,0 +1,14 @@ +{ + "identity": { + "extraId" : "test", + "principalId": "22fddec1-8b9f-49dc-bd72-ddaf8f215577", + "tenantId": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "type": "SystemAssigned, UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b27-9dde-01e2ef9c123c/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": "9a9eaa6a-b49c-4c63-afb5-3b72e3e65422", + "principalId": "77563a98-c9d9-407b-a7af-592d21fa2153" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedMiddleExtraField.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedMiddleExtraField.json new file mode 100644 index 0000000000000..25bd5585dfdf8 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedMiddleExtraField.json @@ -0,0 +1,14 @@ +{ + "identity": { + "principalId": "22fddec1-8b9f-49dc-bd72-ddaf8f215577", + "extraId": "test", + "tenantId": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "type": "SystemAssigned, UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b27-9dde-01e2ef9c123c/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": "9a9eaa6a-b49c-4c63-afb5-3b72e3e65422", + "principalId": "77563a98-c9d9-407b-a7af-592d21fa2153" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedOuterExtraField.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedOuterExtraField.json new file mode 100644 index 0000000000000..9a61e21026640 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedOuterExtraField.json @@ -0,0 +1,14 @@ +{ + "principalId": "test", + "identity": { + "principalId": "22fddec1-8b9f-49dc-bd72-ddaf8f215577", + "tenantId": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "type": "SystemAssigned, UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-3466-4b27-930e-01e2ef9c123c/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": "9a2eaa6b-b49c-4c63-afb5-3b72e3e65422", + "principalId": "7756fa98-c9d9-477b-a7af-592d21fa2153" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedValid.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedValid.json new file mode 100644 index 0000000000000..c9207ff65a275 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedValid.json @@ -0,0 +1,13 @@ +{ + "identity": { + "principalId": "22fdaec1-8b9f-49dc-bd72-ddaf8f215577", + "tenantId": "72f988af-86f1-41af-91ab-2d7cd011db47", + "type": "SystemAssigned, UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4aa7-930e-01e2ef9c123c/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": "9a9eaa6a-b49c-4c63-afb5-3b72e3e65422", + "principalId": "77563a98-c9d9-407b-a7af-592d21fa2153" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedValidMultIdentities.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedValidMultIdentities.json new file mode 100644 index 0000000000000..660ab014dee52 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAndUserAssignedValidMultIdentities.json @@ -0,0 +1,17 @@ +{ + "identity": { + "principalId": "22fddec1-8b9f-49dc-bd72-ddaf8f215570", + "tenantId": "72f988bf-86f1-41af-91ab-2d7cd011db40", + "type": "SystemAssigned, UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123z/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity0": { + "clientId": "9a2eaa6a-b49c-4c63-afb5-3b72e3e65422", + "principalId": "77563a98-c9d9-477b-a7af-592d21fa2153" + }, + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9cfrgh/resourceGroups/tester/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity1": { + "clientId": "9a2eaa6a-b49c-4c63-afb5-3b72e3c65420", + "principalId": "77563a98-c9d9-477b-a7af-592d2bfa2150" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAssigned.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAssigned.json new file mode 100644 index 0000000000000..fed8ac668cf44 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/SystemAssigned.json @@ -0,0 +1,8 @@ +{ + "identity": { + "principalId": "22fddec1-8b9f-49dc-bd72-ddaf8f215577", + "tenantId": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "type": "SystemAssigned", + "userAssignedIdentities": null + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/UserAssigned.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/UserAssigned.json new file mode 100644 index 0000000000000..52a51e50116db --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/Identity/UserAssigned.json @@ -0,0 +1,13 @@ +{ + "identity": { + "principalId": null, + "tenantId": null, + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b2e-930e-01e2ef9c123c/resourceGroups/tester-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": "9a2eaa6a-b49c-4c63-afb5-3b72e3e65422", + "principalId": "77563a98-c9d9-477b-a7af-592d21fa2153" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedBothEmptyString.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedBothEmptyString.json new file mode 100644 index 0000000000000..dfc0a251aeb09 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedBothEmptyString.json @@ -0,0 +1,8 @@ +{ + "identity": { + "principalId": "", + "tenantId": "", + "type": "SystemAssigned", + "userAssignedIdentities": null + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedBothValuesNull.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedBothValuesNull.json new file mode 100644 index 0000000000000..56b0ab1a0c603 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedBothValuesNull.json @@ -0,0 +1,8 @@ +{ + "identity": { + "principalId": null, + "tenantId": null, + "type": "SystemAssigned", + "userAssignedIdentities": null + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedInvalid.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedInvalid.json new file mode 100644 index 0000000000000..bb1568a93322e --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedInvalid.json @@ -0,0 +1,8 @@ +{ + "identity": { + "principalId": "de29bab1-49e1-4705-819b-4dfddceaaa98", + "tenantId": 7, + "type": "SystemAssigned", + "userAssignedIdentities": null + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedOneEmptyString.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedOneEmptyString.json new file mode 100644 index 0000000000000..b348a6fc02d35 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedOneEmptyString.json @@ -0,0 +1,8 @@ +{ + "identity": { + "principalId": "", + "tenantId": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "type": "SystemAssigned", + "userAssignedIdentities": null + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedOneOtherValueNull.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedOneOtherValueNull.json new file mode 100644 index 0000000000000..9b5883ae8b68d --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedOneOtherValueNull.json @@ -0,0 +1,8 @@ +{ + "identity": { + "principalId": null, + "tenantId": "de29bab1-49e1-4705-819b-4dfddceaaa98", + "type": "SystemAssigned", + "userAssignedIdentities": null + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedOneValueNull.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedOneValueNull.json new file mode 100644 index 0000000000000..a8edb93db9e50 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedOneValueNull.json @@ -0,0 +1,8 @@ +{ + "identity": { + "principalId": "de29bab1-49e1-4705-819b-4dfddceaaa98", + "tenantId": null, + "type": "SystemAssigned", + "userAssignedIdentities": null + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedValid.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedValid.json new file mode 100644 index 0000000000000..3262885a1d5d1 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedValid.json @@ -0,0 +1,8 @@ +{ + "identity": { + "principalId": "de29bab1-49e1-4705-819b-4dfddceaaa98", + "tenantId": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "type": "SystemAssigned", + "userAssignedIdentities": null + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedValidExtraField.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedValidExtraField.json new file mode 100644 index 0000000000000..752dd9b5788aa --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/SystemAssignedIdentity/SystemAssignedValidExtraField.json @@ -0,0 +1,9 @@ +{ + "principalId": "test", + "identity": { + "principalId": "de29bab1-49e1-4705-819b-4dfddceaaa98", + "tenantId": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "type": "SystemAssigned", + "userAssignedIdentities": null + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedBothEmptyString.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedBothEmptyString.json new file mode 100644 index 0000000000000..4129138735a05 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedBothEmptyString.json @@ -0,0 +1,13 @@ +{ + "identity": { + "principalId": null, + "tenantId": null, + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/nbhatia-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": "", + "principalId": "" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedBothValuesNull.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedBothValuesNull.json new file mode 100644 index 0000000000000..d746769930593 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedBothValuesNull.json @@ -0,0 +1,13 @@ +{ + "identity": { + "principalId": null, + "tenantId": null, + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/nbhatia-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": null, + "principalId": null + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedExtraField.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedExtraField.json new file mode 100644 index 0000000000000..a197f59551fcf --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedExtraField.json @@ -0,0 +1,14 @@ +{ + "identity": { + "principalId": null, + "tenantId": null, + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/nbhatia-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "tenantId": "3beb288c-c3f9-4300-896f-02fbf175b7he", + "clientId": "3beb288c-c3f9-4300-896f-02fbf175b6be", + "principalId": "d0416856-d6cf-466d-8d64-ddc8d7782096" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedInvalid.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedInvalid.json new file mode 100644 index 0000000000000..a3c6a3509f798 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedInvalid.json @@ -0,0 +1,13 @@ +{ + "identity": { + "principalId": null, + "tenantId": null, + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/nbhatia-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": 6, + "principalId": "3beb288c-c3f9-4300-896f-02fbf175b6be" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedInvalidMultipleIdentities.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedInvalidMultipleIdentities.json new file mode 100644 index 0000000000000..001a5e7a6d1fe --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedInvalidMultipleIdentities.json @@ -0,0 +1,17 @@ +{ + "identity": { + "principalId": null, + "tenantId": null, + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/nbhatia-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": 7, + "principalId": "d0416856-d6cf-466d-8d64-ddc8d7782096" + }, + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/nbhatia-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity2": { + "clientId": "3beb288c-c3f9-4300-896f-02fbf175b6be", + "principalId": 23 + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedOneEmptyString.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedOneEmptyString.json new file mode 100644 index 0000000000000..1604f0a36c4e8 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedOneEmptyString.json @@ -0,0 +1,13 @@ +{ + "identity": { + "principalId": null, + "tenantId": null, + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/nbhatia-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": "3beb288c-c3f9-4300-896f-02fbf175b6be", + "principalId": "" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedOneOtherValueNull.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedOneOtherValueNull.json new file mode 100644 index 0000000000000..371903d0cd5a7 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedOneOtherValueNull.json @@ -0,0 +1,13 @@ +{ + "identity": { + "principalId": null, + "tenantId": null, + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/nbhatia-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": "3beb288c-c3f9-4300-896f-02fbf175b6be", + "principalId": null + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedOneValueNull.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedOneValueNull.json new file mode 100644 index 0000000000000..1764f6db7b300 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedOneValueNull.json @@ -0,0 +1,13 @@ +{ + "identity": { + "principalId": null, + "tenantId": null, + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/nbhatia-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": null, + "principalId": "3beb288c-c3f9-4300-896f-02fbf175b6be" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedValid.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedValid.json new file mode 100644 index 0000000000000..be76c83688258 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedValid.json @@ -0,0 +1,13 @@ +{ + "identity": { + "principalId": null, + "tenantId": null, + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/nbhatia-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": "3beb288c-c3f9-4300-896f-02fbf175b6be", + "principalId": "d0416856-d6cf-466d-8d64-ddc8d7782096" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedValidMultipleIdentities.json b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedValidMultipleIdentities.json new file mode 100644 index 0000000000000..1c532e9c3ee89 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/TestAssets/UserAssignedIdentity/UserAssignedValidMultipleIdentities.json @@ -0,0 +1,17 @@ +{ + "identity": { + "principalId": null, + "tenantId": null, + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/nbhatia-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity": { + "clientId": "3beb288c-c3f9-4300-896f-02fbf175b6be", + "principalId": "d0416856-d6cf-466d-8d64-ddc8d7782096" + }, + "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/nbhatia-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity2": { + "clientId": "fbb39377-ff46-4a82-8c47-42d573180482", + "principalId": "6d63ce43-c3ac-4b03-933d-4bc31eae50b2" + } + } + } +} diff --git a/sdk/resourcemanager/Azure.ResourceManager.Core/tests/UserAssignedIdentityTests.cs b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/UserAssignedIdentityTests.cs new file mode 100644 index 0000000000000..c1ac70ce053d1 --- /dev/null +++ b/sdk/resourcemanager/Azure.ResourceManager.Core/tests/UserAssignedIdentityTests.cs @@ -0,0 +1,315 @@ +using NUnit.Framework; +using System; +using System.IO; +using System.Linq; +using System.Text.Json; + +namespace Azure.ResourceManager.Core.Tests +{ + public class UserAssignedIdentityTests + { + [TestCase(0, "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + + [TestCase(1, "72f988bf-86f1-41af-91ab-2d7cd011db48", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + [TestCase(1, "72f988bf-86f1-41af-91ab-2d7cd011db48", "de29bab1-49e1-4705-819b-4dfddceaaa97", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + [TestCase(1, "72f988bf-86f1-41af-91ab-2d7cd011db48", "de29bab1-49e1-4705-819b-4dfddceaaa99", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + [TestCase(1, "72f988bf-86f1-41af-91ab-2d7cd011eb47", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + + [TestCase(-1, "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db48", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + [TestCase(-1, "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db48", "de29bab1-49e1-4705-819b-4dfddceaaa99")] + [TestCase(-1, "72f988bf-86f1-41af-91ab-2d7cd011db46", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db48", "de29bab1-49e1-4705-819b-4dfddceaaa97")] + [TestCase(-1, "72f988bf-86f1-41af-91ab-2d7cd011db46", "de29bab1-49e1-4705-819b-4dfdbceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db46", "de29bab1-49e1-4705-819b-4dfddceaaa99")] + public void CompareTo(int answer, string clientId1, string principalId1, string clientId2, string principalId2) + { + UserAssignedIdentity identity1 = new UserAssignedIdentity(new Guid(clientId1), new Guid(principalId1)); + UserAssignedIdentity identity2 = new UserAssignedIdentity(new Guid(clientId2), new Guid(principalId2)); + + Assert.AreEqual(answer, identity1.CompareTo(identity2)); + Assert.AreEqual(answer * -1, identity2.CompareTo(identity1)); + } + + [TestCase("72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98")] + public void EqualsMethodTrue(string clientId1, string principalId1, string clientId2, string principalId2) + { + UserAssignedIdentity identity1 = new UserAssignedIdentity(new Guid(clientId1), new Guid(principalId1)); + UserAssignedIdentity identity2 = new UserAssignedIdentity(new Guid(clientId2), new Guid(principalId2)); + Assert.IsTrue(identity1.Equals(identity2)); + } + + [TestCase("72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa98", "72f988bf-86f1-41af-91ab-2d7cd011db44", "de29bab1-49e1-4705-819b-4dfddceaaa94")] + [TestCase("72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa93", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa91")] + [TestCase("72f988bf-86f1-41af-91ab-2d7cd011db49", "de29bab1-49e1-4705-819b-4dfddceaaa91", "72f988bf-86f1-41af-91ab-2d7cd011db47", "de29bab1-49e1-4705-819b-4dfddceaaa91")] + public void EqualsMethodFalse(string clientId1, string principalId1, string clientId2, string principalId2) + { + UserAssignedIdentity identity1 = new UserAssignedIdentity(new Guid(clientId1), new Guid(principalId1)); + UserAssignedIdentity identity2 = new UserAssignedIdentity(new Guid(clientId2), new Guid(principalId2)); + Assert.IsFalse(identity1.Equals(identity2)); + } + + [TestCase] + public void EqualsMethodOneIdentityNull() + { + UserAssignedIdentity identity1 = new UserAssignedIdentity(Guid.Empty, Guid.Empty); + UserAssignedIdentity identity2 = null; + Assert.IsFalse(identity1.Equals(identity2)); + } + + [TestCase] + public void CompareToMethodOneIdentityNull() + { + UserAssignedIdentity identity1 = new UserAssignedIdentity(Guid.Empty, Guid.Empty); + UserAssignedIdentity identity2 = null; + Assert.AreEqual(1, identity1.CompareTo(identity2)); + } + + public JsonElement DeserializerHelper(string filename) + { + var json = GetFileText(filename); + JsonDocument document = JsonDocument.Parse(json); + JsonElement rootElement = document.RootElement; + var properties = rootElement.EnumerateObject().First().Value; + foreach (var property in properties.EnumerateObject()) + { + if (property.NameEquals("userAssignedIdentities")) + { + foreach (var keyValuePair in property.Value.EnumerateObject()) + { + return keyValuePair.Value; + } + } + } + return default(JsonElement); + } + + private static string GetFileText(string filename) + { + return File.ReadAllText(Path.Combine(TestContext.CurrentContext.TestDirectory, "TestAssets", "UserAssignedIdentity", filename)); + } + + [TestCase] + public void TestDeserializerDefaultJson() + { + JsonElement invalid = default(JsonElement); + Assert.Throws(delegate { UserAssignedIdentity.Deserialize(invalid); }); + } + + [TestCase] + public void TestDeserializerValid() + { + var identityJsonProperty = DeserializerHelper("UserAssignedValid.json"); + UserAssignedIdentity back = UserAssignedIdentity.Deserialize(identityJsonProperty); + Assert.IsTrue("3beb288c-c3f9-4300-896f-02fbf175b6be".Equals(back.ClientId.ToString())); + Assert.IsTrue("d0416856-d6cf-466d-8d64-ddc8d7782096".Equals(back.PrincipalId.ToString())); + } + + [TestCase] + public void TestDeserializerValidExtraField() + { + var identityJsonProperty = DeserializerHelper("UserAssignedExtraField.json"); + UserAssignedIdentity back = UserAssignedIdentity.Deserialize(identityJsonProperty); + Assert.IsTrue("3beb288c-c3f9-4300-896f-02fbf175b6be".Equals(back.ClientId.ToString())); + Assert.IsTrue("d0416856-d6cf-466d-8d64-ddc8d7782096".Equals(back.PrincipalId.ToString())); + } + + [TestCase] + public void TestDeserializerBothValuesNull() + { + var identityJsonProperty = DeserializerHelper("UserAssignedBothValuesNull.json"); + var back = UserAssignedIdentity.Deserialize(identityJsonProperty); + Assert.IsNull(back); + } + + [TestCase] + public void TestDeserializerBothEmptyString() + { + var identityJsonProperty = DeserializerHelper("UserAssignedBothEmptyString.json"); + Assert.Throws(delegate { UserAssignedIdentity.Deserialize(identityJsonProperty); }); + } + + [TestCase] + public void TestDeserializerOneEmptyString() + { + var identityJsonProperty = DeserializerHelper("UserAssignedOneEmptyString.json"); + Assert.Throws(delegate { UserAssignedIdentity.Deserialize(identityJsonProperty); }); + } + + [TestCase] + public void TestDeserializerClientIdValueNull() + { + var identityJsonProperty = DeserializerHelper("UserAssignedOneValueNull.json"); + Assert.Throws(delegate { UserAssignedIdentity.Deserialize(identityJsonProperty); }); + } + + [TestCase] + public void TestDeserializerPrincipalIdValueNull() + { + var identityJsonProperty = DeserializerHelper("UserAssignedOneOtherValueNull.json"); + Assert.Throws(delegate { UserAssignedIdentity.Deserialize(identityJsonProperty); }); + } + + [TestCase] + public void TestDeserializerClientIdInvalid() + { + var identityJsonProperty = DeserializerHelper("UserAssignedInvalid.json"); + Assert.Throws(delegate { UserAssignedIdentity.Deserialize(identityJsonProperty); }); + } + + [TestCase] + public void TestDeserializerInvalidMultipleIdentities() + { + var json = GetFileText("UserAssignedInvalidMultipleIdentities.json"); + JsonDocument document = JsonDocument.Parse(json); + var properties = document.RootElement.EnumerateObject().First().Value; + foreach (var property in properties.EnumerateObject()) + { + if (property.NameEquals("userAssignedIdentities")) + { + foreach (var keyValuePair in property.Value.EnumerateObject()) + { + Assert.Throws(delegate { UserAssignedIdentity.Deserialize(keyValuePair.Value); }); + } + } + } + } + + [TestCase] + public void TestDeserializerValidMultipleIdentities() + { + var json = GetFileText("UserAssignedValidMultipleIdentities.json"); + JsonDocument document = JsonDocument.Parse(json); + UserAssignedIdentity[] identities = new UserAssignedIdentity[2]; + var properties = document.RootElement.EnumerateObject().First().Value; + int count = 0; + foreach (var property in properties.EnumerateObject()) + { + if (property.NameEquals("userAssignedIdentities")) + { + foreach (var keyValuePair in property.Value.EnumerateObject()) + { + identities[count] = UserAssignedIdentity.Deserialize(keyValuePair.Value); + count++; + } + } + } + Assert.IsTrue("3beb288c-c3f9-4300-896f-02fbf175b6be".Equals(identities[0].ClientId.ToString())); + Assert.IsTrue("d0416856-d6cf-466d-8d64-ddc8d7782096".Equals(identities[0].PrincipalId.ToString())); + Assert.IsTrue("fbb39377-ff46-4a82-8c47-42d573180482".Equals(identities[1].ClientId.ToString())); + Assert.IsTrue("6d63ce43-c3ac-4b03-933d-4bc31eae50b2".Equals(identities[1].PrincipalId.ToString())); + } + + [TestCase] + public void TestSerializerValidIdentity() + { + UserAssignedIdentity userAssignedIdentity = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + string actual = ""; + using (Stream stream = new MemoryStream()) + { + using (StreamReader streamReader = new StreamReader(stream)) + { + var writer = new Utf8JsonWriter(stream); + UserAssignedIdentity.Serialize(writer, userAssignedIdentity); + stream.Seek(0, SeekOrigin.Begin); + actual = streamReader.ReadToEnd(); + } + } + string expected = "{\"clientId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\",\"principalId\":\"de29bab1-49e1-4705-819b-4dfddceaaa98\"}"; + Assert.AreEqual(expected, actual); + } + + [TestCase] + public void TestSerializerNullIdentity() + { + UserAssignedIdentity userAssignedIdentity = null; + using (Stream stream = new MemoryStream()) + { + var writer = new Utf8JsonWriter(stream); + Assert.Throws(delegate { UserAssignedIdentity.Serialize(writer, userAssignedIdentity); }); + } + } + + [TestCase] + public void TestSerializerNullWriter() + { + UserAssignedIdentity userAssignedIdentity = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + using (Stream stream = new MemoryStream()) + { + Assert.Throws(delegate { UserAssignedIdentity.Serialize(null, userAssignedIdentity); }); + } + } + + [TestCase] + public void TestSerializerArray() + { + UserAssignedIdentity userAssignedIdentity1 = new UserAssignedIdentity(new Guid("3beb288c-c3f9-4300-896f-02fbf175b6be"), new Guid("d0416856-d6cf-466d-8d64-ddc8d7782096")); + UserAssignedIdentity userAssignedIdentity2 = new UserAssignedIdentity(new Guid("fbb39377-ff46-4a82-8c47-42d573180482"), new Guid("6d63ce43-c3ac-4b03-933d-4bc31eae50b2")); + string actual = ""; + UserAssignedIdentity[] identities = { userAssignedIdentity1, userAssignedIdentity2 }; + using (Stream stream = new MemoryStream()) + { + using (StreamReader streamReader = new StreamReader(stream)) + { + foreach (var identity in identities) + { + var writer = new Utf8JsonWriter(stream); + UserAssignedIdentity.Serialize(writer, identity); + stream.Seek(0, SeekOrigin.Begin); + actual = streamReader.ReadToEnd(); + } + } + } + string expected = "{\"clientId\":\"3beb288c-c3f9-4300-896f-02fbf175b6be\"," + + "\"principalId\":\"d0416856-d6cf-466d-8d64-ddc8d7782096\"}" + + "{\"clientId\":\"fbb39377-ff46-4a82-8c47-42d573180482\"," + + "\"principalId\":\"6d63ce43-c3ac-4b03-933d-4bc31eae50b2\"}"; + Assert.AreEqual(expected, actual); + } + + [TestCase] + public void TestEqualsBothIdentitiesNull() + { + UserAssignedIdentity identity1 = null; + UserAssignedIdentity identity2 = null; + Assert.IsTrue(UserAssignedIdentity.Equals(identity1, identity2)); + } + + [TestCase] + public void TestEqualsOneIdentityNull() + { + UserAssignedIdentity identity1 = null; + UserAssignedIdentity identity2 = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + Assert.IsFalse(UserAssignedIdentity.Equals(identity1, identity2)); + } + + [TestCase] + public void TestEqualsOtherIdentityNull() + { + UserAssignedIdentity identity1 = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + UserAssignedIdentity identity2 = null; + Assert.IsFalse(UserAssignedIdentity.Equals(identity1, identity2)); + } + + [TestCase] + public void TestEqualsReference() + { + UserAssignedIdentity identity1 = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + UserAssignedIdentity identity2 = identity1; + Assert.IsTrue(UserAssignedIdentity.Equals(identity1, identity2)); + } + + [TestCase] + public void TestEqualsTrue() + { + UserAssignedIdentity identity1 = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + UserAssignedIdentity identity2 = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + Assert.IsTrue(UserAssignedIdentity.Equals(identity1, identity2)); + } + + [TestCase] + public void TestEqualsFalse() + { + UserAssignedIdentity identity1 = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db47"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + UserAssignedIdentity identity2 = new UserAssignedIdentity(new Guid("72f988bf-86f1-41af-91ab-2d7cd011db42"), new Guid("de29bab1-49e1-4705-819b-4dfddceaaa98")); + Assert.IsFalse(UserAssignedIdentity.Equals(identity1, identity2)); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/Proto.Client.sln b/sdk/resourcemanager/Proto.Client/Proto.Client.sln new file mode 100644 index 0000000000000..0d78ec9861053 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/Proto.Client.sln @@ -0,0 +1,55 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.31019.35 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.ResourceManager.Core", "..\Azure.ResourceManager.Core\src\Azure.ResourceManager.Core.csproj", "{AEBBB0DB-BA2F-42A2-85DD-0019EE64492B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Proto.Compute", "compute\Proto.Compute.csproj", "{8948E020-7C45-4817-9142-D80368F3FB11}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Proto.Network", "network\Proto.Network.csproj", "{AD152BEB-7AE0-42A1-873E-E2AB4519ADA7}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Proto.Client", "src\Proto.Client.csproj", "{280DD3C4-7EC6-471A-BB77-1E7F2F7D6666}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Proto.Authorization", "authorization\Proto.Authorization.csproj", "{540E8EF4-40B6-4F23-8744-2E6705186E7B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.ResourceManager.Authorization", "authorization\Azure.ResourceManager.Authorization\Azure.ResourceManager.Authorization.csproj", "{ADB32B3D-D6DE-49A3-80E1-59ADAA21F78F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AEBBB0DB-BA2F-42A2-85DD-0019EE64492B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AEBBB0DB-BA2F-42A2-85DD-0019EE64492B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AEBBB0DB-BA2F-42A2-85DD-0019EE64492B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AEBBB0DB-BA2F-42A2-85DD-0019EE64492B}.Release|Any CPU.Build.0 = Release|Any CPU + {8948E020-7C45-4817-9142-D80368F3FB11}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8948E020-7C45-4817-9142-D80368F3FB11}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8948E020-7C45-4817-9142-D80368F3FB11}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8948E020-7C45-4817-9142-D80368F3FB11}.Release|Any CPU.Build.0 = Release|Any CPU + {AD152BEB-7AE0-42A1-873E-E2AB4519ADA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AD152BEB-7AE0-42A1-873E-E2AB4519ADA7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AD152BEB-7AE0-42A1-873E-E2AB4519ADA7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AD152BEB-7AE0-42A1-873E-E2AB4519ADA7}.Release|Any CPU.Build.0 = Release|Any CPU + {280DD3C4-7EC6-471A-BB77-1E7F2F7D6666}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {280DD3C4-7EC6-471A-BB77-1E7F2F7D6666}.Debug|Any CPU.Build.0 = Debug|Any CPU + {280DD3C4-7EC6-471A-BB77-1E7F2F7D6666}.Release|Any CPU.ActiveCfg = Release|Any CPU + {280DD3C4-7EC6-471A-BB77-1E7F2F7D6666}.Release|Any CPU.Build.0 = Release|Any CPU + {540E8EF4-40B6-4F23-8744-2E6705186E7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {540E8EF4-40B6-4F23-8744-2E6705186E7B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {540E8EF4-40B6-4F23-8744-2E6705186E7B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {540E8EF4-40B6-4F23-8744-2E6705186E7B}.Release|Any CPU.Build.0 = Release|Any CPU + {ADB32B3D-D6DE-49A3-80E1-59ADAA21F78F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ADB32B3D-D6DE-49A3-80E1-59ADAA21F78F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ADB32B3D-D6DE-49A3-80E1-59ADAA21F78F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ADB32B3D-D6DE-49A3-80E1-59ADAA21F78F}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {6C3A85E2-78AD-4C82-8943-A495B3B42533} + EndGlobalSection +EndGlobal diff --git a/sdk/resourcemanager/Proto.Client/README.MD b/sdk/resourcemanager/Proto.Client/README.MD new file mode 100644 index 0000000000000..efeef3da2460c --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/README.MD @@ -0,0 +1,3 @@ +# Proto Client + +Client used to showcase and test the new prototype track 2 management plane SDK \ No newline at end of file diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Azure.ResourceManager.Authorization.csproj b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Azure.ResourceManager.Authorization.csproj new file mode 100644 index 0000000000000..00a1e88b84232 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Azure.ResourceManager.Authorization.csproj @@ -0,0 +1,13 @@ + + + 1.0.0-beta.1 + Azure.ResourceManager.Authorization + Azure Resource Manager client SDK for Azure resource provider Microsoft.Authorization + azure;management;arm;resource manager;authorization + + + + + $(NoWarn);AZC0001 + + diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Directory.Build.props b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Directory.Build.props new file mode 100644 index 0000000000000..1a9611bd49242 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Directory.Build.props @@ -0,0 +1,6 @@ + + + + diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/AuthorizationManagementClient.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/AuthorizationManagementClient.cs new file mode 100644 index 0000000000000..0332b8b67e2b0 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/AuthorizationManagementClient.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; +using Azure.Core.Pipeline; +using Azure.ResourceManager.Authorization; + +namespace Azure.ResourceManager.Authorization +{ + /// Authorization service management client. + public partial class AuthorizationManagementClient + { + private readonly ClientDiagnostics _clientDiagnostics; + private readonly HttpPipeline _pipeline; + private readonly string _subscriptionId; + private readonly Uri _endpoint; + + /// Initializes a new instance of AuthorizationManagementClient for mocking. + protected AuthorizationManagementClient() + { + } + + /// Initializes a new instance of AuthorizationManagementClient. + /// The ID of the target subscription. + /// The OAuth token for making client requests. + /// The options for configuring the client. + public AuthorizationManagementClient(string subscriptionId, TokenCredential tokenCredential, AuthorizationManagementClientOptions options = null) : this(subscriptionId, null, tokenCredential, options) + { + } + /// Initializes a new instance of AuthorizationManagementClient. + /// The ID of the target subscription. + /// server parameter. + /// The OAuth token for making client requests. + /// The options for configuring the client. + /// is null. + public AuthorizationManagementClient(string subscriptionId, Uri endpoint, TokenCredential tokenCredential, AuthorizationManagementClientOptions options = null) + { + if (subscriptionId == null) + { + throw new ArgumentNullException(nameof(subscriptionId)); + } + endpoint ??= new Uri("https://management.azure.com"); + + options ??= new AuthorizationManagementClientOptions(); + _clientDiagnostics = new ClientDiagnostics(options); + _pipeline = ManagementPipelineBuilder.Build(tokenCredential, endpoint, options); + _subscriptionId = subscriptionId; + _endpoint = endpoint; + } + + /// Returns an instance of RoleAssignmentsOperations. + public virtual RoleAssignmentsOperations RoleAssignments => new RoleAssignmentsOperations(_clientDiagnostics, _pipeline, _subscriptionId, _endpoint); + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/AuthorizationManagementClientOptions.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/AuthorizationManagementClientOptions.cs new file mode 100644 index 0000000000000..890946048a0b9 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/AuthorizationManagementClientOptions.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using Azure.Core; + +namespace Azure.ResourceManager.Authorization +{ + /// Client options for Authorization. + public partial class AuthorizationManagementClientOptions : ClientOptions + { + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorAdditionalInfo.Serialization.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorAdditionalInfo.Serialization.cs new file mode 100644 index 0000000000000..2186871caceca --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorAdditionalInfo.Serialization.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Authorization.Models +{ + internal partial class ErrorAdditionalInfo + { + internal static ErrorAdditionalInfo DeserializeErrorAdditionalInfo(JsonElement element) + { + Optional type = default; + Optional info = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type")) + { + type = property.Value.GetString(); + continue; + } + if (property.NameEquals("info")) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + property.ThrowNonNullablePropertyIsNull(); + continue; + } + info = property.Value.GetObject(); + continue; + } + } + return new ErrorAdditionalInfo(type.Value, info.Value); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorAdditionalInfo.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorAdditionalInfo.cs new file mode 100644 index 0000000000000..0dd0396180f6d --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorAdditionalInfo.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +namespace Azure.ResourceManager.Authorization.Models +{ + /// The resource management error additional info. + internal partial class ErrorAdditionalInfo + { + /// Initializes a new instance of ErrorAdditionalInfo. + internal ErrorAdditionalInfo() + { + } + + /// Initializes a new instance of ErrorAdditionalInfo. + /// The additional info type. + /// The additional info. + internal ErrorAdditionalInfo(string type, object info) + { + Type = type; + Info = info; + } + + /// The additional info type. + public string Type { get; } + /// The additional info. + public object Info { get; } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorDetail.Serialization.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorDetail.Serialization.cs new file mode 100644 index 0000000000000..536d7bed4ad88 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorDetail.Serialization.cs @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Authorization.Models +{ + internal partial class ErrorDetail + { + internal static ErrorDetail DeserializeErrorDetail(JsonElement element) + { + Optional code = default; + Optional message = default; + Optional target = default; + Optional> details = default; + Optional> additionalInfo = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code")) + { + code = property.Value.GetString(); + continue; + } + if (property.NameEquals("message")) + { + message = property.Value.GetString(); + continue; + } + if (property.NameEquals("target")) + { + target = property.Value.GetString(); + continue; + } + if (property.NameEquals("details")) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + property.ThrowNonNullablePropertyIsNull(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(DeserializeErrorDetail(item)); + } + details = array; + continue; + } + if (property.NameEquals("additionalInfo")) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + property.ThrowNonNullablePropertyIsNull(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ErrorAdditionalInfo.DeserializeErrorAdditionalInfo(item)); + } + additionalInfo = array; + continue; + } + } + return new ErrorDetail(code.Value, message.Value, target.Value, Optional.ToList(details), Optional.ToList(additionalInfo)); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorDetail.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorDetail.cs new file mode 100644 index 0000000000000..eba350afafc44 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorDetail.cs @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using Azure.Core; + +namespace Azure.ResourceManager.Authorization.Models +{ + /// The error detail. + internal partial class ErrorDetail + { + /// Initializes a new instance of ErrorDetail. + internal ErrorDetail() + { + Details = new ChangeTrackingList(); + AdditionalInfo = new ChangeTrackingList(); + } + + /// Initializes a new instance of ErrorDetail. + /// The error code. + /// The error message. + /// The error target. + /// The error details. + /// The error additional info. + internal ErrorDetail(string code, string message, string target, IReadOnlyList details, IReadOnlyList additionalInfo) + { + Code = code; + Message = message; + Target = target; + Details = details; + AdditionalInfo = additionalInfo; + } + + /// The error code. + public string Code { get; } + /// The error message. + public string Message { get; } + /// The error target. + public string Target { get; } + /// The error details. + public IReadOnlyList Details { get; } + /// The error additional info. + public IReadOnlyList AdditionalInfo { get; } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorResponse.Serialization.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorResponse.Serialization.cs new file mode 100644 index 0000000000000..9db192f0f694a --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorResponse.Serialization.cs @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Authorization.Models +{ + internal partial class ErrorResponse + { + internal static ErrorResponse DeserializeErrorResponse(JsonElement element) + { + Optional error = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("error")) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + property.ThrowNonNullablePropertyIsNull(); + continue; + } + error = ErrorDetail.DeserializeErrorDetail(property.Value); + continue; + } + } + return new ErrorResponse(error.Value); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorResponse.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorResponse.cs new file mode 100644 index 0000000000000..fbe1ef13920e1 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/ErrorResponse.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +namespace Azure.ResourceManager.Authorization.Models +{ + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). + internal partial class ErrorResponse + { + /// Initializes a new instance of ErrorResponse. + internal ErrorResponse() + { + } + + /// Initializes a new instance of ErrorResponse. + /// The error object. + internal ErrorResponse(ErrorDetail error) + { + Error = error; + } + + /// The error object. + public ErrorDetail Error { get; } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/PrincipalType.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/PrincipalType.cs new file mode 100644 index 0000000000000..dd2733e32d45a --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/PrincipalType.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.Authorization.Models +{ + /// The principal type of the assigned principal ID. + public readonly partial struct PrincipalType : IEquatable + { + private readonly string _value; + + /// Determines if two values are the same. + /// is null. + public PrincipalType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UserValue = "User"; + private const string GroupValue = "Group"; + private const string ServicePrincipalValue = "ServicePrincipal"; + private const string UnknownValue = "Unknown"; + private const string DirectoryRoleTemplateValue = "DirectoryRoleTemplate"; + private const string ForeignGroupValue = "ForeignGroup"; + private const string ApplicationValue = "Application"; + private const string MSIValue = "MSI"; + private const string DirectoryObjectOrGroupValue = "DirectoryObjectOrGroup"; + private const string EveryoneValue = "Everyone"; + + /// User. + public static PrincipalType User { get; } = new PrincipalType(UserValue); + /// Group. + public static PrincipalType Group { get; } = new PrincipalType(GroupValue); + /// ServicePrincipal. + public static PrincipalType ServicePrincipal { get; } = new PrincipalType(ServicePrincipalValue); + /// Unknown. + public static PrincipalType Unknown { get; } = new PrincipalType(UnknownValue); + /// DirectoryRoleTemplate. + public static PrincipalType DirectoryRoleTemplate { get; } = new PrincipalType(DirectoryRoleTemplateValue); + /// ForeignGroup. + public static PrincipalType ForeignGroup { get; } = new PrincipalType(ForeignGroupValue); + /// Application. + public static PrincipalType Application { get; } = new PrincipalType(ApplicationValue); + /// MSI. + public static PrincipalType MSI { get; } = new PrincipalType(MSIValue); + /// DirectoryObjectOrGroup. + public static PrincipalType DirectoryObjectOrGroup { get; } = new PrincipalType(DirectoryObjectOrGroupValue); + /// Everyone. + public static PrincipalType Everyone { get; } = new PrincipalType(EveryoneValue); + /// Determines if two values are the same. + public static bool operator ==(PrincipalType left, PrincipalType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(PrincipalType left, PrincipalType right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator PrincipalType(string value) => new PrincipalType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is PrincipalType other && Equals(other); + /// + public bool Equals(PrincipalType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignment.Serialization.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignment.Serialization.cs new file mode 100644 index 0000000000000..ddb7e4809f65d --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignment.Serialization.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Authorization.Models +{ + public partial class RoleAssignment + { + internal static RoleAssignment DeserializeRoleAssignment(JsonElement element) + { + Optional id = default; + Optional name = default; + Optional type = default; + Optional scope = default; + Optional roleDefinitionId = default; + Optional principalId = default; + Optional principalType = default; + Optional canDelegate = default; + Optional description = default; + Optional condition = default; + Optional conditionVersion = default; + Optional createdOn = default; + Optional updatedOn = default; + Optional createdBy = default; + Optional updatedBy = default; + Optional delegatedManagedIdentityResourceId = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id")) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("name")) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("type")) + { + type = property.Value.GetString(); + continue; + } + if (property.NameEquals("properties")) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + property.ThrowNonNullablePropertyIsNull(); + continue; + } + foreach (var property0 in property.Value.EnumerateObject()) + { + if (property0.NameEquals("scope")) + { + scope = property0.Value.GetString(); + continue; + } + if (property0.NameEquals("roleDefinitionId")) + { + roleDefinitionId = property0.Value.GetString(); + continue; + } + if (property0.NameEquals("principalId")) + { + principalId = property0.Value.GetString(); + continue; + } + if (property0.NameEquals("principalType")) + { + if (property0.Value.ValueKind == JsonValueKind.Null) + { + property0.ThrowNonNullablePropertyIsNull(); + continue; + } + principalType = new PrincipalType(property0.Value.GetString()); + continue; + } + if (property0.NameEquals("canDelegate")) + { + if (property0.Value.ValueKind == JsonValueKind.Null) + { + property0.ThrowNonNullablePropertyIsNull(); + continue; + } + canDelegate = property0.Value.GetBoolean(); + continue; + } + if (property0.NameEquals("description")) + { + description = property0.Value.GetString(); + continue; + } + if (property0.NameEquals("condition")) + { + condition = property0.Value.GetString(); + continue; + } + if (property0.NameEquals("conditionVersion")) + { + conditionVersion = property0.Value.GetString(); + continue; + } + if (property0.NameEquals("createdOn")) + { + if (property0.Value.ValueKind == JsonValueKind.Null) + { + property0.ThrowNonNullablePropertyIsNull(); + continue; + } + createdOn = property0.Value.GetDateTimeOffset("O"); + continue; + } + if (property0.NameEquals("updatedOn")) + { + if (property0.Value.ValueKind == JsonValueKind.Null) + { + property0.ThrowNonNullablePropertyIsNull(); + continue; + } + updatedOn = property0.Value.GetDateTimeOffset("O"); + continue; + } + if (property0.NameEquals("createdBy")) + { + createdBy = property0.Value.GetString(); + continue; + } + if (property0.NameEquals("updatedBy")) + { + updatedBy = property0.Value.GetString(); + continue; + } + if (property0.NameEquals("delegatedManagedIdentityResourceId")) + { + delegatedManagedIdentityResourceId = property0.Value.GetString(); + continue; + } + } + continue; + } + } + return new RoleAssignment(id.Value, name.Value, type.Value, scope.Value, roleDefinitionId.Value, principalId.Value, Optional.ToNullable(principalType), Optional.ToNullable(canDelegate), description.Value, condition.Value, conditionVersion.Value, Optional.ToNullable(createdOn), Optional.ToNullable(updatedOn), createdBy.Value, updatedBy.Value, delegatedManagedIdentityResourceId.Value); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignment.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignment.cs new file mode 100644 index 0000000000000..dac8c754b295e --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignment.cs @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Azure.ResourceManager.Authorization.Models +{ + /// Role Assignments. + public partial class RoleAssignment + { + /// Initializes a new instance of RoleAssignment. + internal RoleAssignment() + { + } + + /// Initializes a new instance of RoleAssignment. + /// The role assignment ID. + /// The role assignment name. + /// The role assignment type. + /// The role assignment scope. + /// The role definition ID. + /// The principal ID. + /// The principal type of the assigned principal ID. + /// The Delegation flag for the role assignment. + /// Description of role assignment. + /// The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container'. + /// Version of the condition. Currently accepted value is '2.0'. + /// Time it was created. + /// Time it was updated. + /// Id of the user who created the assignment. + /// Id of the user who updated the assignment. + /// Id of the delegated managed identity resource. + internal RoleAssignment(string id, string name, string type, string scope, string roleDefinitionId, string principalId, PrincipalType? principalType, bool? canDelegate, string description, string condition, string conditionVersion, DateTimeOffset? createdOn, DateTimeOffset? updatedOn, string createdBy, string updatedBy, string delegatedManagedIdentityResourceId) + { + Id = id; + Name = name; + Type = type; + Scope = scope; + RoleDefinitionId = roleDefinitionId; + PrincipalId = principalId; + PrincipalType = principalType; + CanDelegate = canDelegate; + Description = description; + Condition = condition; + ConditionVersion = conditionVersion; + CreatedOn = createdOn; + UpdatedOn = updatedOn; + CreatedBy = createdBy; + UpdatedBy = updatedBy; + DelegatedManagedIdentityResourceId = delegatedManagedIdentityResourceId; + } + + /// The role assignment ID. + public string Id { get; } + /// The role assignment name. + public string Name { get; } + /// The role assignment type. + public string Type { get; } + /// The role assignment scope. + public string Scope { get; } + /// The role definition ID. + public string RoleDefinitionId { get; } + /// The principal ID. + public string PrincipalId { get; } + /// The principal type of the assigned principal ID. + public PrincipalType? PrincipalType { get; } + /// The Delegation flag for the role assignment. + public bool? CanDelegate { get; } + /// Description of role assignment. + public string Description { get; } + /// The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container'. + public string Condition { get; } + /// Version of the condition. Currently accepted value is '2.0'. + public string ConditionVersion { get; } + /// Time it was created. + public DateTimeOffset? CreatedOn { get; } + /// Time it was updated. + public DateTimeOffset? UpdatedOn { get; } + /// Id of the user who created the assignment. + public string CreatedBy { get; } + /// Id of the user who updated the assignment. + public string UpdatedBy { get; } + /// Id of the delegated managed identity resource. + public string DelegatedManagedIdentityResourceId { get; } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentCreateParameters.Serialization.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentCreateParameters.Serialization.cs new file mode 100644 index 0000000000000..f7fc590e0ab0e --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentCreateParameters.Serialization.cs @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Authorization.Models +{ + public partial class RoleAssignmentCreateParameters : IUtf8JsonSerializable + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + writer.WritePropertyName("properties"); + writer.WriteStartObject(); + writer.WritePropertyName("roleDefinitionId"); + writer.WriteStringValue(RoleDefinitionId); + writer.WritePropertyName("principalId"); + writer.WriteStringValue(PrincipalId); + if (Optional.IsDefined(PrincipalType)) + { + writer.WritePropertyName("principalType"); + writer.WriteStringValue(PrincipalType.Value.ToString()); + } + if (Optional.IsDefined(CanDelegate)) + { + writer.WritePropertyName("canDelegate"); + writer.WriteBooleanValue(CanDelegate.Value); + } + if (Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"); + writer.WriteStringValue(Description); + } + if (Optional.IsDefined(Condition)) + { + writer.WritePropertyName("condition"); + writer.WriteStringValue(Condition); + } + if (Optional.IsDefined(ConditionVersion)) + { + writer.WritePropertyName("conditionVersion"); + writer.WriteStringValue(ConditionVersion); + } + writer.WriteEndObject(); + writer.WriteEndObject(); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentCreateParameters.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentCreateParameters.cs new file mode 100644 index 0000000000000..265ddba80ff52 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentCreateParameters.cs @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Azure.ResourceManager.Authorization.Models +{ + /// Role assignment create parameters. + public partial class RoleAssignmentCreateParameters + { + /// Initializes a new instance of RoleAssignmentCreateParameters. + /// The role definition ID used in the role assignment. + /// The principal ID assigned to the role. This maps to the ID inside the Active Directory. It can point to a user, service principal, or security group. + /// or is null. + public RoleAssignmentCreateParameters(string roleDefinitionId, string principalId) + { + if (roleDefinitionId == null) + { + throw new ArgumentNullException(nameof(roleDefinitionId)); + } + if (principalId == null) + { + throw new ArgumentNullException(nameof(principalId)); + } + + RoleDefinitionId = roleDefinitionId; + PrincipalId = principalId; + } + + /// The role definition ID used in the role assignment. + public string RoleDefinitionId { get; } + /// The principal ID assigned to the role. This maps to the ID inside the Active Directory. It can point to a user, service principal, or security group. + public string PrincipalId { get; } + /// The principal type of the assigned principal ID. + public PrincipalType? PrincipalType { get; set; } + /// The delegation flag used for creating a role assignment. + public bool? CanDelegate { get; set; } + /// Description of role assignment. + public string Description { get; set; } + /// The conditions on the role assignment. This limits the resources it can be assigned to. e.g.: @Resource[Microsoft.Storage/storageAccounts/blobServices/containers:ContainerName] StringEqualsIgnoreCase 'foo_storage_container'. + public string Condition { get; set; } + /// Version of the condition. Currently accepted value is '2.0'. + public string ConditionVersion { get; set; } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentFilter.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentFilter.cs new file mode 100644 index 0000000000000..3cb268cd2c647 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentFilter.cs @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +namespace Azure.ResourceManager.Authorization.Models +{ + /// Role Assignments filter. + internal partial class RoleAssignmentFilter + { + /// Initializes a new instance of RoleAssignmentFilter. + internal RoleAssignmentFilter() + { + } + + /// Returns role assignment of the specific principal. + public string PrincipalId { get; } + /// The Delegation flag for the role assignment. + public bool? CanDelegate { get; } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentListResult.Serialization.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentListResult.Serialization.cs new file mode 100644 index 0000000000000..5c3d699538dd4 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentListResult.Serialization.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Authorization.Models +{ + public partial class RoleAssignmentListResult + { + internal static RoleAssignmentListResult DeserializeRoleAssignmentListResult(JsonElement element) + { + Optional> value = default; + Optional nextLink = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("value")) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + property.ThrowNonNullablePropertyIsNull(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(RoleAssignment.DeserializeRoleAssignment(item)); + } + value = array; + continue; + } + if (property.NameEquals("nextLink")) + { + nextLink = property.Value.GetString(); + continue; + } + } + return new RoleAssignmentListResult(Optional.ToList(value), nextLink.Value); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentListResult.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentListResult.cs new file mode 100644 index 0000000000000..ec7afa7e5a8c2 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/Models/RoleAssignmentListResult.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using Azure.Core; + +namespace Azure.ResourceManager.Authorization.Models +{ + /// Role assignment list operation result. + public partial class RoleAssignmentListResult + { + /// Initializes a new instance of RoleAssignmentListResult. + internal RoleAssignmentListResult() + { + Value = new ChangeTrackingList(); + } + + /// Initializes a new instance of RoleAssignmentListResult. + /// Role assignment list. + /// The URL to use for getting the next set of results. + internal RoleAssignmentListResult(IReadOnlyList value, string nextLink) + { + Value = value; + NextLink = nextLink; + } + + /// Role assignment list. + public IReadOnlyList Value { get; } + /// The URL to use for getting the next set of results. + public string NextLink { get; } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/RoleAssignmentsOperations.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/RoleAssignmentsOperations.cs new file mode 100644 index 0000000000000..6a263cd19bbee --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/RoleAssignmentsOperations.cs @@ -0,0 +1,653 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; +using Azure.ResourceManager.Authorization.Models; + +namespace Azure.ResourceManager.Authorization +{ + /// The RoleAssignments service client. + public partial class RoleAssignmentsOperations + { + private readonly ClientDiagnostics _clientDiagnostics; + private readonly HttpPipeline _pipeline; + internal RoleAssignmentsRestOperations RestClient { get; } + /// Initializes a new instance of RoleAssignmentsOperations for mocking. + protected RoleAssignmentsOperations() + { + } + /// Initializes a new instance of RoleAssignmentsOperations. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The ID of the target subscription. + /// server parameter. + /// Api Version. + internal RoleAssignmentsOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null, string apiVersion = "2020-04-01-preview") + { + RestClient = new RoleAssignmentsRestOperations(clientDiagnostics, pipeline, subscriptionId, endpoint, apiVersion); + _clientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + } + + /// Delete a role assignment. + /// The scope of the role assignment to delete. + /// The name of the role assignment to delete. + /// The cancellation token to use. + public virtual async Task> DeleteAsync(string scope, string roleAssignmentName, CancellationToken cancellationToken = default) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.Delete"); + scope0.Start(); + try + { + return await RestClient.DeleteAsync(scope, roleAssignmentName, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + + /// Delete a role assignment. + /// The scope of the role assignment to delete. + /// The name of the role assignment to delete. + /// The cancellation token to use. + public virtual Response Delete(string scope, string roleAssignmentName, CancellationToken cancellationToken = default) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.Delete"); + scope0.Start(); + try + { + return RestClient.Delete(scope, roleAssignmentName, cancellationToken); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + + /// Create a role assignment. + /// The scope of the role assignment to create. The scope can be any REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' for a resource. + /// The name of the role assignment to create. It can be any valid GUID. + /// Parameters for the role assignment. + /// The cancellation token to use. + public virtual async Task> CreateAsync(string scope, string roleAssignmentName, RoleAssignmentCreateParameters parameters, CancellationToken cancellationToken = default) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.Create"); + scope0.Start(); + try + { + return await RestClient.CreateAsync(scope, roleAssignmentName, parameters, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + + /// Create a role assignment. + /// The scope of the role assignment to create. The scope can be any REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' for a resource. + /// The name of the role assignment to create. It can be any valid GUID. + /// Parameters for the role assignment. + /// The cancellation token to use. + public virtual Response Create(string scope, string roleAssignmentName, RoleAssignmentCreateParameters parameters, CancellationToken cancellationToken = default) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.Create"); + scope0.Start(); + try + { + return RestClient.Create(scope, roleAssignmentName, parameters, cancellationToken); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + + /// Get the specified role assignment. + /// The scope of the role assignment. + /// The name of the role assignment to get. + /// The cancellation token to use. + public virtual async Task> GetAsync(string scope, string roleAssignmentName, CancellationToken cancellationToken = default) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.Get"); + scope0.Start(); + try + { + return await RestClient.GetAsync(scope, roleAssignmentName, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + + /// Get the specified role assignment. + /// The scope of the role assignment. + /// The name of the role assignment to get. + /// The cancellation token to use. + public virtual Response Get(string scope, string roleAssignmentName, CancellationToken cancellationToken = default) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.Get"); + scope0.Start(); + try + { + return RestClient.Get(scope, roleAssignmentName, cancellationToken); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + + /// Delete a role assignment. + /// The ID of the role assignment to delete. + /// The cancellation token to use. + public virtual async Task> DeleteByIdAsync(string roleId, CancellationToken cancellationToken = default) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.DeleteById"); + scope0.Start(); + try + { + return await RestClient.DeleteByIdAsync(roleId, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + + /// Delete a role assignment. + /// The ID of the role assignment to delete. + /// The cancellation token to use. + public virtual Response DeleteById(string roleId, CancellationToken cancellationToken = default) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.DeleteById"); + scope0.Start(); + try + { + return RestClient.DeleteById(roleId, cancellationToken); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + + /// Creates a role assignment by ID. + /// The ID of the role assignment to create. + /// Parameters for the role assignment. + /// The cancellation token to use. + public virtual async Task> CreateByIdAsync(string roleId, RoleAssignmentCreateParameters parameters, CancellationToken cancellationToken = default) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.CreateById"); + scope0.Start(); + try + { + return await RestClient.CreateByIdAsync(roleId, parameters, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + + /// Creates a role assignment by ID. + /// The ID of the role assignment to create. + /// Parameters for the role assignment. + /// The cancellation token to use. + public virtual Response CreateById(string roleId, RoleAssignmentCreateParameters parameters, CancellationToken cancellationToken = default) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.CreateById"); + scope0.Start(); + try + { + return RestClient.CreateById(roleId, parameters, cancellationToken); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + + /// Gets a role assignment by ID. + /// The ID of the role assignment to get. + /// The cancellation token to use. + public virtual async Task> GetByIdAsync(string roleId, CancellationToken cancellationToken = default) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.GetById"); + scope0.Start(); + try + { + return await RestClient.GetByIdAsync(roleId, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + + /// Gets a role assignment by ID. + /// The ID of the role assignment to get. + /// The cancellation token to use. + public virtual Response GetById(string roleId, CancellationToken cancellationToken = default) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.GetById"); + scope0.Start(); + try + { + return RestClient.GetById(roleId, cancellationToken); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + + /// List role assignments for a resource. + /// The name of the resource group. The name is case insensitive. + /// The namespace of the resource provider. + /// The parent resource identity. + /// The resource type of the resource. + /// The name of the resource to get role assignments for. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// , , , , or is null. + public virtual AsyncPageable ListForResourceAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter = null, CancellationToken cancellationToken = default) + { + if (resourceGroupName == null) + { + throw new ArgumentNullException(nameof(resourceGroupName)); + } + if (resourceProviderNamespace == null) + { + throw new ArgumentNullException(nameof(resourceProviderNamespace)); + } + if (parentResourcePath == null) + { + throw new ArgumentNullException(nameof(parentResourcePath)); + } + if (resourceType == null) + { + throw new ArgumentNullException(nameof(resourceType)); + } + if (resourceName == null) + { + throw new ArgumentNullException(nameof(resourceName)); + } + + async Task> FirstPageFunc(int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.ListForResource"); + scope0.Start(); + try + { + var response = await RestClient.ListForResourceAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter, cancellationToken).ConfigureAwait(false); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + async Task> NextPageFunc(string nextLink, int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.ListForResource"); + scope0.Start(); + try + { + var response = await RestClient.ListForResourceNextPageAsync(nextLink, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter, cancellationToken).ConfigureAwait(false); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); + } + + /// List role assignments for a resource. + /// The name of the resource group. The name is case insensitive. + /// The namespace of the resource provider. + /// The parent resource identity. + /// The resource type of the resource. + /// The name of the resource to get role assignments for. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// , , , , or is null. + public virtual Pageable ListForResource(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter = null, CancellationToken cancellationToken = default) + { + if (resourceGroupName == null) + { + throw new ArgumentNullException(nameof(resourceGroupName)); + } + if (resourceProviderNamespace == null) + { + throw new ArgumentNullException(nameof(resourceProviderNamespace)); + } + if (parentResourcePath == null) + { + throw new ArgumentNullException(nameof(parentResourcePath)); + } + if (resourceType == null) + { + throw new ArgumentNullException(nameof(resourceType)); + } + if (resourceName == null) + { + throw new ArgumentNullException(nameof(resourceName)); + } + + Page FirstPageFunc(int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.ListForResource"); + scope0.Start(); + try + { + var response = RestClient.ListForResource(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter, cancellationToken); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + Page NextPageFunc(string nextLink, int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.ListForResource"); + scope0.Start(); + try + { + var response = RestClient.ListForResourceNextPage(nextLink, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter, cancellationToken); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); + } + + /// List role assignments for a resource group. + /// The name of the resource group. The name is case insensitive. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// is null. + public virtual AsyncPageable ListForResourceGroupAsync(string resourceGroupName, string filter = null, CancellationToken cancellationToken = default) + { + if (resourceGroupName == null) + { + throw new ArgumentNullException(nameof(resourceGroupName)); + } + + async Task> FirstPageFunc(int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.ListForResourceGroup"); + scope0.Start(); + try + { + var response = await RestClient.ListForResourceGroupAsync(resourceGroupName, filter, cancellationToken).ConfigureAwait(false); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + async Task> NextPageFunc(string nextLink, int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.ListForResourceGroup"); + scope0.Start(); + try + { + var response = await RestClient.ListForResourceGroupNextPageAsync(nextLink, resourceGroupName, filter, cancellationToken).ConfigureAwait(false); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); + } + + /// List role assignments for a resource group. + /// The name of the resource group. The name is case insensitive. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// is null. + public virtual Pageable ListForResourceGroup(string resourceGroupName, string filter = null, CancellationToken cancellationToken = default) + { + if (resourceGroupName == null) + { + throw new ArgumentNullException(nameof(resourceGroupName)); + } + + Page FirstPageFunc(int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.ListForResourceGroup"); + scope0.Start(); + try + { + var response = RestClient.ListForResourceGroup(resourceGroupName, filter, cancellationToken); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + Page NextPageFunc(string nextLink, int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.ListForResourceGroup"); + scope0.Start(); + try + { + var response = RestClient.ListForResourceGroupNextPage(nextLink, resourceGroupName, filter, cancellationToken); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); + } + + /// Gets all role assignments for the subscription. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + public virtual AsyncPageable ListAsync(string filter = null, CancellationToken cancellationToken = default) + { + async Task> FirstPageFunc(int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.List"); + scope0.Start(); + try + { + var response = await RestClient.ListAsync(filter, cancellationToken).ConfigureAwait(false); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + async Task> NextPageFunc(string nextLink, int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.List"); + scope0.Start(); + try + { + var response = await RestClient.ListNextPageAsync(nextLink, filter, cancellationToken).ConfigureAwait(false); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); + } + + /// Gets all role assignments for the subscription. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + public virtual Pageable List(string filter = null, CancellationToken cancellationToken = default) + { + Page FirstPageFunc(int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.List"); + scope0.Start(); + try + { + var response = RestClient.List(filter, cancellationToken); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + Page NextPageFunc(string nextLink, int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.List"); + scope0.Start(); + try + { + var response = RestClient.ListNextPage(nextLink, filter, cancellationToken); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); + } + + /// Gets role assignments for a scope. + /// The scope of the role assignments. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// is null. + public virtual AsyncPageable ListForScopeAsync(string scope, string filter = null, CancellationToken cancellationToken = default) + { + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + + async Task> FirstPageFunc(int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.ListForScope"); + scope0.Start(); + try + { + var response = await RestClient.ListForScopeAsync(scope, filter, cancellationToken).ConfigureAwait(false); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + async Task> NextPageFunc(string nextLink, int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.ListForScope"); + scope0.Start(); + try + { + var response = await RestClient.ListForScopeNextPageAsync(nextLink, scope, filter, cancellationToken).ConfigureAwait(false); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); + } + + /// Gets role assignments for a scope. + /// The scope of the role assignments. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// is null. + public virtual Pageable ListForScope(string scope, string filter = null, CancellationToken cancellationToken = default) + { + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + + Page FirstPageFunc(int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.ListForScope"); + scope0.Start(); + try + { + var response = RestClient.ListForScope(scope, filter, cancellationToken); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + Page NextPageFunc(string nextLink, int? pageSizeHint) + { + using var scope0 = _clientDiagnostics.CreateScope("RoleAssignmentsOperations.ListForScope"); + scope0.Start(); + try + { + var response = RestClient.ListForScopeNextPage(nextLink, scope, filter, cancellationToken); + return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/RoleAssignmentsRestOperations.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/RoleAssignmentsRestOperations.cs new file mode 100644 index 0000000000000..4851b1729f788 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Generated/RoleAssignmentsRestOperations.cs @@ -0,0 +1,1227 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; +using Azure.ResourceManager.Authorization.Models; + +namespace Azure.ResourceManager.Authorization +{ + internal partial class RoleAssignmentsRestOperations + { + private string subscriptionId; + private Uri endpoint; + private string apiVersion; + private ClientDiagnostics _clientDiagnostics; + private HttpPipeline _pipeline; + + /// Initializes a new instance of RoleAssignmentsRestOperations. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The ID of the target subscription. + /// server parameter. + /// Api Version. + /// or is null. + public RoleAssignmentsRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null, string apiVersion = "2020-04-01-preview") + { + if (subscriptionId == null) + { + throw new ArgumentNullException(nameof(subscriptionId)); + } + endpoint ??= new Uri("https://management.azure.com"); + if (apiVersion == null) + { + throw new ArgumentNullException(nameof(apiVersion)); + } + + this.subscriptionId = subscriptionId; + this.endpoint = endpoint; + this.apiVersion = apiVersion; + _clientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + } + + internal HttpMessage CreateListForResourceRequest(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/resourcegroups/", false); + uri.AppendPath(resourceGroupName, true); + uri.AppendPath("/providers/", false); + uri.AppendPath(resourceProviderNamespace, true); + uri.AppendPath("/", false); + uri.AppendPath(parentResourcePath, false); + uri.AppendPath("/", false); + uri.AppendPath(resourceType, false); + uri.AppendPath("/", false); + uri.AppendPath(resourceName, true); + uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments", false); + if (filter != null) + { + uri.AppendQuery("$filter", filter, true); + } + uri.AppendQuery("api-version", apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + /// List role assignments for a resource. + /// The name of the resource group. The name is case insensitive. + /// The namespace of the resource provider. + /// The parent resource identity. + /// The resource type of the resource. + /// The name of the resource to get role assignments for. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// , , , , or is null. + public async Task> ListForResourceAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter = null, CancellationToken cancellationToken = default) + { + if (resourceGroupName == null) + { + throw new ArgumentNullException(nameof(resourceGroupName)); + } + if (resourceProviderNamespace == null) + { + throw new ArgumentNullException(nameof(resourceProviderNamespace)); + } + if (parentResourcePath == null) + { + throw new ArgumentNullException(nameof(parentResourcePath)); + } + if (resourceType == null) + { + throw new ArgumentNullException(nameof(resourceType)); + } + if (resourceName == null) + { + throw new ArgumentNullException(nameof(resourceName)); + } + + using var message = CreateListForResourceRequest(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// List role assignments for a resource. + /// The name of the resource group. The name is case insensitive. + /// The namespace of the resource provider. + /// The parent resource identity. + /// The resource type of the resource. + /// The name of the resource to get role assignments for. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// , , , , or is null. + public Response ListForResource(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter = null, CancellationToken cancellationToken = default) + { + if (resourceGroupName == null) + { + throw new ArgumentNullException(nameof(resourceGroupName)); + } + if (resourceProviderNamespace == null) + { + throw new ArgumentNullException(nameof(resourceProviderNamespace)); + } + if (parentResourcePath == null) + { + throw new ArgumentNullException(nameof(parentResourcePath)); + } + if (resourceType == null) + { + throw new ArgumentNullException(nameof(resourceType)); + } + if (resourceName == null) + { + throw new ArgumentNullException(nameof(resourceName)); + } + + using var message = CreateListForResourceRequest(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + + internal HttpMessage CreateListForResourceGroupRequest(string resourceGroupName, string filter) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/resourceGroups/", false); + uri.AppendPath(resourceGroupName, true); + uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments", false); + if (filter != null) + { + uri.AppendQuery("$filter", filter, true); + } + uri.AppendQuery("api-version", apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + /// List role assignments for a resource group. + /// The name of the resource group. The name is case insensitive. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// is null. + public async Task> ListForResourceGroupAsync(string resourceGroupName, string filter = null, CancellationToken cancellationToken = default) + { + if (resourceGroupName == null) + { + throw new ArgumentNullException(nameof(resourceGroupName)); + } + + using var message = CreateListForResourceGroupRequest(resourceGroupName, filter); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// List role assignments for a resource group. + /// The name of the resource group. The name is case insensitive. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// is null. + public Response ListForResourceGroup(string resourceGroupName, string filter = null, CancellationToken cancellationToken = default) + { + if (resourceGroupName == null) + { + throw new ArgumentNullException(nameof(resourceGroupName)); + } + + using var message = CreateListForResourceGroupRequest(resourceGroupName, filter); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + + internal HttpMessage CreateDeleteRequest(string scope, string roleAssignmentName) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendPath("/", false); + uri.AppendPath(scope, false); + uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments/", false); + uri.AppendPath(roleAssignmentName, true); + uri.AppendQuery("api-version", apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + /// Delete a role assignment. + /// The scope of the role assignment to delete. + /// The name of the role assignment to delete. + /// The cancellation token to use. + /// or is null. + public async Task> DeleteAsync(string scope, string roleAssignmentName, CancellationToken cancellationToken = default) + { + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + if (roleAssignmentName == null) + { + throw new ArgumentNullException(nameof(roleAssignmentName)); + } + + using var message = CreateDeleteRequest(scope, roleAssignmentName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RoleAssignment value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); + value = RoleAssignment.DeserializeRoleAssignment(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 204: + return Response.FromValue(null, message.Response); + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// Delete a role assignment. + /// The scope of the role assignment to delete. + /// The name of the role assignment to delete. + /// The cancellation token to use. + /// or is null. + public Response Delete(string scope, string roleAssignmentName, CancellationToken cancellationToken = default) + { + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + if (roleAssignmentName == null) + { + throw new ArgumentNullException(nameof(roleAssignmentName)); + } + + using var message = CreateDeleteRequest(scope, roleAssignmentName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RoleAssignment value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream); + value = RoleAssignment.DeserializeRoleAssignment(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 204: + return Response.FromValue(null, message.Response); + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + + internal HttpMessage CreateCreateRequest(string scope, string roleAssignmentName, RoleAssignmentCreateParameters parameters) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendPath("/", false); + uri.AppendPath(scope, false); + uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments/", false); + uri.AppendPath(roleAssignmentName, true); + uri.AppendQuery("api-version", apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(parameters); + request.Content = content; + return message; + } + + /// Create a role assignment. + /// The scope of the role assignment to create. The scope can be any REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' for a resource. + /// The name of the role assignment to create. It can be any valid GUID. + /// Parameters for the role assignment. + /// The cancellation token to use. + /// , , or is null. + public async Task> CreateAsync(string scope, string roleAssignmentName, RoleAssignmentCreateParameters parameters, CancellationToken cancellationToken = default) + { + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + if (roleAssignmentName == null) + { + throw new ArgumentNullException(nameof(roleAssignmentName)); + } + if (parameters == null) + { + throw new ArgumentNullException(nameof(parameters)); + } + + using var message = CreateCreateRequest(scope, roleAssignmentName, parameters); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 201: + { + RoleAssignment value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); + value = RoleAssignment.DeserializeRoleAssignment(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// Create a role assignment. + /// The scope of the role assignment to create. The scope can be any REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}' for a resource. + /// The name of the role assignment to create. It can be any valid GUID. + /// Parameters for the role assignment. + /// The cancellation token to use. + /// , , or is null. + public Response Create(string scope, string roleAssignmentName, RoleAssignmentCreateParameters parameters, CancellationToken cancellationToken = default) + { + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + if (roleAssignmentName == null) + { + throw new ArgumentNullException(nameof(roleAssignmentName)); + } + if (parameters == null) + { + throw new ArgumentNullException(nameof(parameters)); + } + + using var message = CreateCreateRequest(scope, roleAssignmentName, parameters); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 201: + { + RoleAssignment value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream); + value = RoleAssignment.DeserializeRoleAssignment(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + + internal HttpMessage CreateGetRequest(string scope, string roleAssignmentName) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendPath("/", false); + uri.AppendPath(scope, false); + uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments/", false); + uri.AppendPath(roleAssignmentName, true); + uri.AppendQuery("api-version", apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + /// Get the specified role assignment. + /// The scope of the role assignment. + /// The name of the role assignment to get. + /// The cancellation token to use. + /// or is null. + public async Task> GetAsync(string scope, string roleAssignmentName, CancellationToken cancellationToken = default) + { + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + if (roleAssignmentName == null) + { + throw new ArgumentNullException(nameof(roleAssignmentName)); + } + + using var message = CreateGetRequest(scope, roleAssignmentName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RoleAssignment value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); + value = RoleAssignment.DeserializeRoleAssignment(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// Get the specified role assignment. + /// The scope of the role assignment. + /// The name of the role assignment to get. + /// The cancellation token to use. + /// or is null. + public Response Get(string scope, string roleAssignmentName, CancellationToken cancellationToken = default) + { + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + if (roleAssignmentName == null) + { + throw new ArgumentNullException(nameof(roleAssignmentName)); + } + + using var message = CreateGetRequest(scope, roleAssignmentName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RoleAssignment value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream); + value = RoleAssignment.DeserializeRoleAssignment(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + + internal HttpMessage CreateDeleteByIdRequest(string roleId) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendPath("/", false); + uri.AppendPath(roleId, false); + uri.AppendQuery("api-version", apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + /// Delete a role assignment. + /// The ID of the role assignment to delete. + /// The cancellation token to use. + /// is null. + public async Task> DeleteByIdAsync(string roleId, CancellationToken cancellationToken = default) + { + if (roleId == null) + { + throw new ArgumentNullException(nameof(roleId)); + } + + using var message = CreateDeleteByIdRequest(roleId); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RoleAssignment value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); + value = RoleAssignment.DeserializeRoleAssignment(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 204: + return Response.FromValue(null, message.Response); + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// Delete a role assignment. + /// The ID of the role assignment to delete. + /// The cancellation token to use. + /// is null. + public Response DeleteById(string roleId, CancellationToken cancellationToken = default) + { + if (roleId == null) + { + throw new ArgumentNullException(nameof(roleId)); + } + + using var message = CreateDeleteByIdRequest(roleId); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RoleAssignment value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream); + value = RoleAssignment.DeserializeRoleAssignment(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 204: + return Response.FromValue(null, message.Response); + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + + internal HttpMessage CreateCreateByIdRequest(string roleId, RoleAssignmentCreateParameters parameters) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendPath("/", false); + uri.AppendPath(roleId, false); + uri.AppendQuery("api-version", apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(parameters); + request.Content = content; + return message; + } + + /// Creates a role assignment by ID. + /// The ID of the role assignment to create. + /// Parameters for the role assignment. + /// The cancellation token to use. + /// or is null. + public async Task> CreateByIdAsync(string roleId, RoleAssignmentCreateParameters parameters, CancellationToken cancellationToken = default) + { + if (roleId == null) + { + throw new ArgumentNullException(nameof(roleId)); + } + if (parameters == null) + { + throw new ArgumentNullException(nameof(parameters)); + } + + using var message = CreateCreateByIdRequest(roleId, parameters); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 201: + { + RoleAssignment value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); + value = RoleAssignment.DeserializeRoleAssignment(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// Creates a role assignment by ID. + /// The ID of the role assignment to create. + /// Parameters for the role assignment. + /// The cancellation token to use. + /// or is null. + public Response CreateById(string roleId, RoleAssignmentCreateParameters parameters, CancellationToken cancellationToken = default) + { + if (roleId == null) + { + throw new ArgumentNullException(nameof(roleId)); + } + if (parameters == null) + { + throw new ArgumentNullException(nameof(parameters)); + } + + using var message = CreateCreateByIdRequest(roleId, parameters); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 201: + { + RoleAssignment value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream); + value = RoleAssignment.DeserializeRoleAssignment(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + + internal HttpMessage CreateGetByIdRequest(string roleId) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendPath("/", false); + uri.AppendPath(roleId, false); + uri.AppendQuery("api-version", apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + /// Gets a role assignment by ID. + /// The ID of the role assignment to get. + /// The cancellation token to use. + /// is null. + public async Task> GetByIdAsync(string roleId, CancellationToken cancellationToken = default) + { + if (roleId == null) + { + throw new ArgumentNullException(nameof(roleId)); + } + + using var message = CreateGetByIdRequest(roleId); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RoleAssignment value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); + value = RoleAssignment.DeserializeRoleAssignment(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// Gets a role assignment by ID. + /// The ID of the role assignment to get. + /// The cancellation token to use. + /// is null. + public Response GetById(string roleId, CancellationToken cancellationToken = default) + { + if (roleId == null) + { + throw new ArgumentNullException(nameof(roleId)); + } + + using var message = CreateGetByIdRequest(roleId); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RoleAssignment value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream); + value = RoleAssignment.DeserializeRoleAssignment(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + + internal HttpMessage CreateListRequest(string filter) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments", false); + if (filter != null) + { + uri.AppendQuery("$filter", filter, true); + } + uri.AppendQuery("api-version", apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + /// Gets all role assignments for the subscription. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + public async Task> ListAsync(string filter = null, CancellationToken cancellationToken = default) + { + using var message = CreateListRequest(filter); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// Gets all role assignments for the subscription. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + public Response List(string filter = null, CancellationToken cancellationToken = default) + { + using var message = CreateListRequest(filter); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + + internal HttpMessage CreateListForScopeRequest(string scope, string filter) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendPath("/", false); + uri.AppendPath(scope, false); + uri.AppendPath("/providers/Microsoft.Authorization/roleAssignments", false); + if (filter != null) + { + uri.AppendQuery("$filter", filter, true); + } + uri.AppendQuery("api-version", apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + /// Gets role assignments for a scope. + /// The scope of the role assignments. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// is null. + public async Task> ListForScopeAsync(string scope, string filter = null, CancellationToken cancellationToken = default) + { + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + + using var message = CreateListForScopeRequest(scope, filter); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// Gets role assignments for a scope. + /// The scope of the role assignments. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// is null. + public Response ListForScope(string scope, string filter = null, CancellationToken cancellationToken = default) + { + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + + using var message = CreateListForScopeRequest(scope, filter); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + + internal HttpMessage CreateListForResourceNextPageRequest(string nextLink, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + /// List role assignments for a resource. + /// The URL to the next page of results. + /// The name of the resource group. The name is case insensitive. + /// The namespace of the resource provider. + /// The parent resource identity. + /// The resource type of the resource. + /// The name of the resource to get role assignments for. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// , , , , , or is null. + public async Task> ListForResourceNextPageAsync(string nextLink, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter = null, CancellationToken cancellationToken = default) + { + if (nextLink == null) + { + throw new ArgumentNullException(nameof(nextLink)); + } + if (resourceGroupName == null) + { + throw new ArgumentNullException(nameof(resourceGroupName)); + } + if (resourceProviderNamespace == null) + { + throw new ArgumentNullException(nameof(resourceProviderNamespace)); + } + if (parentResourcePath == null) + { + throw new ArgumentNullException(nameof(parentResourcePath)); + } + if (resourceType == null) + { + throw new ArgumentNullException(nameof(resourceType)); + } + if (resourceName == null) + { + throw new ArgumentNullException(nameof(resourceName)); + } + + using var message = CreateListForResourceNextPageRequest(nextLink, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// List role assignments for a resource. + /// The URL to the next page of results. + /// The name of the resource group. The name is case insensitive. + /// The namespace of the resource provider. + /// The parent resource identity. + /// The resource type of the resource. + /// The name of the resource to get role assignments for. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// , , , , , or is null. + public Response ListForResourceNextPage(string nextLink, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter = null, CancellationToken cancellationToken = default) + { + if (nextLink == null) + { + throw new ArgumentNullException(nameof(nextLink)); + } + if (resourceGroupName == null) + { + throw new ArgumentNullException(nameof(resourceGroupName)); + } + if (resourceProviderNamespace == null) + { + throw new ArgumentNullException(nameof(resourceProviderNamespace)); + } + if (parentResourcePath == null) + { + throw new ArgumentNullException(nameof(parentResourcePath)); + } + if (resourceType == null) + { + throw new ArgumentNullException(nameof(resourceType)); + } + if (resourceName == null) + { + throw new ArgumentNullException(nameof(resourceName)); + } + + using var message = CreateListForResourceNextPageRequest(nextLink, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + + internal HttpMessage CreateListForResourceGroupNextPageRequest(string nextLink, string resourceGroupName, string filter) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + /// List role assignments for a resource group. + /// The URL to the next page of results. + /// The name of the resource group. The name is case insensitive. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// or is null. + public async Task> ListForResourceGroupNextPageAsync(string nextLink, string resourceGroupName, string filter = null, CancellationToken cancellationToken = default) + { + if (nextLink == null) + { + throw new ArgumentNullException(nameof(nextLink)); + } + if (resourceGroupName == null) + { + throw new ArgumentNullException(nameof(resourceGroupName)); + } + + using var message = CreateListForResourceGroupNextPageRequest(nextLink, resourceGroupName, filter); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// List role assignments for a resource group. + /// The URL to the next page of results. + /// The name of the resource group. The name is case insensitive. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// or is null. + public Response ListForResourceGroupNextPage(string nextLink, string resourceGroupName, string filter = null, CancellationToken cancellationToken = default) + { + if (nextLink == null) + { + throw new ArgumentNullException(nameof(nextLink)); + } + if (resourceGroupName == null) + { + throw new ArgumentNullException(nameof(resourceGroupName)); + } + + using var message = CreateListForResourceGroupNextPageRequest(nextLink, resourceGroupName, filter); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + + internal HttpMessage CreateListNextPageRequest(string nextLink, string filter) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + /// Gets all role assignments for the subscription. + /// The URL to the next page of results. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// is null. + public async Task> ListNextPageAsync(string nextLink, string filter = null, CancellationToken cancellationToken = default) + { + if (nextLink == null) + { + throw new ArgumentNullException(nameof(nextLink)); + } + + using var message = CreateListNextPageRequest(nextLink, filter); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// Gets all role assignments for the subscription. + /// The URL to the next page of results. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// is null. + public Response ListNextPage(string nextLink, string filter = null, CancellationToken cancellationToken = default) + { + if (nextLink == null) + { + throw new ArgumentNullException(nameof(nextLink)); + } + + using var message = CreateListNextPageRequest(nextLink, filter); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + + internal HttpMessage CreateListForScopeNextPageRequest(string nextLink, string scope, string filter) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + /// Gets role assignments for a scope. + /// The URL to the next page of results. + /// The scope of the role assignments. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// or is null. + public async Task> ListForScopeNextPageAsync(string nextLink, string scope, string filter = null, CancellationToken cancellationToken = default) + { + if (nextLink == null) + { + throw new ArgumentNullException(nameof(nextLink)); + } + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + + using var message = CreateListForScopeNextPageRequest(nextLink, scope, filter); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// Gets role assignments for a scope. + /// The URL to the next page of results. + /// The scope of the role assignments. + /// The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. + /// The cancellation token to use. + /// or is null. + public Response ListForScopeNextPage(string nextLink, string scope, string filter = null, CancellationToken cancellationToken = default) + { + if (nextLink == null) + { + throw new ArgumentNullException(nameof(nextLink)); + } + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + + using var message = CreateListForScopeNextPageRequest(nextLink, scope, filter); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RoleAssignmentListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream); + value = RoleAssignmentListResult.DeserializeRoleAssignmentListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Properties/AssemblyInfo.cs b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000..4cab9c49d0ebf --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/Properties/AssemblyInfo.cs @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: Azure.Core.AzureResourceProviderNamespace("Microsoft.Authorization")] + +[assembly: InternalsVisibleTo("Azure.ResourceManager.Authorization.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/README.MD b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/README.MD new file mode 100644 index 0000000000000..b41873a90b179 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/README.MD @@ -0,0 +1,3 @@ +# Proto Azure ResourceManager Authorization + +Prototype version of Azure.ResourceManager.Authorization used to showcase and test the new prototype track 2 management plane SDK \ No newline at end of file diff --git a/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/autorest.md b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/autorest.md new file mode 100644 index 0000000000000..face655375676 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Azure.ResourceManager.Authorization/autorest.md @@ -0,0 +1,11 @@ +# Generated code configuration + +Run `dotnet build /t:GenerateCode` to generate code. + +``` yaml + +azure-arm: true +require: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/f0a0a9f0ab2278885f9349ef03bf02d4790f28ec/specification/authorization/resource-manager/readme.md + + +``` \ No newline at end of file diff --git a/sdk/resourcemanager/Proto.Client/authorization/CHANGELOG.md b/sdk/resourcemanager/Proto.Client/authorization/CHANGELOG.md new file mode 100644 index 0000000000000..5c312e4ea9bea --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/CHANGELOG.md @@ -0,0 +1,5 @@ +# Release History + +## 1.0.0-beta.1 (Unreleased) + +-Initial checkin diff --git a/sdk/resourcemanager/Proto.Client/authorization/Extensions/RoleAssignmentExtensions.cs b/sdk/resourcemanager/Proto.Client/authorization/Extensions/RoleAssignmentExtensions.cs new file mode 100644 index 0000000000000..b8009caf3628b --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Extensions/RoleAssignmentExtensions.cs @@ -0,0 +1,92 @@ +using Azure.ResourceManager.Core; + +namespace Proto.Authorization +{ + /// + /// Extensions for RoleAssignment Containers and Operations + /// + public static class RoleAssignmentExtensions + { + /// + /// Get RoleAssignment Container for the given resource. Note that this is only valid for unconstrained role assignments, so + /// it is a generation-time decision if we include this. + /// + /// The resource that is the target of the roel assignemnt + /// A that allows creating and listing RoleAssignments + public static RoleAssignmentContainer GetRoleAssignmentContainer(this ResourceOperationsBase resource) + { + return new RoleAssignmentContainer(resource); + } + + /// + /// Get RoleAssignment Container for the given resource. Note that this is only valid for unconstrained role assignments, so + /// it is a generation-time decision if we include this. + /// + /// The subscription that is the target of the role assignemnt + /// A that allows creating and listing RoleAssignments + public static RoleAssignmentContainer GetRoleAssignmentContainer(this SubscriptionOperations resource) + { + return new RoleAssignmentContainer(resource); + } + + /// + /// Get RoleAssignment Container for the given resource and scope. Note that this is only valid for unconstrained role assignments, so + /// it is a generation-time decision if we include this. + /// + /// The subscription containign the role assignment + /// The target of the role assignment + /// A that allows creating and listing RoleAssignments + public static RoleAssignmentContainer GetRoleAssigmentContainerAtScope(this SubscriptionOperations subscription, ResourceIdentifier scope) + { + return new RoleAssignmentContainer(subscription, scope); + } + + /// + /// Get RoleAssignment Container for the given resource and scope. Note that this is only valid for unconstrained role assignments, so + /// it is a generation-time decision if we include this. + /// + /// The subscription containign the role assignment + /// The target of the role assignment + /// A that allows creating and listing RoleAssignments + public static RoleAssignmentContainer GetRoleAssigmentContainerAtScope(this SubscriptionOperations subscription, Resource scope) + { + return new RoleAssignmentContainer(subscription, scope.Id); + } + + /// + /// Get RoleAssignment Operations for the given resource and scope. Note that this is only valid for unconstrained role assignments, so + /// it is a generation-time decision if we include this. + /// + /// The resource containing the role assignment + /// The name of the role assignment + /// A that allows getting and deleting RoleAssignments + public static RoleAssignmentOperations GetRoleAssignmentOperations(this ResourceOperationsBase resource, string name) + { + return new RoleAssignmentOperations(resource, $"{resource.Id}/providers/Microsoft.Authorization/roleAssignments/{name}"); + } + + /// + /// Get RoleAssignment Operations for the given resource and scope. Note that this is only valid for unconstrained role assignments, so + /// it is a generation-time decision if we include this. + /// + /// The subscription containing the role assignment + /// The name of the role assignment + /// A that allows getting and deleting RoleAssignments + public static RoleAssignmentOperations GetRoleAssignmentOperations(this SubscriptionOperations resource, string name) + { + return new RoleAssignmentOperations(resource, $"{resource.Id}/providers/Microsoft.Authorization/roleAssignments/{name}"); + } + + /// + /// Get RoleAssignment Operations for the given resource and scope. Note that this is only valid for unconstrained role assignments, so + /// it is a generation-time decision if we include this. + /// + /// The subscription containing the role assignment + /// The id of the role assignment + /// A that allows getting and deleting RoleAssignments + public static RoleAssignmentOperations GetRoleAssignmentOperationsAtScope(this SubscriptionOperations resource, ResourceIdentifier resourceId) + { + return new RoleAssignmentOperations(resource, resourceId); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Placeholder/RoleAssignmentCreateParameters.cs b/sdk/resourcemanager/Proto.Client/authorization/Placeholder/RoleAssignmentCreateParameters.cs new file mode 100644 index 0000000000000..d702b00b93e2e --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Placeholder/RoleAssignmentCreateParameters.cs @@ -0,0 +1,55 @@ +using Azure.ResourceManager.Authorization.Models; +using Azure.ResourceManager.Core; + +namespace Proto.Authorization +{ + /// + /// Creation properties for RoleAssignments + /// + public class RoleAssignmentCreateParameters + { + /// + /// Initializes a new instance of the class. + /// + /// The granted permissiosn for this assignment + /// The principal id for this assignment + public RoleAssignmentCreateParameters(ResourceIdentifier roleDefinitionId, string principalId) + { + RoleDefinitionId = roleDefinitionId; + PrincipalId = principalId; + PrincipalType = Azure.ResourceManager.Authorization.Models.PrincipalType.ServicePrincipal; + } + + /// + /// Gets the identifier of the role definition used in the assignment + /// + public ResourceIdentifier RoleDefinitionId { get; } + + /// + /// Gets the Object ID of the principal used in the assignment + /// + public string PrincipalId { get; } + + /// + /// Gets or sets the type of the principal used in the assignment + /// + public PrincipalType? PrincipalType { get; set; } + + /// + /// Gets or sets the data indicating whether the principal can delegate privileges + /// + public bool? CanDelegate { get; set; } + + /// + /// Return the underlying serialization model + /// + /// The serialization model for the role assignemnt + public Azure.ResourceManager.Authorization.Models.RoleAssignmentCreateParameters ToModel() + { + var model = new Azure.ResourceManager.Authorization.Models.RoleAssignmentCreateParameters(RoleDefinitionId, PrincipalId); + model.PrincipalType = PrincipalType; + model.CanDelegate = CanDelegate; + return model; + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Placeholder/RoleAssignmentData.cs b/sdk/resourcemanager/Proto.Client/authorization/Placeholder/RoleAssignmentData.cs new file mode 100644 index 0000000000000..d5741c69fc315 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Placeholder/RoleAssignmentData.cs @@ -0,0 +1,72 @@ +using Azure.ResourceManager.Authorization.Models; +using Azure.ResourceManager.Core; + +namespace Proto.Authorization +{ + /// + /// Placholder class containing Role assignment POCO properties. + /// + public class RoleAssignmentData : Resource + { + private Azure.ResourceManager.Authorization.Models.RoleAssignment _model; + + /// + /// Initializes a new instance of the class. + /// + /// The Track2 management plane assignment. + public RoleAssignmentData(Azure.ResourceManager.Authorization.Models.RoleAssignment assign) + { + _model = assign; + Id = assign.Id; + Scope = assign.Scope; + RoleDefinitionId = assign.RoleDefinitionId; + PrincipalId = assign.PrincipalId; + PrincipalType = assign.PrincipalType; + CanDelegate = assign.CanDelegate; + } + + /// + /// Gets the resource type of thsi resource. + /// + public static Azure.ResourceManager.Core.ResourceType ResourceType => "Microsoft.Authorization/roleAssignments"; + + /// + /// Gets the target of this role assignment. + /// + public string Scope { get; } + + /// + /// Gets the role definition id for this role assignment - determines the permissions allowed by this assignment. + /// + public ResourceIdentifier RoleDefinitionId { get; } + + /// + /// Gets the ActiveDirectory principal that is assigned privileges to the target by this assignemnt. + /// + public string PrincipalId { get; } + + /// + /// Gets the type of the principal associated with this assignment. + /// + public PrincipalType? PrincipalType { get; } + + /// + /// Gets the value determining whether the principal can delegate its permissions. + /// + public bool? CanDelegate { get; } + + /// + /// Gets or sets the identifier of the RoleAssignment. + /// + public override ResourceIdentifier Id { get; protected set; } + + /// + /// Gets the Track2 Management model associated with the data object. + /// + /// The Track2 Role Assignment, for serialization. + public Azure.ResourceManager.Authorization.Models.RoleAssignment ToModel() + { + return _model; + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/Proto.Authorization.csproj b/sdk/resourcemanager/Proto.Client/authorization/Proto.Authorization.csproj new file mode 100644 index 0000000000000..2027a495657b5 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/Proto.Authorization.csproj @@ -0,0 +1,30 @@ + + + + netstandard2.0 + Proto.Authorization + latest + ..\stylecop.ruleset + obj\docs.xml + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + diff --git a/sdk/resourcemanager/Proto.Client/authorization/README.MD b/sdk/resourcemanager/Proto.Client/authorization/README.MD new file mode 100644 index 0000000000000..dd11dbdd018a0 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/README.MD @@ -0,0 +1,3 @@ +# Proto Authorization + +Prototype version of Azure.ResourceManager.Authorization used to showcase and test the new prototype track 2 management plane SDK \ No newline at end of file diff --git a/sdk/resourcemanager/Proto.Client/authorization/RoleAssignment.cs b/sdk/resourcemanager/Proto.Client/authorization/RoleAssignment.cs new file mode 100644 index 0000000000000..a18da72944083 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/RoleAssignment.cs @@ -0,0 +1,39 @@ +using System.Threading.Tasks; +using Azure.ResourceManager.Core; + +namespace Proto.Authorization +{ + /// + /// A Role Assignment for Role-based access control in ARM + /// + public class RoleAssignment : RoleAssignmentOperations + { + /// + /// Initializes a new instance of the class. + /// + /// The operations class to copy the http settings from. + /// The properties of the resource. + internal RoleAssignment(OperationsBase operations, RoleAssignmentData data) + : base(operations, data?.Id) + { + Data = data; + } + + /// + /// Gets the properties of the RoleAssignment. + /// + public RoleAssignmentData Data { get; } + + /// + protected override RoleAssignment GetResource() + { + return this; + } + + /// + protected override Task GetResourceAsync() + { + return Task.FromResult(this); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/RoleAssignmentContainer.cs b/sdk/resourcemanager/Proto.Client/authorization/RoleAssignmentContainer.cs new file mode 100644 index 0000000000000..c0a17bef35862 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/RoleAssignmentContainer.cs @@ -0,0 +1,127 @@ +using Azure.ResourceManager.Authorization; +using Azure.ResourceManager.Core; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Authorization +{ + /// + /// Container for role assignments - note that in this case, the container is either a TrackedResource or a resource Id + /// + public class RoleAssignmentContainer : ExtensionResourceContainer + { + /// + /// Initializes a new instance of the class. + /// + /// A generic operations class representing the parent of the role Assignment. + internal RoleAssignmentContainer(OperationsBase operations) + : base(operations) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client options with http client details for these operations. + /// The resource id of the target resource, resource group, or subscription for this role assignment. + internal RoleAssignmentContainer(OperationsBase operations, ResourceIdentifier scope) + : base(operations, scope) + { + } + + /// + protected override ResourceType ValidResourceType => RoleAssignmentOperations.ResourceType; + + /// + /// Gets the resource type of the resource being created. + /// + private RoleAssignmentsOperations Operations => new AuthorizationManagementClient(Id.Subscription, BaseUri, Credential).RoleAssignments; + + /// + /// Create a role assignment. This method blocks until the RoleAssignment is created on the service. + /// + /// The name of the role assignment. + /// The properties of the role assignment. + /// A token that allows cancellation of any blockign API calls made during this method. + /// The created role assignment. + public override ArmResponse Create(string name, RoleAssignmentCreateParameters resourceDetails, CancellationToken cancellationToken = default) + { + var response = Operations.Create(Id, name, resourceDetails.ToModel(), cancellationToken); + return new PhArmResponse( + response, + a => new RoleAssignment(this, new RoleAssignmentData(a))); + } + + /// + /// Create a role assignment. This method returns a task performs the creation. The task may make multiple blocking calls. + /// When complete the task yields the created RoleAssignment. + /// + /// The name of the role assignment. + /// The properties of the role assignment. + /// A token that allows cancellation of any blockign API calls made during this method. + /// A Task that yields the created role assignment when complete. + public async override Task> CreateAsync(string name, RoleAssignmentCreateParameters resourceDetails, CancellationToken cancellationToken = default) + { + var response = await Operations.CreateAsync(Id, name, resourceDetails.ToModel(), cancellationToken).ConfigureAwait(false); + return new PhArmResponse( + response, + a => new RoleAssignment(this, new RoleAssignmentData(a))); + } + + /// + /// Create a role assignment. This method blocks until the RoleAssignment creation is accepted on the service. It returns an + /// allowing the caller to control polling and waiting for the creation to complete. + /// + /// The name of the role assignment. + /// The properties of the role assignment. + /// A token that allows cancellation of any blocking API calls made during this method. + /// An ArmOperation that yields the created role assignment and gives the user control over polling. + public override ArmOperation StartCreate(string name, RoleAssignmentCreateParameters resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + Operations.Create(Id, name, resourceDetails.ToModel(), cancellationToken), + a => new RoleAssignment(this, new RoleAssignmentData(a))); + } + + /// + /// Create a role assignment. This method blocks until the RoleAssignment creation is accepted on the service. It returns an + /// allowing the caller to control polling and waiting for the creation to complete. + /// + /// The name of the role assignment. + /// The properties of the role assignment. + /// A token that allows cancellation of any blocking API calls made during this method. + /// A that yields the created role assignment and gives the user control over polling. + public async override Task> StartCreateAsync(string name, RoleAssignmentCreateParameters resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + await Operations.CreateAsync(Id, name, resourceDetails.ToModel(), cancellationToken).ConfigureAwait(false), + a => new RoleAssignment(this, new RoleAssignmentData(a))); + } + + /// + /// List all role assignments at this scope. This call blocks until the first page or results is returned from the service. + /// + /// A token that allows cancellation of any blocking API calls made during this method. + /// A that allows paged enumeration of the role assignments at this scope. + public override Azure.Pageable ListAtScope(CancellationToken cancellationToken = default) + { + throw new System.NotImplementedException(); + } + + /// + /// List all role assignments at this scope. + /// + /// A token that allows cancellation of any blocking API calls made during this method. + /// A that allows asynchronous paged enumeration of the role assignments at this scope. + public override Azure.AsyncPageable ListAtScopeAsync(CancellationToken cancellationToken = default) + { + throw new System.NotImplementedException(); + } + + /// + protected override void Validate(ResourceIdentifier identifier) + { + return; + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/authorization/RoleAssignmentOperations.cs b/sdk/resourcemanager/Proto.Client/authorization/RoleAssignmentOperations.cs new file mode 100644 index 0000000000000..bf94bb0852a2e --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/authorization/RoleAssignmentOperations.cs @@ -0,0 +1,116 @@ +using Azure; +using Azure.ResourceManager.Authorization; +using Azure.ResourceManager.Core; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Authorization +{ + /// + /// Operations over Role Assignments for Role-based access control to ARM resources + /// + public class RoleAssignmentOperations : ExtensionResourceOperationsBase, IDeletableResource + { + /// + /// Gets the resource type for Role Assignments + /// + public static readonly ResourceType ResourceType = "Microsoft.Authorization/roleAssignments"; + + /// + /// Initializes a new instance of the class. + /// Allows creating operations specific to a role assignment from generic ARM operations for the same resource + /// + /// A generic operations class corresponding to a Role Assignment. + internal RoleAssignmentOperations(GenericResourceOperations genericOperations) + : base(genericOperations) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The http settings to use with these operations. + /// The resource identifier for the RoleAssignment to operate on. + internal RoleAssignmentOperations(OperationsBase operation, ResourceIdentifier id) + : base(operation, id) + { + } + + /// + protected override ResourceType ValidResourceType => ResourceType; + + private RoleAssignmentsOperations Operations => new AuthorizationManagementClient( + Id.Subscription, + BaseUri, + Credential).RoleAssignments; + + /// + /// Delete a role assignment. This operation may involve multiple blocking calls to the service. + /// The operation returns when deletion is complete on the service. + /// + /// The http response returned from the server. + public ArmResponse Delete() + { + return new ArmResponse(Operations.DeleteById(Id).GetRawResponse()); + } + + /// + /// Delete a role assignment. This operation creates a Task to perform and monitor deletion of the role assignment. + /// The task may perform multiple blocking calls, the provided can be + /// used to cancel any of these calls. + /// + /// A token allowing the user to cancel the REST API call. + /// A Task that will yield the http response from the server to the delete request once the Task is completed. + public async Task> DeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmResponse((await Operations.DeleteByIdAsync(Id)).GetRawResponse()); + } + + /// + /// Delete a Role Assignment. This call blocks until the initial response is returned from the service. + /// + /// A token allowing the user to cancel the REST API call. + /// An that allows the user to control how to wait and poll + /// for the delete operation to complete. + public ArmOperation StartDelete(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(Operations.DeleteById(Id, cancellationToken).GetRawResponse()); + } + + /// + /// Delete a Role Assignment. This call returns a Task that blocks until the initial response is returned from the service. + /// The task yields an that allows the user to control how to wait and poll for the + /// delete operation on the service to complete + /// + /// A token allowing the user to cancel the REST API call. + /// A . The task yields an Operation that allows the caller to control how to + /// wait and poll for operation completion on the service. + public async Task> StartDeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation((await Operations.DeleteByIdAsync(Id, cancellationToken)).GetRawResponse()); + } + + /// + /// Gets the RoleAssignment. This call will block until a response is returned from the servcie. + /// + /// A , the http response from the service. + public override ArmResponse Get() + { + return new PhArmResponse( + Operations.GetById(Id), a => new RoleAssignment(this, new RoleAssignmentData(a))); + } + + /// + /// Get the role assignment. This call returns a . When complete, the Task yields the + /// + /// A token allowing the user to cancel the REST API call. + /// A that performs the Get operation. The Task yields a + /// when complete. + public async override Task> GetAsync(CancellationToken cancellationToken = default) + { + return new PhArmResponse( + await Operations.GetByIdAsync(Id, cancellationToken), + a => new RoleAssignment(this, new RoleAssignmentData(a))); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/AvailabilitySet.cs b/sdk/resourcemanager/Proto.Client/compute/AvailabilitySet.cs new file mode 100644 index 0000000000000..07a3dd16ba7c2 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/AvailabilitySet.cs @@ -0,0 +1,39 @@ +using System.Threading.Tasks; +using Azure.ResourceManager.Core; + +namespace Proto.Compute +{ + /// + /// A class representing an availability set along with the instance operations that can be performed on it. + /// + public class AvailabilitySet : AvailabilitySetOperations + { + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The resource that is the target of operations. + internal AvailabilitySet(ResourceOperationsBase options, AvailabilitySetData resource) + : base(options, resource.Id) + { + Data = resource; + } + + /// + /// Gets or sets the availability set data. + /// + public AvailabilitySetData Data { get; private set; } + + /// + protected override AvailabilitySet GetResource() + { + return this; + } + + /// + protected override Task GetResourceAsync() + { + return Task.FromResult(this); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/AvailabilitySetContainer.cs b/sdk/resourcemanager/Proto.Client/compute/AvailabilitySetContainer.cs new file mode 100644 index 0000000000000..11e9b95f5f0b1 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/AvailabilitySetContainer.cs @@ -0,0 +1,157 @@ +using Azure; +using Azure.ResourceManager.Compute; +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Core.Resources; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Compute +{ + /// + /// A class representing collection of availability set and their operations over a resource group. + /// + public class AvailabilitySetContainer : ResourceContainerBase + { + /// + /// Initializes a new instance of the class. + /// + /// The parent resource group. + internal AvailabilitySetContainer(ResourceGroupOperations resourceGroup) + : base(resourceGroup) + { + } + + /// + protected override ResourceType ValidResourceType => ResourceGroupOperations.ResourceType; + + /// + public override ArmResponse CreateOrUpdate(string name, AvailabilitySetData resourceDetails) + { + var response = Operations.CreateOrUpdate(Id.ResourceGroup, name, resourceDetails.Model); + return new PhArmResponse( + response, + a => new AvailabilitySet(Parent, new AvailabilitySetData(a))); + } + + /// + public async override Task> CreateOrUpdateAsync(string name, AvailabilitySetData resourceDetails, CancellationToken cancellationToken = default) + { + var response = await Operations.CreateOrUpdateAsync(Id.ResourceGroup, name, resourceDetails.Model, cancellationToken).ConfigureAwait(false); + return new PhArmResponse( + response, + a => new AvailabilitySet(Parent, new AvailabilitySetData(a))); + } + + /// + public override ArmOperation StartCreateOrUpdate(string name, AvailabilitySetData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + Operations.CreateOrUpdate(Id.ResourceGroup, name, resourceDetails.Model, cancellationToken), + a => new AvailabilitySet(Parent, new AvailabilitySetData(a))); + } + + /// + public async override Task> StartCreateOrUpdateAsync(string name, AvailabilitySetData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + await Operations.CreateOrUpdateAsync(Id.ResourceGroup, name, resourceDetails.Model, cancellationToken).ConfigureAwait(false), + a => new AvailabilitySet(Parent, new AvailabilitySetData(a))); + } + + /// + /// Constructs an object used to create an availability set. + /// + /// The sku name of the resource. + /// The location of the resource. + /// A builder with and . + public ArmBuilder Construct(string skuName, LocationData location = null) + { + var parent = GetParentResource(); + var availabilitySet = new Azure.ResourceManager.Compute.Models.AvailabilitySet(location ?? parent.Data.Location) + { + PlatformUpdateDomainCount = 5, + PlatformFaultDomainCount = 2, + Sku = new Azure.ResourceManager.Compute.Models.Sku() { Name = skuName } + }; + + return new ArmBuilder(this, new AvailabilitySetData(availabilitySet)); + } + + /// + /// Filters the list of availabitlity set for this resource group represented as generic resources. + /// + /// The filter used in this operation. + /// The number of results to return. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of resource that may take multiple service requests to iterate over. + public Pageable ListByName(string filter, int? top = null, CancellationToken cancellationToken = default) + { + ResourceFilterCollection filters = new ResourceFilterCollection(AvailabilitySetData.ResourceType); + filters.SubstringFilter = filter; + return ResourceListOperations.ListAtContext(Parent as ResourceGroupOperations, filters, top, cancellationToken); + } + + /// + /// Filters the list of availabitlity set for this resource group represented as generic resources. + /// + /// The filter used in this operation. + /// The number of results to return. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of resource that may take multiple service requests to iterate over. + public AsyncPageable ListByNameAsync(string filter, int? top = null, CancellationToken cancellationToken = default) + { + ResourceFilterCollection filters = new ResourceFilterCollection(AvailabilitySetData.ResourceType); + filters.SubstringFilter = filter; + return ResourceListOperations.ListAtContextAsync(Parent as ResourceGroupOperations, filters, top, cancellationToken); + } + + /// + /// Filters the list of availabitlity set for this resource group. + /// Makes an additional network call to retrieve the full data model for each resource group. + /// + /// The filter used in this operation. + /// The number of results to return. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of availability set that may take multiple service requests to iterate over. + public Pageable ListByNameExpanded(string filter, int? top = null, CancellationToken cancellationToken = default) + { + var results = ListByName(filter, top, cancellationToken); + return new PhWrappingPageable(results, s => new AvailabilitySetOperations(s).Get().Value); + } + + /// + /// Filters the list of availabitlity set for this resource group. + /// Makes an additional network call to retrieve the full data model for each resource group. + /// + /// The filter used in this operation. + /// The number of results to return. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An asyc collection of availability set that may take multiple service requests to iterate over. + public AsyncPageable ListByNameExpandedAsync(string filter, int? top = null, CancellationToken cancellationToken = default) + { + var results = ListByNameAsync(filter, top, cancellationToken); + return new PhWrappingAsyncPageable(results, s => new AvailabilitySetOperations(s).Get().Value); + } + + private AvailabilitySetsOperations Operations => new ComputeManagementClient( + BaseUri, + Id.Subscription, + Credential, + ClientOptions.Convert()).AvailabilitySets; + + + /// + public override ArmResponse Get(string availabilitySetName) + { + return new PhArmResponse(Operations.Get(Id.ResourceGroup, availabilitySetName), + g => new AvailabilitySet(Parent, new AvailabilitySetData(g))); + } + + /// + public override async Task> GetAsync(string availabilitySetName, CancellationToken cancellationToken = default) + { + return new PhArmResponse(await Operations.GetAsync(Id.ResourceGroup, availabilitySetName, cancellationToken), + g => new AvailabilitySet(Parent, new AvailabilitySetData(g))); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/AvailabilitySetOperations.cs b/sdk/resourcemanager/Proto.Client/compute/AvailabilitySetOperations.cs new file mode 100644 index 0000000000000..2fa2d675a44e8 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/AvailabilitySetOperations.cs @@ -0,0 +1,335 @@ +using Azure; +using Azure.ResourceManager.Compute; +using Azure.ResourceManager.Compute.Models; +using Azure.ResourceManager.Core; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Compute +{ + /// + /// A class representing the operations that can be performed over a specific availability set. + /// + public class AvailabilitySetOperations : ResourceOperationsBase, ITaggableResource, IDeletableResource + { + /// + /// Initializes a new instance of the class. + /// + /// An instance of that has an id for an availability set. + internal AvailabilitySetOperations(GenericResourceOperations genericOperations) + : base(genericOperations) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The name of the availability set to use. + internal AvailabilitySetOperations(ResourceGroupOperations resourceGroup, string availabilitySetName) + : base(resourceGroup, $"{resourceGroup.Id}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}") + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + protected AvailabilitySetOperations(ResourceOperationsBase options, ResourceIdentifier id) + : base(options, id) + { + } + + /// + /// Gets the resource type definition for an availability set. + /// + public static readonly ResourceType ResourceType = "Microsoft.Compute/availabilitySets"; + + /// + protected override ResourceType ValidResourceType => ResourceType; + + private AvailabilitySetsOperations Operations => new ComputeManagementClient( + BaseUri, + Id.Subscription, + Credential, + ClientOptions.Convert()).AvailabilitySets; + + /// + /// The operation to delete an availability set. + /// + /// A response with the operation for this resource. + public ArmResponse Delete() + { + return new ArmResponse(Operations.Delete(Id.ResourceGroup, Id.Name)); + } + + /// + /// The operation to delete an availability set. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + public async Task> DeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmResponse(await Operations.DeleteAsync(Id.ResourceGroup, Id.Name, cancellationToken)); + } + + /// + /// The operation to delete an availability set. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// An that allows polling for completion of the operation. + public ArmOperation StartDelete(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(Operations.Delete(Id.ResourceGroup, Id.Name, cancellationToken)); + } + + /// + /// The operation to delete an availability set. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> StartDeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(await Operations.DeleteAsync(Id.ResourceGroup, Id.Name, cancellationToken)); + } + + /// + public override ArmResponse Get() + { + return new PhArmResponse( + Operations.Get(Id.ResourceGroup, Id.Name), + a => new AvailabilitySet(this, new AvailabilitySetData(a))); + } + + /// + public async override Task> GetAsync(CancellationToken cancellationToken = default) + { + return new PhArmResponse( + await Operations.GetAsync(Id.ResourceGroup, Id.Name, cancellationToken), + a => new AvailabilitySet(this, new AvailabilitySetData(a))); + } + + /// + /// The operation to update an availability set. + /// + /// The parameters to update. + /// The operation of the updated resource. + public ArmResponse Update(AvailabilitySetUpdate patchable) + { + return new PhArmResponse( + Operations.Update(Id.ResourceGroup, Id.Name, patchable), + a => new AvailabilitySet(this, new AvailabilitySetData(a))); + } + + /// + /// The operation to update an availability set. + /// + /// The parameters to update. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns the operation of the updated resource. + public async Task> UpdateAsync(AvailabilitySetUpdate patchable, CancellationToken cancellationToken = default) + { + return new PhArmResponse( + await Operations.UpdateAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + a => new AvailabilitySet(this, new AvailabilitySetData(a))); + } + + /// + /// The operation to update an availability set. + /// + /// The parameters to update. + /// The operation of the updated resource. + public ArmOperation StartUpdate(AvailabilitySetUpdate patchable) + { + return new PhArmOperation( + Operations.Update(Id.ResourceGroup, Id.Name, patchable), + a => new AvailabilitySet(this, new AvailabilitySetData(a))); + } + + /// + /// The operation to update an availability set. + /// + /// The parameters to update. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns the operation of the updated resource. + public async Task> StartUpdateAsync(AvailabilitySetUpdate patchable, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + await Operations.UpdateAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + a => new AvailabilitySet(this, new AvailabilitySetData(a))); + } + + /// + /// Adds a tag to an availability set. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// An that allows polling for completion of the operation. + public ArmResponse AddTag(string key, string value) + { + var resource = GetResource(); + var patchable = new AvailabilitySetUpdate(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return Update(patchable); + } + + /// + /// Adds a tag to an availability set. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new AvailabilitySetUpdate(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return await UpdateAsync(patchable); + } + + /// + /// Adds a tag to an availability set. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// + /// Details on long running operation object. + /// + /// An that allows polling for completion of the operation. + public ArmOperation StartAddTag(string key, string value) + { + var resource = GetResource(); + var patchable = new AvailabilitySetUpdate(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return StartUpdate(patchable); + } + + /// + /// Adds a tag to an availability set. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> StartAddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new AvailabilitySetUpdate(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return await StartUpdateAsync(patchable); + } + + /// + public ArmResponse SetTags(IDictionary tags) + { + var patchable = new AvailabilitySetUpdate(); + patchable.Tags.ReplaceWith(tags); + return Update(patchable); + } + + /// + public async Task> SetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + var patchable = new AvailabilitySetUpdate(); + patchable.Tags.ReplaceWith(tags); + return await UpdateAsync(patchable); + } + + /// + public ArmOperation StartSetTags(IDictionary tags) + { + var patchable = new AvailabilitySetUpdate(); + patchable.Tags.ReplaceWith(tags); + return StartUpdate(patchable); + } + + /// + public async Task> StartSetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + var patchable = new AvailabilitySetUpdate(); + patchable.Tags.ReplaceWith(tags); + return await StartUpdateAsync(patchable); + } + + /// + public ArmResponse RemoveTag(string key) + { + var resource = GetResource(); + var patchable = new AvailabilitySetUpdate(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return Update(patchable); + } + + /// + public async Task> RemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new AvailabilitySetUpdate(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return await UpdateAsync(patchable); + } + + /// + public ArmOperation StartRemoveTag(string key) + { + var resource = GetResource(); + var patchable = new AvailabilitySetUpdate(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return StartUpdate(patchable); + } + + /// + public async Task> StartRemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new AvailabilitySetUpdate(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return await StartUpdateAsync(patchable); + } + + /// + /// Lists all available geo-locations. + /// + /// A collection of location that may take multiple service requests to iterate over. + public IEnumerable ListAvailableLocations() + { + return ListAvailableLocations(ResourceType); + } + + /// + /// Lists all available geo-locations. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of location that may take multiple service requests to iterate over. + /// The default subscription id is null. + public async Task> ListAvailableLocationsAsync(CancellationToken cancellationToken = default) + { + return await ListAvailableLocationsAsync(ResourceType, cancellationToken); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/ComputeRestApiVersions.cs b/sdk/resourcemanager/Proto.Client/compute/ComputeRestApiVersions.cs new file mode 100644 index 0000000000000..e9f12a385023e --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/ComputeRestApiVersions.cs @@ -0,0 +1,24 @@ +namespace Proto.Compute +{ + /// + /// A class representing which api version to use for each compute resource. + /// + public class ComputeRestApiVersions + { + internal ComputeRestApiVersions() + { + VirtualMachinesVersion = VirtualMachinesApiVersions.Default; + AvailabilitySetsVersion = AvailabilitySetsApiVersions.Default; + } + + /// + /// Gets or sets the virtual machine api version. + /// + public VirtualMachinesApiVersions VirtualMachinesVersion { get; set; } + + /// + /// Gets or sets the availability set api version. + /// + public AvailabilitySetsApiVersions AvailabilitySetsVersion { get; set; } + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/Convenience/VirtualMachineModelBuilder.cs b/sdk/resourcemanager/Proto.Client/compute/Convenience/VirtualMachineModelBuilder.cs new file mode 100644 index 0000000000000..79a31fecf2cf4 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/Convenience/VirtualMachineModelBuilder.cs @@ -0,0 +1,57 @@ +using Azure.ResourceManager.Core; +using System; + +namespace Proto.Compute.Convenience +{ + /// + /// A class representing a builder object to help create a virtual machine. + /// + public class VirtualMachineModelBuilder : VirtualMachineModelBuilderBase + { + /// + /// Initializes a new instance of the class. + /// + /// The container to create the virtual machine in. + /// The data model representing the virtual machine to create. + public VirtualMachineModelBuilder(VirtualMachineContainer containerOperations, VirtualMachineData vm): base(containerOperations, vm) + { + // TODO: GENERATOR Update Builder after models are incorporated in generated models + // _model.Name = vmName; + //_model = new VirtualMachine(location); + } + + /// + /// Attaches a disk to the virtual machine to be created. + /// + /// The disk to attach. + /// An instance of + public VirtualMachineModelBuilderBase AttachDataDisk(TrackedResource azureEntity) + { + throw new NotImplementedException(); + } + + /// + public override VirtualMachineModelBuilderBase UseWindowsImage(string adminUser, string password) + { + throw new NotImplementedException(); + } + + /// + public override VirtualMachineModelBuilderBase UseLinuxImage(string adminUser, string password) + { + throw new NotImplementedException(); + } + + /// + public override VirtualMachineModelBuilderBase RequiredNetworkInterface(ResourceIdentifier nicResourceId) + { + throw new NotImplementedException(); + } + + /// + public override VirtualMachineModelBuilderBase RequiredAvalabilitySet(ResourceIdentifier asetResourceId) + { + throw new NotImplementedException(); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/Convenience/VirtualMachineModelBuilderBase.cs b/sdk/resourcemanager/Proto.Client/compute/Convenience/VirtualMachineModelBuilderBase.cs new file mode 100644 index 0000000000000..b3ee5ee648f8d --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/Convenience/VirtualMachineModelBuilderBase.cs @@ -0,0 +1,50 @@ +using Azure.ResourceManager.Core; + +namespace Proto.Compute.Convenience +{ + /// + /// A class representing the base for a builder object to help create a virtual machine. + /// + public abstract class VirtualMachineModelBuilderBase : ArmBuilder + { + /// + /// Initializes a new instance of . + /// + /// The that the virtual machine will be built in. + /// The data model representing the virtual machine to create. + protected VirtualMachineModelBuilderBase(VirtualMachineContainer containerOperations, VirtualMachineData vm) + : base(containerOperations, vm) + { + } + + /// + /// Tells the builder to use a windows image. + /// + /// The admin username for the virtual machine. + /// The asmin password for the virtual machine. + /// An instance of . + public abstract VirtualMachineModelBuilderBase UseWindowsImage(string adminUser, string password); + + /// + /// Tells the builder to use a linux image. + /// + /// The admin username for the virtual machine. + /// The asmin password for the virtual machine. + /// An instance of . + public abstract VirtualMachineModelBuilderBase UseLinuxImage(string adminUser, string password); + + /// + /// Tells the builder to use a specific network interface. + /// + /// The network interface identifier. + /// An instance of . + public abstract VirtualMachineModelBuilderBase RequiredNetworkInterface(ResourceIdentifier nicResourceId); + + /// + /// Tells the builder to use a specific availability set. + /// + /// The availability set identifier. + /// An instance of . + public abstract VirtualMachineModelBuilderBase RequiredAvalabilitySet(ResourceIdentifier asetResourceId); + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/Extensions/ArmClientExtensions.cs b/sdk/resourcemanager/Proto.Client/compute/Extensions/ArmClientExtensions.cs new file mode 100644 index 0000000000000..1601ce928cc87 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/Extensions/ArmClientExtensions.cs @@ -0,0 +1,48 @@ +using Azure.ResourceManager.Core; +using System; + +namespace Proto.Compute +{ + /// + /// A class to add extension methods to an ArmClient. + /// + public static class ArmClientExtensions + { + + /// + /// Gets the AvailabilitySetOperations. + /// + /// The instance the method will execute against. + /// The ResourceIdentifier of the resource that is the target of operations. + /// Returns an object representing the operations that can be performed over a specific . + /// ResourceIdentifier provided is not for an AvailabilitySet. + /// ResourceIdentifier cannot be null. + public static AvailabilitySetOperations GetAvailabilitySetOperations(this AzureResourceManagerClient client, ResourceIdentifier resourceId) + { + if (resourceId is null) + throw new ArgumentNullException(nameof(resourceId)); + if (resourceId.Type != AvailabilitySetOperations.ResourceType) + throw new ArgumentException($"{nameof(resourceId.Type)} provided is not for an AvailabilitySet.", nameof(resourceId.Type)); + + return client.GetSubscriptionOperations(resourceId.Subscription).GetResourceGroupOperations(resourceId.ResourceGroup).GetAvailabilitySetOperations(resourceId.Name); + } + + /// + /// Gets the VirtualMachineOperations. + /// + /// The instance the method will execute against. + /// The ResourceIdentifier of the resource that is the target of operations. + /// Returns an object representing the operations that can be performed over a specific . + /// ResourceIdentifier provided is not for a VirtualMachine. + /// ResourceIdentifier cannot be null. + public static VirtualMachineOperations GetVirtualMachineOperations(this AzureResourceManagerClient client, ResourceIdentifier resourceId) + { + if (resourceId is null) + throw new ArgumentNullException(nameof(resourceId)); + if (resourceId.Type != VirtualMachineOperations.ResourceType) + throw new ArgumentException($"{nameof(resourceId.Type)} provided is not for a VirtualMachine.", nameof(resourceId.Type)); + + return client.GetSubscriptionOperations(resourceId.Subscription).GetResourceGroupOperations(resourceId.ResourceGroup).GetVirtualMachineOperations(resourceId.Name); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/Extensions/AzureResourceManagerClientOptionsExtensions.cs b/sdk/resourcemanager/Proto.Client/compute/Extensions/AzureResourceManagerClientOptionsExtensions.cs new file mode 100644 index 0000000000000..de3bb64817512 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/Extensions/AzureResourceManagerClientOptionsExtensions.cs @@ -0,0 +1,20 @@ +using Azure.ResourceManager.Core; + +namespace Proto.Compute.Extensions +{ + /// + /// A class to add extension methods to AzureResourceManagerClientOptions. + /// + public static class AzureResourceManagerClientOptionsExtensions + { + /// + /// Adds a method to AzureResourceManagerClientOptions which returns all the versions to all resources inside the compute resource provider. + /// + /// The instance the method will execute against. + /// Returns a response with the operation for this resource. + public static ComputeRestApiVersions GetComputeRestApiVersions(this AzureResourceManagerClientOptions azureResourceManagerClientOptions) + { + return azureResourceManagerClientOptions.GetOverrideObject(() => new ComputeRestApiVersions()) as ComputeRestApiVersions; + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/Extensions/ResourceGroupExtensions.cs b/sdk/resourcemanager/Proto.Client/compute/Extensions/ResourceGroupExtensions.cs new file mode 100644 index 0000000000000..1031a20918536 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/Extensions/ResourceGroupExtensions.cs @@ -0,0 +1,63 @@ +using Azure.ResourceManager.Core; +using System; + +namespace Proto.Compute +{ + /// + /// A class to add extension methods to ResourceGroup. + /// + public static class ResourceGroupExtensions + { + #region VirtualMachines + /// + /// Gets an object representing the operations that can be performed over a specific VirtualMachine. + /// + /// The instance the method will execute against. + /// The name of the VirtualMachine. + /// Returns an object representing the operations that can be performed over a specific . + /// vmName cannot be null or a whitespace. + public static VirtualMachineOperations GetVirtualMachineOperations(this ResourceGroupOperations resourceGroup, string vmName) + { + if (string.IsNullOrWhiteSpace(vmName)) + throw new ArgumentException($"{nameof(vmName)} cannot be null or a whitespace.", nameof(vmName)); + return new VirtualMachineOperations(resourceGroup, vmName); + } + + /// + /// Gets an object representing a VirtualMachineContainer along with the instance operations that can be performed on it. + /// + /// The instance the method will execute against. + /// Returns a object. + public static VirtualMachineContainer GetVirtualMachineContainer(this ResourceGroupOperations resourceGroup) + { + return new VirtualMachineContainer(resourceGroup); + } + #endregion + + #region AvailabilitySets + /// + /// Gets an object representing the operations that can be performed over a specific AvailabilitySet. + /// + /// The instance the method will execute against. + /// The name of the AvailibilitySet. + /// Returns an object representing the operations that can be performed over a specific . + /// availabilitySetName cannot be null or a whitespace. + public static AvailabilitySetOperations GetAvailabilitySetOperations(this ResourceGroupOperations resourceGroup, string availabilitySetName) + { + if (string.IsNullOrWhiteSpace(availabilitySetName)) + throw new ArgumentException($"{nameof(availabilitySetName)} cannot be null or a whitespace.", nameof(availabilitySetName)); + return new AvailabilitySetOperations(resourceGroup, availabilitySetName); + } + + /// + /// Gets an object representing a AvailabilitySetContainer along with the instance operations that can be performed on it. + /// + /// The instance the method will execute against. + /// Returns an object. + public static AvailabilitySetContainer GetAvailabilitySetContainer(this ResourceGroupOperations resourceGroup) + { + return new AvailabilitySetContainer(resourceGroup); + } + #endregion + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/Extensions/SubscriptionExtensions.cs b/sdk/resourcemanager/Proto.Client/compute/Extensions/SubscriptionExtensions.cs new file mode 100644 index 0000000000000..8a9c3d619395a --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/Extensions/SubscriptionExtensions.cs @@ -0,0 +1,117 @@ +using Azure; +using Azure.ResourceManager.Compute; +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Core.Adapters; +using Azure.ResourceManager.Core.Resources; +using System.Threading; + +namespace Proto.Compute +{ + /// + /// Extension methods for convenient access on SubscriptionOperations in a client + /// + public static class SubscriptionExtensions + { + #region Virtual Machine List Operations + /// + /// Lists the VirtualMachines for this SubscriptionOperations. + /// + /// The instance the method will execute against. + /// A collection of resource operations that may take multiple service requests to iterate over. + public static Pageable ListVirtualMachines(this SubscriptionOperations subscription) + { + ComputeManagementClient computeClient = GetComputeClient(subscription); + var vmOperations = computeClient.VirtualMachines; + var result = vmOperations.ListAll(); + return new PhWrappingPageable( + result, + s => new VirtualMachine(subscription, new VirtualMachineData(s))); + } + + private static ComputeManagementClient GetComputeClient(SubscriptionOperations subscription) + { + return new ComputeManagementClient( + subscription.BaseUri, + subscription.Id.Subscription, + subscription.Credential, + subscription.ClientOptions.Convert()); + } + + /// + /// Lists the VirtualMachines for this SubscriptionOperations. + /// + /// The instance the method will execute against. + /// An async collection of resource operations that may take multiple service requests to iterate over. + public static AsyncPageable ListVirtualMachinesAsync(this SubscriptionOperations subscription) + { + var vmOperations = GetComputeClient(subscription).VirtualMachines; + var result = vmOperations.ListAllAsync(); + return new PhWrappingAsyncPageable( + result, + s => new VirtualMachine(subscription, new VirtualMachineData(s))); + } + + /// + /// Filters the list of VMs for a SubscriptionOperations represented as generic resources. + /// + /// The instance the method will execute against. + /// The string to filter the list. + /// The number of results to return. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of resource operations that may take multiple service requests to iterate over. + public static Pageable ListVirtualMachinesByName(this SubscriptionOperations subscription, string filter, int? top = null, CancellationToken cancellationToken = default) + { + ResourceFilterCollection filters = new ResourceFilterCollection(VirtualMachineOperations.ResourceType); + filters.SubstringFilter = filter; + return ResourceListOperations.ListAtContext(subscription, filters, top, cancellationToken); + } + + /// + /// Filters the list of VMs for a SubscriptionOperations represented as generic resources. + /// + /// The instance the method will execute against. + /// The string to filter the list. + /// The number of results to return. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of resource operations that may take multiple service requests to iterate over. + public static AsyncPageable ListVirtualMachinesByNameAsync(this SubscriptionOperations subscription, string filter, int? top = null, CancellationToken cancellationToken = default) + { + ResourceFilterCollection filters = new ResourceFilterCollection(VirtualMachineOperations.ResourceType); + filters.SubstringFilter = filter; + return ResourceListOperations.ListAtContextAsync(subscription, filters, top, cancellationToken); + } + #endregion + + #region AvailabilitySet List Operations + /// + /// Lists the AvailabilitySets for this SubscriptionOperations. + /// + /// The instance the method will execute against. + /// A collection of resource operations that may take multiple service requests to iterate over. + public static Pageable ListAvailabilitySets(this SubscriptionOperations subscription) + { + ComputeManagementClient computeClient = GetComputeClient(subscription); + var availabilitySetOperations = computeClient.AvailabilitySets; + var result = availabilitySetOperations.ListBySubscription(); + return new PhWrappingPageable( + result, + s => new AvailabilitySet(subscription, new AvailabilitySetData(s))); + } + + /// + /// Lists the AvailabilitySets for this SubscriptionOperations. + /// + /// The instance the method will execute against. + /// An async collection of resource operations that may take multiple service requests to iterate over. + public static AsyncPageable ListAvailabilitySetsAsync(this SubscriptionOperations subscription) + { + ComputeManagementClient computeClient = GetComputeClient(subscription); + var availabilitySetOperations = computeClient.AvailabilitySets; + var result = availabilitySetOperations.ListBySubscriptionAsync(); + return new PhWrappingAsyncPageable( + result, + s => new AvailabilitySet(subscription, new AvailabilitySetData(s))); + } + #endregion + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/Placeholder/AvailabilitySetData.cs b/sdk/resourcemanager/Proto.Client/compute/Placeholder/AvailabilitySetData.cs new file mode 100644 index 0000000000000..57b1f66a3602a --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/Placeholder/AvailabilitySetData.cs @@ -0,0 +1,70 @@ +using Azure.ResourceManager.Compute.Models; +using Azure.ResourceManager.Core; +using System; +using System.Collections.Generic; + +namespace Proto.Compute +{ + /// + /// A class representing the availability set data model. + /// + public class AvailabilitySetData : TrackedResource + { + /// + /// Gets the resource type definition for an availability set. + /// + public static ResourceType ResourceType => "Microsoft.Compute/availabilitySets"; + + /// + /// Initializes a new instance of the class. + /// + /// The availability set to initialize. + public AvailabilitySetData(Azure.ResourceManager.Compute.Models.AvailabilitySet aset) + : base(aset.Id, aset.Location, aset) + { + } + + /// Resource tags. + public override IDictionary Tags => Model.Tags; + + /// Resource name. + public override string Name => Model.Name; + + /// Sku of the availability set, only name is required to be set. See AvailabilitySetSkuTypes for possible set of values. Use 'Aligned' for virtual machines with managed disks and 'Classic' for virtual machines with unmanaged disks. Default value is 'Classic'. + public Azure.ResourceManager.Compute.Models.Sku Sku + { + get => Model.Sku; + set => Model.Sku = value; + } + + /// The number of update domains that the availaility set can span. + public int? PlatformUpdateDomainCount + { + get => Model.PlatformUpdateDomainCount; + set => Model.PlatformUpdateDomainCount = value; + } + + /// The number of fault domains that the availaility set can span. + public int? PlatformFaultDomainCount + { + get => Model.PlatformFaultDomainCount; + set => Model.PlatformFaultDomainCount = value; + } + + /// A list of references to all virtual machines in the availability set. + public IList VirtualMachines + { + get => Model.VirtualMachines; + } + + /// Specifies information about the proximity placement group that the availability set should be assigned to. <br><br>Minimum api-version: 2018-04-01. + public SubResource ProximityPlacementGroup + { + get => Model.ProximityPlacementGroup; + set => Model.ProximityPlacementGroup = value; + } + + /// The resource status information. + public IReadOnlyList Statuses => Model.Statuses; + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/Placeholder/VirtualMachineData.cs b/sdk/resourcemanager/Proto.Client/compute/Placeholder/VirtualMachineData.cs new file mode 100644 index 0000000000000..65f46a4961fc5 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/Placeholder/VirtualMachineData.cs @@ -0,0 +1,175 @@ +using Azure.ResourceManager.Compute.Models; +using Azure.ResourceManager.Core; +using System; +using System.Collections.Generic; + +namespace Proto.Compute +{ + /// + /// A class representing the VirtualMachine data model. + /// + public class VirtualMachineData : TrackedResource + { + /// + /// Initializes a new instance of the class. + /// + /// The virtual machine to initialize. + public VirtualMachineData(Azure.ResourceManager.Compute.Models.VirtualMachine vm) : base(vm.Id, vm.Location, vm) + { + } + + /// Resource tags. + public override IDictionary Tags => Model.Tags; + + /// Resource name. + public override string Name => Model.Name; + + /// The virtual machine instance view. + public VirtualMachineInstanceView InstanceView => Model.InstanceView; + + /// The provisioning state, which only appears in the response. + public string ProvisioningState => Model.ProvisioningState; + + /// Specifies information about the dedicated host that the virtual machine resides in. <br><br>Minimum api-version: 2018-10-01. + public SubResource Host + { + get => Model.Host; + set => Model.Host = value; + } + + /// Specifies the billing related details of a Azure Spot virtual machine. <br><br>Minimum api-version: 2019-03-01. + public BillingProfile BillingProfile + { + get => Model.BillingProfile; + set => Model.BillingProfile = value; + } + + /// Specifies the eviction policy for the Azure Spot virtual machine and Azure Spot scale set. <br><br>For Azure Spot virtual machines, the only supported value is 'Deallocate' and the minimum api-version is 2019-03-01. <br><br>For Azure Spot scale sets, both 'Deallocate' and 'Delete' are supported and the minimum api-version is 2017-10-30-preview. + public VirtualMachineEvictionPolicyTypes? EvictionPolicy + { + get => Model.EvictionPolicy; + set => Model.EvictionPolicy = value; + } + + /// Specifies the priority for the virtual machine. <br><br>Minimum api-version: 2019-03-01. + public VirtualMachinePriorityTypes? Priority + { + get => Model.Priority; + set => Model.Priority = value; + } + + /// Specifies information about the proximity placement group that the virtual machine should be assigned to. <br><br>Minimum api-version: 2018-04-01. + public SubResource ProximityPlacementGroup + { + get => Model.ProximityPlacementGroup; + set => Model.ProximityPlacementGroup = value; + } + + /// Specifies information about the virtual machine scale set that the virtual machine should be assigned to. Virtual machines specified in the same virtual machine scale set are allocated to different nodes to maximize availability. Currently, a VM can only be added to virtual machine scale set at creation time. An existing VM cannot be added to a virtual machine scale set. <br><br>This property cannot exist along with a non-null properties.availabilitySet reference. <br><br>Minimum api‐version: 2019‐03‐01. + public SubResource VirtualMachineScaleSet + { + get => Model.VirtualMachineScaleSet; + set => Model.VirtualMachineScaleSet = value; + } + + /// Specifies information about the availability set that the virtual machine should be assigned to. Virtual machines specified in the same availability set are allocated to different nodes to maximize availability. For more information about availability sets, see [Manage the availability of virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-manage-availability?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). <br><br> For more information on Azure planned maintenance, see [Planned maintenance for virtual machines in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-planned-maintenance?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> Currently, a VM can only be added to availability set at creation time. The availability set to which the VM is being added should be under the same resource group as the availability set resource. An existing VM cannot be added to an availability set. <br><br>This property cannot exist along with a non-null properties.virtualMachineScaleSet reference. + public SubResource AvailabilitySet + { + get => Model.AvailabilitySet; + set => Model.AvailabilitySet = value; + } + + /// Specifies the boot diagnostic settings state. <br><br>Minimum api-version: 2015-06-15. + public DiagnosticsProfile DiagnosticsProfile + { + get => Model.DiagnosticsProfile; + set => Model.DiagnosticsProfile = value; + } + + /// Specifies the network interfaces of the virtual machine. + public NetworkProfile NetworkProfile + { + get => Model.NetworkProfile; + set => Model.NetworkProfile = value; + } + + /// Specifies the operating system settings used while creating the virtual machine. Some of the settings cannot be changed once VM is provisioned. + public OSProfile OsProfile + { + get => Model.OsProfile; + set => Model.OsProfile = value; + } + + /// Specifies additional capabilities enabled or disabled on the virtual machine. + public AdditionalCapabilities AdditionalCapabilities + { + get => Model.AdditionalCapabilities; + set => Model.AdditionalCapabilities = value; + } + + /// Specifies the storage settings for the virtual machine disks. + public StorageProfile StorageProfile + { + get => Model.StorageProfile; + set => Model.StorageProfile = value; + } + + /// Specifies the hardware settings for the virtual machine. + public HardwareProfile HardwareProfile + { + get => Model.HardwareProfile; + set => Model.HardwareProfile = value; + } + + /// The virtual machine zones. + public IList Zones + { + get => Model.Zones; + } + + /// The identity of the virtual machine, if configured. + public ResourceIdentity Identity + { + get => VmIdentityToIdentity(Model.Identity); + } + + private ResourceIdentity VmIdentityToIdentity(VirtualMachineIdentity vmIdentity) + { + SystemAssignedIdentity systemAssignedIdentity = new SystemAssignedIdentity(new Guid(vmIdentity.TenantId), new Guid(vmIdentity.PrincipalId)); + var userAssignedIdentities = new Dictionary(); + if (vmIdentity.UserAssignedIdentities != null) + { + foreach (var entry in vmIdentity.UserAssignedIdentities) + { + ResourceIdentifier resourceId = new ResourceIdentifier(entry.Key); + var userAssignedIdentity = new UserAssignedIdentity(new Guid(entry.Value.ClientId), new Guid(entry.Value.PrincipalId)); + userAssignedIdentities[resourceId] = userAssignedIdentity; + } + } + + return new ResourceIdentity(systemAssignedIdentity, userAssignedIdentities); + } + + /// + /// Gets the virtual machine extensions. + /// + public IReadOnlyList Resources => Model.Resources; + + /// Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace images. Before you can use a marketplace image from an API, you must enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click **Want to deploy programmatically, Get Started ->**. Enter any required information and then click **Save**. + public Azure.ResourceManager.Compute.Models.Plan Plan + { + get => Model.Plan; + set => Model.Plan = value; + } + + /// Specifies that the image or disk that is being used was licensed on-premises. This element is only used for images that contain the Windows Server operating system. <br><br> Possible values are: <br><br> Windows_Client <br><br> Windows_Server <br><br> If this element is included in a request for an update, the value must match the initial value. This value cannot be updated. <br><br> For more information, see [Azure Hybrid Use Benefit for Windows Server](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-hybrid-use-benefit-licensing?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> Minimum api-version: 2015-06-15. + public string LicenseType + { + get => Model.LicenseType; + set => Model.LicenseType = value; + } + + /// Specifies the VM unique ID which is a 128-bits identifier that is encoded and stored in all Azure IaaS VMs SMBIOS and can be read using platform BIOS commands. + public string VmId => Model.VmId; + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/Proto.Compute.csproj b/sdk/resourcemanager/Proto.Client/compute/Proto.Compute.csproj new file mode 100644 index 0000000000000..c0592e2e8b519 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/Proto.Compute.csproj @@ -0,0 +1,19 @@ + + + + netstandard2.0 + Proto.Compute + latest + + + + + + + + + + + + + diff --git a/sdk/resourcemanager/Proto.Client/compute/README.MD b/sdk/resourcemanager/Proto.Client/compute/README.MD new file mode 100644 index 0000000000000..c5d39b78c6da7 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/README.MD @@ -0,0 +1,3 @@ +# Proto Compute + +Prototype version of Azure.ResourceManager.Compute used to showcase and test the new prototype track 2 management plane SDK \ No newline at end of file diff --git a/sdk/resourcemanager/Proto.Client/compute/VersionOverrides/AvailabilitySetsApiVersions.cs b/sdk/resourcemanager/Proto.Client/compute/VersionOverrides/AvailabilitySetsApiVersions.cs new file mode 100644 index 0000000000000..66c947505b17e --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/VersionOverrides/AvailabilitySetsApiVersions.cs @@ -0,0 +1,38 @@ +using Azure.ResourceManager.Core; + +namespace Proto.Compute +{ + /// + /// A class representing the valid api versions for an availability set. + /// + public class AvailabilitySetsApiVersions : ApiVersionsBase + { + /// + /// Api version for 2020/05/01. + /// + public static readonly AvailabilitySetsApiVersions V2020_05_01 = new AvailabilitySetsApiVersions("2020-05-01"); + + /// + /// Api version for 2019/12/01. + /// + public static readonly AvailabilitySetsApiVersions V2019_12_01 = new AvailabilitySetsApiVersions("2019-12-01"); + + /// + /// Default api version to use. + /// + public static readonly AvailabilitySetsApiVersions Default = V2020_05_01; + + private AvailabilitySetsApiVersions(string value) : base(value) { } + + /// + /// Converts an api version into a string. + /// + /// The api version instnace to convert. + public static implicit operator string(AvailabilitySetsApiVersions version) + { + if (version == null) + return null; + return version.ToString(); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/VersionOverrides/VirtualMachinesApiVersions.cs b/sdk/resourcemanager/Proto.Client/compute/VersionOverrides/VirtualMachinesApiVersions.cs new file mode 100644 index 0000000000000..adbfffde2c61c --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/VersionOverrides/VirtualMachinesApiVersions.cs @@ -0,0 +1,38 @@ +using Azure.ResourceManager.Core; + +namespace Proto.Compute +{ + /// + /// A class representing the valid api versions for a virtual machine. + /// + public class VirtualMachinesApiVersions : ApiVersionsBase + { + /// + /// Api version 2020/06/01 + /// + public static readonly VirtualMachinesApiVersions V2020_06_01 = new VirtualMachinesApiVersions("2020-06-01"); + + /// + /// Api version 2019/12/01 + /// + public static readonly VirtualMachinesApiVersions V2019_12_01 = new VirtualMachinesApiVersions("2019-12-01"); + + /// + /// Default api version to use. + /// + public static readonly VirtualMachinesApiVersions Default = V2020_06_01; + + private VirtualMachinesApiVersions(string value) : base(value) { } + + /// + /// Converts an api version into a string. + /// + /// The api version instnace to convert. + public static implicit operator string(VirtualMachinesApiVersions version) + { + if (version == null) + return null; + return version.ToString(); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/VirtualMachine.cs b/sdk/resourcemanager/Proto.Client/compute/VirtualMachine.cs new file mode 100644 index 0000000000000..f2397f51ec2ac --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/VirtualMachine.cs @@ -0,0 +1,39 @@ +using System.Threading.Tasks; +using Azure.ResourceManager.Core; + +namespace Proto.Compute +{ + /// + /// Class representing a VirtualMachine along with the instance operations that can be performed on it. + /// + public class VirtualMachine : VirtualMachineOperations + { + /// + /// Gets the data representing this VirtualMachine. + /// + public VirtualMachineData Data { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The resource that is the target of operations. + internal VirtualMachine(ResourceOperationsBase operations, VirtualMachineData resource) + : base(operations, resource.Id) + { + Data = resource; + } + + /// + protected override VirtualMachine GetResource() + { + return this; + } + + /// + protected override Task GetResourceAsync() + { + return Task.FromResult(this); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/VirtualMachineContainer.cs b/sdk/resourcemanager/Proto.Client/compute/VirtualMachineContainer.cs new file mode 100644 index 0000000000000..aa8e158fd3496 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/VirtualMachineContainer.cs @@ -0,0 +1,238 @@ +using Azure; +using Azure.ResourceManager.Compute; +using Azure.ResourceManager.Compute.Models; +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Core.Resources; +using Proto.Compute.Convenience; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Compute +{ + /// + /// A class representing collection of VirtualMachine and their operations over a ResourceGroup. + /// + public class VirtualMachineContainer : ResourceContainerBase + { + /// + /// Initializes a new instance of the class. + /// + /// The ResourceGroup that is the parent of the VirtualMachines. + internal VirtualMachineContainer(ResourceGroupOperations resourceGroup) + : base(resourceGroup) + { + } + + private VirtualMachinesOperations Operations => new ComputeManagementClient( + BaseUri, + Id.Subscription, + Credential, + ClientOptions.Convert()).VirtualMachines; + + /// + /// Gets the valid resource type for this object + /// + protected override ResourceType ValidResourceType => ResourceGroupOperations.ResourceType; + + /// + /// The operation to create a virtual machine. + /// + /// The name of the virtual machine. + /// Parameters supplied to the Create Virtual Machine operation. + /// A response with the operation for this resource. + public override ArmResponse CreateOrUpdate(string name, VirtualMachineData resourceDetails) + { + var operation = Operations.StartCreateOrUpdate(Id.ResourceGroup, name, resourceDetails.Model); + return new PhArmResponse( + operation.WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult(), + v => new VirtualMachine(Parent, new VirtualMachineData(v))); + } + + /// + /// The operation to create a virtual machine. + /// + /// The name of the virtual machine. + /// Parameters supplied to the Create Virtual Machine operation. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + public async override Task> CreateOrUpdateAsync(string name, VirtualMachineData resourceDetails, CancellationToken cancellationToken = default) + { + var operation = await Operations.StartCreateOrUpdateAsync(Id.ResourceGroup, name, resourceDetails.Model, cancellationToken).ConfigureAwait(false); + return new PhArmResponse( + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false), + v => new VirtualMachine(Parent, new VirtualMachineData(v))); + } + + /// + /// The operation to create a virtual machine. + /// + /// The name of the virtual machine. + /// Parameters supplied to the Create Virtual Machine operation. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// An that allows polling for completion of the operation. + public override ArmOperation StartCreateOrUpdate(string name, VirtualMachineData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + Operations.StartCreateOrUpdate(Id.ResourceGroup, name, resourceDetails.Model, cancellationToken), + v => new VirtualMachine(Parent, new VirtualMachineData(v))); + } + + /// + /// The operation to create a virtual machine. + /// + /// The name of the virtual machine. + /// Parameters supplied to the Create Virtual Machine operation. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// A that on completion returns an that allows polling for completion of the operation. + public async override Task> StartCreateOrUpdateAsync(string name, VirtualMachineData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + await Operations.StartCreateOrUpdateAsync(Id.ResourceGroup, name, resourceDetails.Model, cancellationToken).ConfigureAwait(false), + v => new VirtualMachine(Parent, new VirtualMachineData(v))); + } + + /// + /// Construct an object used to create a VirtualMachine. + /// + /// The hostname for the virtual machine. + /// The admin username to use. + /// The admin password to use. + /// The network interface id to use. + /// The availability set id to use. + /// The location to create the Virtual Machine. + /// Object used to create a . + public VirtualMachineModelBuilder Construct(string hostName, string adminUser, string adminPassword, ResourceIdentifier networkInterfaceId, ResourceIdentifier availabilitySetId, LocationData location = null) + { + var parent = GetParentResource(); + var vm = new Azure.ResourceManager.Compute.Models.VirtualMachine(location ?? parent.Data.Location) + { + NetworkProfile = new NetworkProfile(), + OsProfile = new OSProfile + { + ComputerName = hostName, + AdminUsername = adminUser, + AdminPassword = adminPassword, + WindowsConfiguration = new WindowsConfiguration { TimeZone = "Pacific Standard Time", ProvisionVMAgent = true } + }, + StorageProfile = new StorageProfile() + { + ImageReference = new ImageReference() + { + Offer = "WindowsServer", + Publisher = "MicrosoftWindowsServer", + Sku = "2019-Datacenter", + Version = "latest" + }, + }, + HardwareProfile = new HardwareProfile() { VmSize = VirtualMachineSizeTypes.StandardB1Ms }, + AvailabilitySet = new SubResource() { Id = availabilitySetId } + }; + vm.NetworkProfile.NetworkInterfaces.Add(new NetworkInterfaceReference() { Id = networkInterfaceId }); + + return new VirtualMachineModelBuilder(this, new VirtualMachineData(vm)); + } + + /// + /// List the virtual machines for this resource group. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of that may take multiple service requests to iterate over. + public Pageable List(CancellationToken cancellationToken = default) + { + var result = Operations.List(Id.Name, cancellationToken); + return new PhWrappingPageable( + result, + s => new VirtualMachine(Parent, new VirtualMachineData(s))); + } + + /// + /// List the virtual machines for this resource group. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of that may take multiple service requests to iterate over. + public AsyncPageable ListAsync(CancellationToken cancellationToken = default) + { + var result = Operations.ListAsync(Id.Name, cancellationToken); + return new PhWrappingAsyncPageable( + result, + s => new VirtualMachine(Parent, new VirtualMachineData(s))); + } + + /// + /// Filters the list of virtual machines for this resource group represented as generic resources. + /// + /// The substring to filter by. + /// The number of items to truncate by. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of that may take multiple service requests to iterate over. + public Pageable ListByName(string filter, int? top = null, CancellationToken cancellationToken = default) + { + ResourceFilterCollection filters = new ResourceFilterCollection(VirtualMachineOperations.ResourceType); + filters.SubstringFilter = filter; + return ResourceListOperations.ListAtContext(Parent as ResourceGroupOperations, filters, top, cancellationToken); + } + + /// + /// Filters the list of virtual machines for this resource group represented as generic resources. + /// + /// The substring to filter by. + /// The number of items to truncate by. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of that may take multiple service requests to iterate over. + public AsyncPageable ListByNameAsync(string filter, int? top = null, CancellationToken cancellationToken = default) + { + ResourceFilterCollection filters = new ResourceFilterCollection(VirtualMachineOperations.ResourceType); + filters.SubstringFilter = filter; + return ResourceListOperations.ListAtContextAsync(Parent as ResourceGroupOperations, filters, top, cancellationToken); + } + + /// + /// Filters the list of virtual machines for this resource group represented as generic resources. + /// Makes an additional network call to retrieve the full data model for each virtual machine. + /// + /// The substring to filter by. + /// The number of items to truncate by. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of that may take multiple service requests to iterate over. + public Pageable ListByNameExpanded(string filter, int? top = null, CancellationToken cancellationToken = default) + { + var results = ListByName(filter, top, cancellationToken); + return new PhWrappingPageable(results, s => (new VirtualMachineOperations(s)).Get().Value); + } + + /// + /// Filters the list of virtual machines for this resource group represented as generic resources. + /// Makes an additional network call to retrieve the full data model for each virtual machine. + /// + /// The substring to filter by. + /// The number of items to truncate by. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of that may take multiple service requests to iterate over. + public AsyncPageable ListByNameExpandedAsync(string filter, int? top = null, CancellationToken cancellationToken = default) + { + var results = ListByNameAsync(filter, top, cancellationToken); + return new PhWrappingAsyncPageable(results, s => (new VirtualMachineOperations(s)).Get().Value); + } + + /// + public override ArmResponse Get(string virtualMachineName) + { + return new PhArmResponse(Operations.Get(Id.ResourceGroup, virtualMachineName), + v => new VirtualMachine(Parent, new VirtualMachineData(v))); + } + + /// + public override async Task> GetAsync(string virtualMachineName, CancellationToken cancellationToken = default) + { + return new PhArmResponse(await Operations.GetAsync(Id.ResourceGroup, virtualMachineName, cancellationToken), + v => new VirtualMachine(Parent, new VirtualMachineData(v))); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/compute/VirtualMachineOperations.cs b/sdk/resourcemanager/Proto.Client/compute/VirtualMachineOperations.cs new file mode 100644 index 0000000000000..4e0b39c17e938 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/compute/VirtualMachineOperations.cs @@ -0,0 +1,444 @@ +using Azure; +using Azure.ResourceManager.Compute; +using Azure.ResourceManager.Compute.Models; +using Azure.ResourceManager.Core; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Compute +{ + /// + /// A class representing the operations that can be performed over a specific VirtualMachine. + /// + public class VirtualMachineOperations : ResourceOperationsBase, ITaggableResource, IDeletableResource + { + /// + /// Initializes a new instance of the class. + /// + /// An instance of that has an id for a virtual machine. + internal VirtualMachineOperations(GenericResourceOperations genericOperations) + : base(genericOperations) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + internal VirtualMachineOperations(ResourceGroupOperations resourceGroup, string vmName) + : base(resourceGroup, $"{resourceGroup.Id}/providers/Microsoft.Compute/virtualMachines/{vmName}") + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + protected VirtualMachineOperations(ResourceOperationsBase operation, ResourceIdentifier id) + : base(operation, id) + { + } + + /// + /// Gets the resource type definition for a virtual machine. + /// + public static readonly ResourceType ResourceType = "Microsoft.Compute/virtualMachines"; + + /// + /// Gets the valid resources for virtual machines. + /// + protected override ResourceType ValidResourceType => ResourceType; + + private VirtualMachinesOperations Operations => new ComputeManagementClient( + BaseUri, + Id.Subscription, + Credential, + ClientOptions.Convert()).VirtualMachines; + + /// + /// Initializes a new instance of the class from a . + /// + /// An instance of that has an id for a virtual machine. + /// A new instance of the class. + public static VirtualMachineOperations FromGeneric(GenericResourceOperations genericOperations) + { + return new VirtualMachineOperations(genericOperations); + } + + /// + /// The operation to delete a virtual machine. + /// + /// A response with the operation for this resource. + public ArmResponse Delete() + { + return new ArmResponse(Operations.StartDelete(Id.ResourceGroup, Id.Name).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult()); + } + + /// + /// The operation to delete a virtual machine. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + public async Task> DeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmResponse((await Operations.StartDeleteAsync(Id.ResourceGroup, Id.Name)).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult()); + } + + /// + /// The operation to delete a virtual machine. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// An that allows polling for completion of the operation. + public ArmOperation StartDelete(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(Operations.StartDelete(Id.ResourceGroup, Id.Name, cancellationToken)); + } + + /// + /// The operation to delete a virtual machine. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> StartDeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(await Operations.StartDeleteAsync(Id.ResourceGroup, Id.Name, cancellationToken)); + } + + #region PowerOn + /// + /// The operation to start a virtual machine. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A response with the operation for this resource. + public ArmResponse PowerOn(CancellationToken cancellationToken = default) + { + var operation = Operations.StartStart(Id.ResourceGroup, Id.Name, cancellationToken); + return new ArmResponse(operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult()); + } + + /// + /// The operation to start a virtual machine. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + public async Task> PowerOnAsync(CancellationToken cancellationToken = default) + { + var operation = await Operations.StartStartAsync(Id.ResourceGroup, Id.Name, cancellationToken).ConfigureAwait(false); + return new ArmResponse(await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false)); + } + + /// + /// The operation to start a virtual machine. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An that allows polling for completion of the operation. + public ArmOperation StartPowerOn(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(Operations.StartStart(Id.ResourceGroup, Id.Name, cancellationToken)); + } + + /// + /// The operation to start a virtual machine. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> StartPowerOnAsync(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(await Operations.StartStartAsync(Id.ResourceGroup, Id.Name, cancellationToken).ConfigureAwait(false)); + } + #endregion + + #region PowerOff + /// + /// The operation to power off (stop) a virtual machine. The virtual machine can be restarted with the same provisioned resources. You are still charged for this virtual machine. + /// + /// The parameter to request non-graceful VM shutdown. True value for this flag indicates non-graceful shutdown whereas false indicates otherwise. Default value for this flag is false if not specified. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A response with the operation for this resource. + public ArmResponse PowerOff(bool? skipShutdown = null, CancellationToken cancellationToken = default) + { + var operation = Operations.StartPowerOff(Id.ResourceGroup, Id.Name, skipShutdown, cancellationToken); + return new ArmResponse(operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult()); + } + + /// + /// The operation to power off (stop) a virtual machine. The virtual machine can be restarted with the same provisioned resources. You are still charged for this virtual machine. + /// + /// The parameter to request non-graceful VM shutdown. True value for this flag indicates non-graceful shutdown whereas false indicates otherwise. Default value for this flag is false if not specified. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + public async Task> PowerOffAsync(bool? skipShutdown = null, CancellationToken cancellationToken = default) + { + var operation = await Operations.StartPowerOffAsync(Id.ResourceGroup, Id.Name, skipShutdown, cancellationToken).ConfigureAwait(false); + return new ArmResponse(await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false)); + } + + /// + /// The operation to power off (stop) a virtual machine. The virtual machine can be restarted with the same provisioned resources. You are still charged for this virtual machine. + /// + /// The parameter to request non-graceful VM shutdown. True value for this flag indicates non-graceful shutdown whereas false indicates otherwise. Default value for this flag is false if not specified. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An that allows polling for completion of the operation. + public ArmOperation StartPowerOff(bool? skipShutdown = null, CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(Operations.StartPowerOff(Id.ResourceGroup, Id.Name, skipShutdown, cancellationToken)); + } + + /// + /// The operation to power off (stop) a virtual machine. The virtual machine can be restarted with the same provisioned resources. You are still charged for this virtual machine. + /// + /// The parameter to request non-graceful VM shutdown. True value for this flag indicates non-graceful shutdown whereas false indicates otherwise. Default value for this flag is false if not specified. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> StartPowerOffAsync(bool? skipShutdown = null, CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(await Operations.StartPowerOffAsync(Id.ResourceGroup, Id.Name, skipShutdown, cancellationToken).ConfigureAwait(false)); + } + #endregion + + /// + public override ArmResponse Get() + { + return new PhArmResponse( + Operations.Get(Id.ResourceGroup, Id.Name), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + public override async Task> GetAsync(CancellationToken cancellationToken = default) + { + return new PhArmResponse( + await Operations.GetAsync(Id.ResourceGroup, Id.Name, cancellationToken), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + /// The operation to update a virtual machine. Please note some properties can be set only during virtual machine creation. + /// + /// The parameters to update. + /// An that allows polling for completion of the operation. + public ArmOperation StartUpdate(VirtualMachineUpdate patchable) + { + return new PhArmOperation( + Operations.StartUpdate(Id.ResourceGroup, Id.Name, patchable), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + /// The operation to update a virtual machine. Please note some properties can be set only during virtual machine creation. + /// + /// The parameters to update. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> StartUpdateAsync(VirtualMachineUpdate patchable, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + await Operations.StartUpdateAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + /// Add a tag to a virtual machine. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// An that allows polling for completion of the operation. + public ArmResponse AddTag(string key, string value) + { + var vm = GetResource(); + var patchable = new VirtualMachineUpdate(); + patchable.Tags.ReplaceWith(vm.Data.Tags); + patchable.Tags[key] = value; + + return new PhArmResponse( + Operations.StartUpdate(Id.ResourceGroup, Id.Name, patchable).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult(), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + /// Add a tag to a virtual machine. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + var vm = await GetResourceAsync(); + var patchable = new VirtualMachineUpdate(); + patchable.Tags.ReplaceWith(vm.Data.Tags); + patchable.Tags[key] = value; + + return new PhArmResponse( + await Operations.StartUpdateAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken).Result.WaitForCompletionAsync(), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + /// Add a tag to a virtual machine. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// An that allows polling for completion of the operation. + public ArmOperation StartAddTag(string key, string value) + { + var vm = GetResource(); + var patchable = new VirtualMachineUpdate(); + patchable.Tags.ReplaceWith(vm.Data.Tags); + patchable.Tags[key] = value; + + return new PhArmOperation( + Operations.StartUpdate(Id.ResourceGroup, Id.Name, patchable), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + /// Add a tag to a virtual machine. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> StartAddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + var vm = await GetResourceAsync(); + var patchable = new VirtualMachineUpdate(); + patchable.Tags.ReplaceWith(vm.Data.Tags); + patchable.Tags[key] = value; + + return new PhArmOperation( + await Operations.StartUpdateAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + public ArmResponse SetTags(IDictionary tags) + { + var patchable = new VirtualMachineUpdate(); + patchable.Tags.ReplaceWith(tags); + + return new PhArmResponse( + Operations.StartUpdate(Id.ResourceGroup, Id.Name, patchable).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult(), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + public async Task> SetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + var patchable = new VirtualMachineUpdate(); + patchable.Tags.ReplaceWith(tags); + + return new PhArmResponse( + await Operations.StartUpdateAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken).Result.WaitForCompletionAsync(), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + public ArmOperation StartSetTags(IDictionary tags) + { + var patchable = new VirtualMachineUpdate(); + patchable.Tags.ReplaceWith(tags); + + return new PhArmOperation( + Operations.StartUpdate(Id.ResourceGroup, Id.Name, patchable).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult(), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + public async Task> StartSetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + var patchable = new VirtualMachineUpdate(); + patchable.Tags.ReplaceWith(tags); + + return new PhArmOperation( + await Operations.StartUpdateAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken).Result.WaitForCompletionAsync(), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + public ArmResponse RemoveTag(string key) + { + var vm = GetResource(); + var patchable = new VirtualMachineUpdate(); + patchable.Tags.ReplaceWith(vm.Data.Tags); + patchable.Tags.Remove(key); + + return new PhArmResponse( + Operations.StartUpdate(Id.ResourceGroup, Id.Name, patchable).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult(), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + public async Task> RemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + var vm = await GetResourceAsync(); + var patchable = new VirtualMachineUpdate(); + patchable.Tags.ReplaceWith(vm.Data.Tags); + patchable.Tags.Remove(key); + + return new PhArmResponse( + await Operations.StartUpdateAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken).Result.WaitForCompletionAsync(), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + public ArmOperation StartRemoveTag(string key) + { + var vm = GetResource(); + var patchable = new VirtualMachineUpdate(); + patchable.Tags.ReplaceWith(vm.Data.Tags); + patchable.Tags.Remove(key); + + return new PhArmOperation( + Operations.StartUpdate(Id.ResourceGroup, Id.Name, patchable).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult(), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + public async Task> StartRemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + var vm = await GetResourceAsync(); + var patchable = new VirtualMachineUpdate(); + patchable.Tags.ReplaceWith(vm.Data.Tags); + patchable.Tags.Remove(key); + + return new PhArmOperation( + await Operations.StartUpdateAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken).Result.WaitForCompletionAsync(), + v => new VirtualMachine(this, new VirtualMachineData(v))); + } + + /// + /// Lists all available geo-locations. + /// + /// A collection of location that may take multiple service requests to iterate over. + public IEnumerable ListAvailableLocations() + { + return ListAvailableLocations(ResourceType); + } + + /// + /// Lists all available geo-locations. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of location that may take multiple service requests to iterate over. + /// The default subscription id is null. + public async Task> ListAvailableLocationsAsync(CancellationToken cancellationToken = default) + { + return await ListAvailableLocationsAsync(ResourceType, cancellationToken); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/Extensions/ArmClientExtensions.cs b/sdk/resourcemanager/Proto.Client/network/Extensions/ArmClientExtensions.cs new file mode 100644 index 0000000000000..1b5103d57f996 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/Extensions/ArmClientExtensions.cs @@ -0,0 +1,112 @@ +using Azure.ResourceManager.Core; +using System; + +namespace Proto.Network +{ + /// + /// A class to add extension methods to an ArmClient. + /// + public static class ArmClientExtensions + { + + /// + /// Gets the NetworkInterfaceOperations. + /// + /// The instance the method will execute against. + /// The ResourceIdentifier of the resource that is the target of operations. + /// Returns an object representing the operations that can be performed over a specific . + /// ResourceIdentifier provided is not for a NetworkInterfaceOperations. + /// ResourceIdentifier cannot be null. + public static NetworkInterfaceOperations GetNetworkInterfaceOperations(this AzureResourceManagerClient client, ResourceIdentifier resourceId) + { + if (resourceId is null) + throw new ArgumentNullException(nameof(resourceId)); + if (resourceId.Type != NetworkInterfaceOperations.ResourceType) + throw new ArgumentException($"{nameof(resourceId.Type)} provided is not for a NetworkInterface.", nameof(resourceId.Type)); + + var subOps = client.GetSubscriptionOperations(resourceId.Subscription); + var rgOps = subOps.GetResourceGroupOperations(resourceId.ResourceGroup); + return rgOps.GetNetworkInterfaceOperations(resourceId.Name); + } + + /// + /// Gets the NetworkSecurityGroupOperations. + /// + /// The instance the method will execute against. + /// The ResourceIdentifier of the resource that is the target of operations. + /// Returns an object representing the operations that can be performed over a specific . + /// ResourceIdentifier provided is not for a NetworkSecurityGroup. + /// ResourceIdentifier cannot be null. + public static NetworkSecurityGroupOperations GetNetworkSecurityGroupOperations(this AzureResourceManagerClient client, ResourceIdentifier resourceId) + { + if (resourceId is null) + throw new ArgumentNullException(nameof(resourceId)); + if (resourceId.Type != NetworkSecurityGroupOperations.ResourceType) + throw new ArgumentException($"{nameof(resourceId.Type)} provided is not for a NetworkSecurityGroup.", nameof(resourceId.Type)); + + var subOps = client.GetSubscriptionOperations(resourceId.Subscription); + var rgOps = subOps.GetResourceGroupOperations(resourceId.ResourceGroup); + return rgOps.GetNetworkSecurityGroupOperations(resourceId.Name); + } + + /// + /// Gets the PublicIpAddressOperations. + /// + /// The instance the method will execute against. + /// The ResourceIdentifier of the resource that is the target of operations. + /// Returns an object representing the operations that can be performed over a specific . + /// ResourceIdentifier provided is not for a PublicIpAddress. + /// ResourceIdentifier cannot be null. + public static PublicIpAddressOperations GetPublicIpAddressOperations(this AzureResourceManagerClient client, ResourceIdentifier resourceId) + { + if (resourceId is null) + throw new ArgumentNullException(nameof(resourceId)); + if (resourceId.Type != PublicIpAddressOperations.ResourceType) + throw new ArgumentException($"{nameof(resourceId.Type)} provided is not for a PublicIpAddress.", nameof(resourceId.Type)); + + var subOps = client.GetSubscriptionOperations(resourceId.Subscription); + var rgOps = subOps.GetResourceGroupOperations(resourceId.ResourceGroup); + return rgOps.GetPublicIpAddressOperations(resourceId.Name); + } + + /// + /// Gets the SubnetOperations. + /// + /// The instance the method will execute against. + /// The ResourceIdentifier of the resource that is the target of operations. + /// Returns an object representing the operations that can be performed over a specific . + /// ResourceIdentifier provided is not for a Subnet. + /// ResourceIdentifier cannot be null. + public static SubnetOperations GetSubnetOperations(this AzureResourceManagerClient client, ResourceIdentifier resourceId) + { + if (resourceId is null) + throw new ArgumentNullException(nameof(resourceId)); + if (resourceId.Type != SubnetOperations.ResourceType) + throw new ArgumentException($"{nameof(resourceId.Type)} provided is not for a Subnet.", nameof(resourceId.Type)); + var subOps = client.GetSubscriptionOperations(resourceId.Subscription); + var rgOps = subOps.GetResourceGroupOperations(resourceId.ResourceGroup); + var vnetOps = rgOps.GetVirtualNetworkOperations(resourceId.Parent.Name); + return vnetOps.GetSubnetOperations(resourceId.Name); + } + + /// + /// Gets the VirtualNetworkOperations. + /// + /// The instance the method will execute against. + /// The ResourceIdentifier of the resource that is the target of operations. + /// Returns an object representing the operations that can be performed over a specific . + /// ResourceIdentifier provided is not for a VirtualNetwork. + /// ResourceIdentifier cannot be null. + public static VirtualNetworkOperations GetVirtualNetworkOperations(this AzureResourceManagerClient client, ResourceIdentifier resourceId) + { + if (resourceId is null) + throw new ArgumentNullException(nameof(resourceId)); + if (resourceId.Type != VirtualNetworkOperations.ResourceType) + throw new ArgumentException($"{nameof(resourceId.Type)} provided is not for a VirtualNetwork.", nameof(resourceId.Type)); + + var subOps = client.GetSubscriptionOperations(resourceId.Subscription); + var rgOps = subOps.GetResourceGroupOperations(resourceId.ResourceGroup); + return rgOps.GetVirtualNetworkOperations(resourceId.Parent.Name); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/Extensions/ResourceGroupExtensions.cs b/sdk/resourcemanager/Proto.Client/network/Extensions/ResourceGroupExtensions.cs new file mode 100644 index 0000000000000..d112c63016045 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/Extensions/ResourceGroupExtensions.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.ResourceManager.Core; +using System; + +namespace Proto.Network +{ + /// + /// A class to add extension methods to resource group. + /// + public static class ResourceGroupExtensions + { + #region Virtual Network Operations + /// + /// Gets a for a given resource under a . + /// + /// The instance the method will execute against. + /// The resource id of data model. + /// An instance of . + /// virtualNetwork cannot be null or a whitespace. + public static VirtualNetworkOperations GetVirtualNetworkOperations(this ResourceGroupOperations resourceGroup, string virtualNetwork) + { + if (string.IsNullOrWhiteSpace(virtualNetwork)) + throw new ArgumentException($"{nameof(virtualNetwork)} cannot be null or a whitespace.", nameof(virtualNetwork)); + return new VirtualNetworkOperations(resourceGroup, virtualNetwork); + } + + /// + /// Gets a under a . + /// + /// The instance the method will execute against. + /// An instance of . + public static VirtualNetworkContainer GetVirtualNetworkContainer(this ResourceGroupOperations resourceGroup) + { + return new VirtualNetworkContainer(resourceGroup); + } + #endregion + + #region Public IP Address Operations + /// + /// Gets a under a . + /// + /// The instance the method will execute against. + /// The resource id of data model. + /// An instance of . + /// publicIpAddress cannot be null or a whitespace. + public static PublicIpAddressOperations GetPublicIpAddressOperations(this ResourceGroupOperations resourceGroup, string publicIpAddress) + { + if (string.IsNullOrWhiteSpace(publicIpAddress)) + throw new ArgumentException($"{nameof(publicIpAddress)} cannot be null or a whitespace.", nameof(publicIpAddress)); + return new PublicIpAddressOperations(resourceGroup, publicIpAddress); + } + + /// + /// Gets a under a . + /// + /// The instance the method will execute against. + /// An instance of . + public static PublicIpAddressContainer GetPublicIpAddressContainer(this ResourceGroupOperations resourceGroup) + { + return new PublicIpAddressContainer(resourceGroup); + } + #endregion + + #region Network Interface (NIC) operations + /// + /// Gets the operations over a specific + /// + /// The operations over a specific resource group. + /// The network interface to target for operations. + /// A including the operations that can be peformed on it. + /// networkInterface cannot be null or a whitespace. + public static NetworkInterfaceOperations GetNetworkInterfaceOperations(this ResourceGroupOperations resourceGroup, string networkInterface) + { + if (string.IsNullOrWhiteSpace(networkInterface)) + throw new ArgumentException($"{nameof(networkInterface)} cannot be null or a whitespace.", nameof(networkInterface)); + return new NetworkInterfaceOperations(resourceGroup, networkInterface); + } + + /// + /// Gets the operations over the collection of contained in the resource group. + /// + /// The operations over a specific resource group. + /// A representing the collection of + public static NetworkInterfaceContainer GetNetworkInterfaceContainer(this ResourceGroupOperations resourceGroup) + { + return new NetworkInterfaceContainer(resourceGroup); + } + + /// + /// Gets the operations over the collection of contained in the resource group. + /// + /// The instance the method will execute against. + /// The resource id of data model. + /// An instance of . + /// networkSecurityGroup cannot be null or a whitespace. + public static NetworkSecurityGroupOperations GetNetworkSecurityGroupOperations(this ResourceGroupOperations resourceGroup, string networkSecurityGroup) + { + if (string.IsNullOrWhiteSpace(networkSecurityGroup)) + throw new ArgumentException($"{nameof(networkSecurityGroup)} cannot be null or a whitespace.", nameof(networkSecurityGroup)); + return new NetworkSecurityGroupOperations(resourceGroup, networkSecurityGroup); + } + + /// + /// Gets a under a . + /// + /// The instance the method will execute against. + /// An instance of . + public static NetworkSecurityGroupContainer GetNetworkSecurityGroupContainer(this ResourceGroupOperations resourceGroup) + { + return new NetworkSecurityGroupContainer(resourceGroup); + } + #endregion + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/Extensions/SubscriptionExtensions.cs b/sdk/resourcemanager/Proto.Client/network/Extensions/SubscriptionExtensions.cs new file mode 100644 index 0000000000000..84e66631beeaf --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/Extensions/SubscriptionExtensions.cs @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure; +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Core.Adapters; +using Azure.ResourceManager.Network; + +namespace Proto.Network +{ + /// + /// A class to add extension methods to Azure subscription. + /// + public static class SubscriptionExtensions + { + #region Virtual Network Operations + + private static NetworkManagementClient GetNetworkClient(SubscriptionOperations subscription) + { + return new NetworkManagementClient( + subscription.Id.Subscription, + subscription.BaseUri, + subscription.Credential, + subscription.ClientOptions.Convert()); + } + + /// + /// Lists the virtual networks for this subscription. + /// + /// The instance the method will execute against. + /// A collection of resource operations that may take multiple service requests to iterate over. + public static Pageable ListVnets(this SubscriptionOperations subscription) + { + NetworkManagementClient networkClient = GetNetworkClient(subscription); + var vmOperations = networkClient.VirtualNetworks; + var result = vmOperations.ListAll(); + return new PhWrappingPageable( + result, + s => new VirtualNetwork(subscription, new VirtualNetworkData(s))); + } + + /// + /// Lists the virtual networks for this subscription. + /// + /// The instance the method will execute against. + /// An async collection of resource operations that may take multiple service requests to iterate over. + public static AsyncPageable ListVnetsAsync(this SubscriptionOperations subscription) + { + NetworkManagementClient networkClient = GetNetworkClient(subscription); + var vmOperations = networkClient.VirtualNetworks; + var result = vmOperations.ListAllAsync(); + return new PhWrappingAsyncPageable( + result, + s => new VirtualNetwork(subscription, new VirtualNetworkData(s))); + } + + #endregion + + #region Public IP Address Operations + + /// + /// Lists the public IPs for this subscription. + /// + /// The instance the method will execute against. + /// A collection of resource operations that may take multiple service requests to iterate over. + public static Pageable ListPublicIps(this SubscriptionOperations subscription) + { + NetworkManagementClient networkClient = GetNetworkClient(subscription); + var publicIPAddressesOperations = networkClient.PublicIPAddresses; + var result = publicIPAddressesOperations.ListAll(); + return new PhWrappingPageable( + result, + s => new PublicIpAddress(subscription, new PublicIPAddressData(s))); + } + + /// + /// Lists the public IP addresses for this subscription. + /// + /// The instance the method will execute against. + /// An async collection of resource operations that may take multiple service requests to iterate over. + public static AsyncPageable ListPublicIpsAsync(this SubscriptionOperations subscription) + { + NetworkManagementClient networkClient = GetNetworkClient(subscription); + var publicIPAddressesOperations = networkClient.PublicIPAddresses; + var result = publicIPAddressesOperations.ListAllAsync(); + return new PhWrappingAsyncPageable( + result, + s => new PublicIpAddress(subscription, new PublicIPAddressData(s))); + } + + #endregion + + #region Network Interface (NIC) operations + + /// + /// Lists the for this . + /// + /// The to target for listing. + /// A collection of that may take multiple service requests to iterate over. + public static Pageable ListNics(this SubscriptionOperations subscription) + { + NetworkManagementClient networkClient = GetNetworkClient(subscription); + var networkInterfacesOperations = networkClient.NetworkInterfaces; + var result = networkInterfacesOperations.ListAll(); + return new PhWrappingPageable( + result, + s => new NetworkInterface(subscription, new NetworkInterfaceData(s))); + } + + /// + /// Lists the for this . + /// + /// The to target for listing. + /// An async collection of resource operations that may take multiple service requests to iterate over. + public static AsyncPageable ListNicsAsync(this SubscriptionOperations subscription) + { + NetworkManagementClient networkClient = GetNetworkClient(subscription); + var networkInterfacesOperations = networkClient.NetworkInterfaces; + var result = networkInterfacesOperations.ListAllAsync(); + return new PhWrappingAsyncPageable( + result, + s => new NetworkInterface(subscription, new NetworkInterfaceData(s))); + } + + #endregion + + #region Network Security Group operations + + /// + /// Lists the network security groups for this subscription. + /// + /// The instance the method will execute against. + /// A collection of resource operations that may take multiple service requests to iterate over. + public static Pageable ListNsgs(this SubscriptionOperations subscription) + { + NetworkManagementClient networkClient = GetNetworkClient(subscription); + var networkSecurityGroupsOperations = networkClient.NetworkSecurityGroups; + var result = networkSecurityGroupsOperations.ListAll(); + return new PhWrappingPageable( + result, + s => new NetworkSecurityGroup(subscription, new NetworkSecurityGroupData(s))); + } + + /// + /// Lists the network security groups for this subscription. + /// + /// The instance the method will execute against. + /// An async collection of resource operations that may take multiple service requests to iterate over. + public static AsyncPageable ListNsgsAsync(this SubscriptionOperations subscription) + { + NetworkManagementClient networkClient = GetNetworkClient(subscription); + var networkSecurityGroupsOperations = networkClient.NetworkSecurityGroups; + var result = networkSecurityGroupsOperations.ListAllAsync(); + return new PhWrappingAsyncPageable( + result, + s => new NetworkSecurityGroup(subscription, new NetworkSecurityGroupData(s))); + } + + #endregion + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/NetworkInterface.cs b/sdk/resourcemanager/Proto.Client/network/NetworkInterface.cs new file mode 100644 index 0000000000000..7af879e2f6473 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/NetworkInterface.cs @@ -0,0 +1,34 @@ +using System.Threading.Tasks; +using Azure.ResourceManager.Core; + +namespace Proto.Network +{ + /// + /// A class that represents a network interface in a resource group and the operatiosn that can be performed on it. + /// + public class NetworkInterface : NetworkInterfaceOperations + { + internal NetworkInterface(ResourceOperationsBase options, NetworkInterfaceData resource) + : base(options, resource.Id) + { + Data = resource; + } + + /// + /// Gets the for this . + /// + public NetworkInterfaceData Data { get; private set; } + + /// + protected override NetworkInterface GetResource() + { + return this; + } + + /// + protected override Task GetResourceAsync() + { + return Task.FromResult(this); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/NetworkInterfaceContainer.cs b/sdk/resourcemanager/Proto.Client/network/NetworkInterfaceContainer.cs new file mode 100644 index 0000000000000..40755a1598727 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/NetworkInterfaceContainer.cs @@ -0,0 +1,204 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure; +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Core.Resources; +using Azure.ResourceManager.Network; +using Azure.ResourceManager.Network.Models; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Network +{ + /// + /// A class representing collection of and their operations over a . + /// + public class NetworkInterfaceContainer : ResourceContainerBase + { + internal NetworkInterfaceContainer(ResourceGroupOperations resourceGroup) + : base(resourceGroup) + { + } + + internal NetworkInterfacesOperations Operations => new NetworkManagementClient( + Id.Subscription, + BaseUri, + Credential, + ClientOptions.Convert()).NetworkInterfaces; + + /// + protected override ResourceType ValidResourceType => ResourceGroupOperations.ResourceType; + + /// + public override ArmResponse CreateOrUpdate(string name, NetworkInterfaceData resourceDetails) + { + var operation = Operations.StartCreateOrUpdate(Id.ResourceGroup, name, resourceDetails); + return new PhArmResponse( + operation.WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult(), + n => new NetworkInterface(Parent, new NetworkInterfaceData(n))); + } + + /// + public async override Task> CreateOrUpdateAsync(string name, NetworkInterfaceData resourceDetails, CancellationToken cancellationToken = default) + { + var operation = await Operations.StartCreateOrUpdateAsync(Id.ResourceGroup, name, resourceDetails, cancellationToken).ConfigureAwait(false); + return new PhArmResponse( + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false), + n => new NetworkInterface(Parent, new NetworkInterfaceData(n))); + } + + /// + public override ArmOperation StartCreateOrUpdate(string name, NetworkInterfaceData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + Operations.StartCreateOrUpdate(Id.ResourceGroup, name, resourceDetails, cancellationToken), + n => new NetworkInterface(Parent, new NetworkInterfaceData(n))); + } + + /// + public async override Task> StartCreateOrUpdateAsync(string name, NetworkInterfaceData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + await Operations.StartCreateOrUpdateAsync(Id.ResourceGroup, name, resourceDetails, cancellationToken).ConfigureAwait(false), + n => new NetworkInterface(Parent, new NetworkInterfaceData(n))); + } + + /// + /// Constructs an object used to create a . + /// + /// The public IP address of the . + /// The resource identifier of the subnet attached to this . + /// The that will contain the . + /// An object used to create a . + public ArmBuilder Construct(string subnetId, PublicIPAddressData ip = default, LocationData location = null) + { + var parent = GetParentResource(); + var nic = new Azure.ResourceManager.Network.Models.NetworkInterface() + { + Location = location ?? parent.Data.Location, + }; + + nic.IpConfigurations.Add(new NetworkInterfaceIPConfiguration() + { + Name = "Primary", + Primary = true, + Subnet = new Azure.ResourceManager.Network.Models.Subnet() { Id = subnetId }, + PrivateIPAllocationMethod = IPAllocationMethod.Dynamic, + }); + + if (ip != null) + nic.IpConfigurations[0].PublicIPAddress = new PublicIPAddress() { Id = ip.Id }; + + return new ArmBuilder(this, new NetworkInterfaceData(nic)); + } + + /// + /// Lists the for this . + /// + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// A collection of that may take multiple service requests to iterate over. + public Pageable List(CancellationToken cancellationToken = default) + { + return new PhWrappingPageable( + Operations.List(Id.Name, cancellationToken), + this.convertor()); + } + + /// + /// Lists the for this . + /// + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// An async collection of that may take multiple service requests to iterate over. + public AsyncPageable ListAsync(CancellationToken cancellationToken = default) + { + var result = Operations.ListAsync(Id.Name, cancellationToken); + return new PhWrappingAsyncPageable( + result, + this.convertor()); + } + + /// + /// Filters the list of resources for this represented as generic resources. + /// + /// A string to filter the resources by name. + /// The number of results to return per page of data. + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// A collection of resource operations that may take multiple service requests to iterate over. + public Pageable ListByName(string filter, int? top = null, CancellationToken cancellationToken = default) + { + ResourceFilterCollection filters = new ResourceFilterCollection(NetworkInterfaceData.ResourceType); + filters.SubstringFilter = filter; + return ResourceListOperations.ListAtContext(Parent as ResourceGroupOperations, filters, top, cancellationToken); + } + + /// + /// Filters the list of resources for this represented as generic resources. + /// + /// A string to filter the resources by name. + /// The number of results to return per page of data. + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// An async collection of resource operations that may take multiple service requests to iterate over. + public AsyncPageable ListByNameAsync(string filter, int? top = null, CancellationToken cancellationToken = default) + { + ResourceFilterCollection filters = new ResourceFilterCollection(NetworkInterfaceData.ResourceType); + filters.SubstringFilter = filter; + return ResourceListOperations.ListAtContextAsync(Parent as ResourceGroupOperations, filters, top, cancellationToken); + } + + /// + /// Filters the list of resources for this . + /// Makes an additional network call to retrieve the full data model for each . + /// + /// A string to filter the resources by name. + /// The number of results to return per page of data. + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// A collection of resource operations that may take multiple service requests to iterate over. + public Pageable ListByNameExpanded(string filter, int? top = null, CancellationToken cancellationToken = default) + { + var results = ListByName(filter, top, cancellationToken); + return new PhWrappingPageable(results, s => new NetworkInterfaceOperations(s).Get().Value); + } + + /// + /// Filters the list of resources for this . + /// Makes an additional network call to retrieve the full data model for each . + /// + /// A string to filter the resources by name. + /// The number of results to return per page of data. + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// An async collection of resource operations that may take multiple service requests to iterate over. + public AsyncPageable ListByNameExpandedAsync(string filter, int? top = null, CancellationToken cancellationToken = default) + { + var results = ListByNameAsync(filter, top, cancellationToken); + return new PhWrappingAsyncPageable(results, s => new NetworkInterfaceOperations(s).Get().Value); + } + + private Func convertor() + { + return s => new NetworkInterface(Parent, new NetworkInterfaceData(s)); + } + + /// + public override ArmResponse Get(string networkInterfaceName) + { + return new PhArmResponse(Operations.Get(Id.ResourceGroup, networkInterfaceName), + g => new NetworkInterface(Parent, new NetworkInterfaceData(g))); + } + + /// + public override async Task> GetAsync(string networkInterfaceName, CancellationToken cancellationToken = default) + { + return new PhArmResponse(await Operations.GetAsync(Id.ResourceGroup, networkInterfaceName, null, cancellationToken), + g => new NetworkInterface(Parent, new NetworkInterfaceData(g))); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/NetworkInterfaceOperations.cs b/sdk/resourcemanager/Proto.Client/network/NetworkInterfaceOperations.cs new file mode 100644 index 0000000000000..04e4e780218b0 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/NetworkInterfaceOperations.cs @@ -0,0 +1,298 @@ +using Azure; +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Network; +using Azure.ResourceManager.Network.Models; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Network +{ + /// + /// A class representing the operations that can be pefroemd over a specific . + /// + public class NetworkInterfaceOperations : ResourceOperationsBase, ITaggableResource, IDeletableResource + { + internal NetworkInterfaceOperations(GenericResourceOperations genericOperations) + : base(genericOperations) + { + } + + internal NetworkInterfaceOperations(ResourceGroupOperations resourceGroup, string nicName) + : base(resourceGroup, $"{resourceGroup.Id}/providers/Microsoft.Network/networkInterfaces/{nicName}") + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + protected NetworkInterfaceOperations(ResourceOperationsBase options, ResourceIdentifier id) + : base(options, id) + { + } + + /// + /// The resource type of a . + /// + public static readonly ResourceType ResourceType = "Microsoft.Network/networkInterfaces"; + + /// + protected override ResourceType ValidResourceType => ResourceType; + + internal NetworkInterfacesOperations Operations => new NetworkManagementClient( + Id.Subscription, + BaseUri, + Credential, + ClientOptions.Convert()).NetworkInterfaces; + + /// + /// Deletes a . + /// + /// An representing the service response to deletion. + public ArmResponse Delete() + { + return new ArmResponse(Operations.StartDelete(Id.ResourceGroup, Id.Name).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult()); + } + + /// + /// Deletes a . + /// + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// A that returns an when completed. + public async Task> DeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmResponse((await Operations.StartDeleteAsync(Id.ResourceGroup, Id.Name, cancellationToken)).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult()); + } + + /// + /// Deletes a . + /// + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// An that allows polling for completion of the operation. + /// + /// Details on long running operation object. + /// + public ArmOperation StartDelete(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(Operations.StartDelete(Id.ResourceGroup, Id.Name, cancellationToken)); + } + + /// + /// Deletes a . + /// + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// A that on completion returns an that allows polling for completion of the operation. + /// + /// Details on long running operation object. + /// + public async Task> StartDeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(await Operations.StartDeleteAsync(Id.ResourceGroup, Id.Name, cancellationToken)); + } + + /// + /// Gets details of the from the service. + /// + /// An . + public override ArmResponse Get() + { + return new PhArmResponse( + Operations.Get(Id.ResourceGroup, Id.Name), + n => new NetworkInterface(this, new NetworkInterfaceData(n))); + } + + /// + public async override Task> GetAsync(CancellationToken cancellationToken = default) + { + return new PhArmResponse( + await Operations.GetAsync(Id.ResourceGroup, Id.Name, null, cancellationToken), + n => new NetworkInterface(this, new NetworkInterfaceData(n))); + } + + /// + /// Add the given tag key and tag value to the resource. + /// + /// The tag key. + /// The Tag Value. + /// An that allows polling for completion of the operation. + public ArmResponse AddTag(string key, string value) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmResponse(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new NetworkInterface(this, new NetworkInterfaceData(n))); + } + + /// + /// Add the given tag key and tag value to the resource. + /// + /// The tag key. + /// The Tag Value. + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// A that on completion returns a that allows polling for completion of the operation. + public async Task> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmResponse( + await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new NetworkInterface(this, new NetworkInterfaceData(n))); + } + + /// + /// Add the given tag key and tag value to the resource. + /// + /// The tag key. + /// The Tag Value. + /// An that allows polling for completion of the operation. + /// + /// Details on long running operation object. + /// + public ArmOperation StartAddTag(string key, string value) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmOperation(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new NetworkInterface(this, new NetworkInterfaceData(n))); + } + + /// + /// Add the given tag key and tag value to the resource. + /// + /// The tag key. + /// The Tag Value. + /// A token to allow the caller to cancel the call to the service. + /// The default value is . + /// A that on completion returns a that allows polling for completion of the operation. + /// + /// Details on long running operation object. + /// + public async Task> StartAddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmOperation( + await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new NetworkInterface(this, new NetworkInterfaceData(n))); + } + + /// + public ArmResponse SetTags(IDictionary tags) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmResponse(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new NetworkInterface(this, new NetworkInterfaceData(n))); + } + + /// + public async Task> SetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmResponse( + await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new NetworkInterface(this, new NetworkInterfaceData(n))); + } + + /// + public ArmOperation StartSetTags(IDictionary tags) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmOperation(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new NetworkInterface(this, new NetworkInterfaceData(n))); + } + + /// + public async Task> StartSetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmOperation( + await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new NetworkInterface(this, new NetworkInterfaceData(n))); + } + + /// + public ArmResponse RemoveTag(string key) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmResponse(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new NetworkInterface(this, new NetworkInterfaceData(n))); + } + + /// + public async Task> RemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmResponse( + await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new NetworkInterface(this, new NetworkInterfaceData(n))); + } + + /// + public ArmOperation StartRemoveTag(string key) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmOperation(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new NetworkInterface(this, new NetworkInterfaceData(n))); + } + + /// + public async Task> StartRemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmOperation( + await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new NetworkInterface(this, new NetworkInterfaceData(n))); + } + + /// + /// Lists all available geo-locations. + /// + /// A collection of location that may take multiple service requests to iterate over. + public IEnumerable ListAvailableLocations() + { + return ListAvailableLocations(ResourceType); + } + + /// + /// Lists all available geo-locations. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of location that may take multiple service requests to iterate over. + /// The default subscription id is null. + public async Task> ListAvailableLocationsAsync(CancellationToken cancellationToken = default) + { + return await ListAvailableLocationsAsync(ResourceType, cancellationToken); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/NetworkSecurityGroup.cs b/sdk/resourcemanager/Proto.Client/network/NetworkSecurityGroup.cs new file mode 100644 index 0000000000000..c006c06c247ca --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/NetworkSecurityGroup.cs @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.ResourceManager.Core; +using System.Threading.Tasks; + +namespace Proto.Network +{ + /// + /// A class representing the operations that can be performed over a specific network security group. + /// + public class NetworkSecurityGroup : NetworkSecurityGroupOperations + { + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The resource that is the target of operations. + internal NetworkSecurityGroup(ResourceOperationsBase operations, NetworkSecurityGroupData resource) + : base(operations, resource.Id) + { + Data = resource; + } + + /// + /// Gets the data representing this network security group. + /// + public NetworkSecurityGroupData Data { get; private set; } + + /// + protected override NetworkSecurityGroup GetResource() + { + return this; + } + + /// + protected override Task GetResourceAsync() + { + return Task.FromResult(this); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/NetworkSecurityGroupContainer.cs b/sdk/resourcemanager/Proto.Client/network/NetworkSecurityGroupContainer.cs new file mode 100644 index 0000000000000..325c75e596718 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/NetworkSecurityGroupContainer.cs @@ -0,0 +1,246 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure; +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Core.Resources; +using Azure.ResourceManager.Network; +using Azure.ResourceManager.Network.Models; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Network +{ + /// + /// A class representing collection of NetworkSecurityGroup and their operations over a resource group. + /// + public class NetworkSecurityGroupContainer : ResourceContainerBase + { + /// + /// Initializes a new instance of the class. + /// + /// An instance of that has an id for a [Resource]. + internal NetworkSecurityGroupContainer(GenericResourceOperations genericOperations) + : base(genericOperations) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The ResourceGroup that is the parent of the NetworkSecurityGroups. + internal NetworkSecurityGroupContainer(ResourceGroupOperations resourceGroup) + : base(resourceGroup) + { + } + + /// + /// Gets the valid resource type for network security groups. + /// + protected override ResourceType ValidResourceType => ResourceGroupOperations.ResourceType; + + private NetworkSecurityGroupsOperations Operations => new NetworkManagementClient( + Id.Subscription, + BaseUri, + Credential, + ClientOptions.Convert()).NetworkSecurityGroups; + + /// + public override ArmResponse CreateOrUpdate(string name, NetworkSecurityGroupData resourceDetails) + { + var operation = Operations.StartCreateOrUpdate(Id.ResourceGroup, name, resourceDetails.Model); + return new PhArmResponse( + operation.WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult(), + n => new NetworkSecurityGroup(Parent, new NetworkSecurityGroupData(n))); + } + + /// + public override async Task> CreateOrUpdateAsync(string name, NetworkSecurityGroupData resourceDetails, CancellationToken cancellationToken = default) + { + var operation = await Operations.StartCreateOrUpdateAsync(Id.ResourceGroup, name, resourceDetails.Model, cancellationToken).ConfigureAwait(false); + return new PhArmResponse( + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false), + n => new NetworkSecurityGroup(Parent, new NetworkSecurityGroupData(n))); + } + + /// + public override ArmOperation StartCreateOrUpdate(string name, NetworkSecurityGroupData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + Operations.StartCreateOrUpdate(Id.ResourceGroup, name, resourceDetails.Model, cancellationToken), + n => new NetworkSecurityGroup(Parent, new NetworkSecurityGroupData(n))); + } + + /// + public override async Task> StartCreateOrUpdateAsync(string name, NetworkSecurityGroupData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + await Operations.StartCreateOrUpdateAsync(Id.ResourceGroup, name, resourceDetails.Model, cancellationToken).ConfigureAwait(false), + n => new NetworkSecurityGroup(Parent, new NetworkSecurityGroupData(n))); + } + + /// + /// Construct an object used to create a network security group. + /// + /// The location to create the network security group. + /// The location to create the network security group. + /// Object used to create a . + public ArmBuilder Construct(LocationData locationData = null, params int[] openPorts) + { + var parent = GetParentResource(); + var nsg = new Azure.ResourceManager.Network.Models.NetworkSecurityGroup + { + Location = locationData ?? parent.Data.Location + }; + var index = 0; + foreach(int port in openPorts) + { + var securityRule = new SecurityRule + { + Name = $"Port{port}", + Priority = 1000 + (++index), + Protocol = SecurityRuleProtocol.Tcp, + Access = SecurityRuleAccess.Allow, + Direction = SecurityRuleDirection.Inbound, + SourcePortRange = "*", + SourceAddressPrefix = "*", + DestinationPortRange = $"{port}", + DestinationAddressPrefix = "*", + Description = $"Port_{port}" + }; + nsg.SecurityRules.Add(securityRule); + } + + return new ArmBuilder(this, new NetworkSecurityGroupData(nsg)); + } + + /// + /// Construct an object used to create a network security group. + /// + /// The location to create the network security group. + /// Object used to create a . + public ArmBuilder Construct(params int[] openPorts) + { + var parent = GetParentResource(); + var nsg = new Azure.ResourceManager.Network.Models.NetworkSecurityGroup + { + Location = parent.Data.Location, + }; + var index = 0; + foreach (int port in openPorts) + { + var securityRule = new SecurityRule + { + Name = $"Port{port}", + Priority = 1000 + (++index), + Protocol = SecurityRuleProtocol.Tcp, + Access = SecurityRuleAccess.Allow, + Direction = SecurityRuleDirection.Inbound, + SourcePortRange = "*", + SourceAddressPrefix = "*", + DestinationPortRange = $"{port}", + DestinationAddressPrefix = "*", + Description = $"Port_{port}" + }; + nsg.SecurityRules.Add(securityRule); + } + + return new ArmBuilder(this, new NetworkSecurityGroupData(nsg)); + } + + /// + /// List the network security groups for this resource group. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of that may take multiple service requests to iterate over. + public Pageable List(CancellationToken cancellationToken = default) + { + return new PhWrappingPageable( + Operations.List(Id.Name, cancellationToken), + r => new NetworkSecurityGroup(Parent, new NetworkSecurityGroupData(r))); + } + + /// + /// List the network security groups for this resource group. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of that may take multiple service requests to iterate over. + public AsyncPageable ListAsync(CancellationToken cancellationToken = default) + { + return new PhWrappingAsyncPageable( + Operations.ListAsync(Id.Name, cancellationToken), + r => new NetworkSecurityGroup(Parent, new NetworkSecurityGroupData(r))); + } + + /// + /// Filters the list of network security groups for this resource group represented as generic resources. + /// + /// The substring to filter by. + /// The number of items to truncate by. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of that may take multiple service requests to iterate over. + public Pageable ListByName(string filter, int? top = null, CancellationToken cancellationToken = default) + { + ResourceFilterCollection filters = new ResourceFilterCollection(NetworkSecurityGroupOperations.ResourceType); + filters.SubstringFilter = filter; + return ResourceListOperations.ListAtContext(Parent as ResourceGroupOperations, filters, top, cancellationToken); + } + + /// + /// Filters the list of network security groups for this resource group represented as generic resources. + /// + /// The substring to filter by. + /// The number of items to truncate by. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of that may take multiple service requests to iterate over. + public AsyncPageable ListByNameAsync(string filter, int? top = null, CancellationToken cancellationToken = default) + { + ResourceFilterCollection filters = new ResourceFilterCollection(NetworkSecurityGroupOperations.ResourceType); + filters.SubstringFilter = filter; + return ResourceListOperations.ListAtContextAsync(Parent as ResourceGroupOperations, filters, top, cancellationToken); + } + + /// + /// Filters the list of network security groups for this resource group represented as generic resources. + /// Makes an additional network call to retrieve the full data model for each network security group. + /// + /// The substring to filter by. + /// The number of items to truncate by. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of that may take multiple service requests to iterate over. + public Pageable ListByNameExpanded(string filter, int? top = null, CancellationToken cancellationToken = default) + { + var results = ListByName(filter, top, cancellationToken); + return new PhWrappingPageable(results, s => new NetworkSecurityGroupOperations(s).Get().Value); + } + + /// + /// Filters the list of network security groups for this resource group represented as generic resources. + /// Makes an additional network call to retrieve the full data model for each network security group. + /// + /// The substring to filter by. + /// The number of items to truncate by. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of that may take multiple service requests to iterate over. + public AsyncPageable ListByNameExpandedAsync(string filter, int? top = null, CancellationToken cancellationToken = default) + { + var results = ListByNameAsync(filter, top, cancellationToken); + return new PhWrappingAsyncPageable(results, s => new NetworkSecurityGroupOperations(s).Get().Value); + } + + /// + public override ArmResponse Get(string networkSecurityGroup) + { + return new PhArmResponse(Operations.Get(Id.ResourceGroup, networkSecurityGroup), + g => new NetworkSecurityGroup(Parent, new NetworkSecurityGroupData(g))); + } + + /// + public override async Task> GetAsync(string networkSecurityGroup, CancellationToken cancellationToken = default) + { + return new PhArmResponse(await Operations.GetAsync(Id.ResourceGroup, networkSecurityGroup, null, cancellationToken), + g => new NetworkSecurityGroup(Parent, new NetworkSecurityGroupData(g))); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/NetworkSecurityGroupOperations.cs b/sdk/resourcemanager/Proto.Client/network/NetworkSecurityGroupOperations.cs new file mode 100644 index 0000000000000..9ab60bf661a49 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/NetworkSecurityGroupOperations.cs @@ -0,0 +1,298 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure; +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Network; +using Azure.ResourceManager.Network.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Network +{ + /// + /// A class representing the operations that can be performed over a specific NetworkSecurityGroup. + /// + public class NetworkSecurityGroupOperations : ResourceOperationsBase, ITaggableResource, IDeletableResource + { + /// + /// Initializes a new instance of the class. + /// + /// An instance of that has an id for a virtual machine. + internal NetworkSecurityGroupOperations(GenericResourceOperations genericOperations) + : base(genericOperations) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The network security group name. + internal NetworkSecurityGroupOperations(ResourceGroupOperations resourceGroup, string nsgName) + : base(resourceGroup, $"{resourceGroup.Id}/providers/Microsoft.Network/networkSecurityGroups/{nsgName}") + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + protected NetworkSecurityGroupOperations(ResourceOperationsBase operation, ResourceIdentifier id) + : base(operation, id) + { + } + + /// + protected override ResourceType ValidResourceType => ResourceType; + + /// + /// Gets the resource type definition for a network security group. + /// + public static readonly ResourceType ResourceType = "Microsoft.Network/networkSecurityGroups"; + + private NetworkSecurityGroupsOperations Operations => new NetworkManagementClient( + Id.Subscription, + BaseUri, + Credential, + ClientOptions.Convert()).NetworkSecurityGroups; + + /// + /// Updates the network security group rules. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// The rules to be updated. + /// An that allows polling for completion of the operation. + public ArmOperation UpdateRules(CancellationToken cancellationToken = default, params SecurityRule[] rules) + { + var resource = GetResource(); + foreach (var rule in rules) + { + // Note that this makes use of the + var matchingRule = resource.Data.SecurityRules.FirstOrDefault(r => ResourceIdentifier.Equals(r.Id, rule.Id)); + if (matchingRule != null) + { + matchingRule.Access = rule.Access; + matchingRule.Description = rule.Description; + matchingRule.DestinationAddressPrefix = rule.DestinationAddressPrefix; + //matchingRule.DestinationAddressPrefixes = rule.DestinationAddressPrefixes; + matchingRule.DestinationPortRange = rule.DestinationPortRange; + //matchingRule.DestinationPortRanges = rule.DestinationPortRanges; + matchingRule.Direction = rule.Direction; + matchingRule.Priority = rule.Priority; + matchingRule.Protocol = rule.Protocol; + matchingRule.SourceAddressPrefix = rule.SourceAddressPrefix; + //matchingRule.SourceAddressPrefixes = rule.SourceAddressPrefixes; + matchingRule.SourcePortRange = rule.SourcePortRange; + //matchingRule.SourcePortRanges = rule.SourcePortRanges; + } + else + { + resource.Data.SecurityRules.Add(rule); + } + } + + return new PhArmOperation( + Operations.StartCreateOrUpdate(Id.ResourceGroup, Id.Name, resource.Data), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + public override ArmResponse Get() + { + return new PhArmResponse(Operations.Get(Id.ResourceGroup, Id.Name), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + public override async Task> GetAsync(CancellationToken cancellationToken = default) + { + return new PhArmResponse(await Operations.GetAsync(Id.ResourceGroup, Id.Name, null, cancellationToken), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + public ArmResponse AddTag(string key, string value) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmResponse( + Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + public async Task> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmResponse(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + public ArmOperation StartAddTag(string key, string value) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmOperation( + Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + public async Task> StartAddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmOperation(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + public ArmResponse Delete() + { + return new ArmResponse(Operations.StartDelete(Id.ResourceGroup, Id.Name).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult()); + } + + /// + public async Task> DeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmResponse((await Operations.StartDeleteAsync(Id.ResourceGroup, Id.Name, cancellationToken)).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult()); + } + + /// + public ArmOperation StartDelete(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(Operations.StartDelete(Id.ResourceGroup, Id.Name, cancellationToken)); + } + + /// + public async Task> StartDeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(await Operations.StartDeleteAsync(Id.ResourceGroup, Id.Name, cancellationToken)); + } + + /// + protected override NetworkSecurityGroup GetResource() + { + return Get().Value; + } + + /// + public ArmResponse SetTags(IDictionary tags) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmResponse( + Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + public async Task> SetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmResponse(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + public ArmOperation StartSetTags(IDictionary tags) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmOperation( + Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + public async Task> StartSetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmOperation(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + public ArmResponse RemoveTag(string key) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmResponse( + Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + public async Task> RemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmResponse(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + public ArmOperation StartRemoveTag(string key) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmOperation( + Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + public async Task> StartRemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmOperation(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new NetworkSecurityGroup(this, new NetworkSecurityGroupData(n))); + } + + /// + /// Lists all available geo-locations. + /// + /// A collection of location that may take multiple service requests to iterate over. + public IEnumerable ListAvailableLocations() + { + return ListAvailableLocations(ResourceType); + } + + /// + /// Lists all available geo-locations. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of location that may take multiple service requests to iterate over. + /// The default subscription id is null. + public async Task> ListAvailableLocationsAsync(CancellationToken cancellationToken = default) + { + return await ListAvailableLocationsAsync(ResourceType, cancellationToken); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/Placeholder/NetworkInterfaceData.cs b/sdk/resourcemanager/Proto.Client/network/Placeholder/NetworkInterfaceData.cs new file mode 100644 index 0000000000000..c69b4442041fd --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/Placeholder/NetworkInterfaceData.cs @@ -0,0 +1,125 @@ +using Azure.ResourceManager.Network.Models; +using Azure.ResourceManager.Core; +using System; +using System.Collections.Generic; + +namespace Proto.Network +{ + /// + /// A network interface in a resource group. + /// + public class NetworkInterfaceData : TrackedResource + { + /// + /// The ARM resource type for this . + /// + public static ResourceType ResourceType => "Microsoft.Network/networkInterfaces"; + + /// + /// Initializes a new instance of the class. + /// + /// The low level network interace model. + public NetworkInterfaceData(Azure.ResourceManager.Network.Models.NetworkInterface nic) : base(nic.Id, nic.Location, nic) + { + } + + /// + /// Gets the resource tags. + /// + public override IDictionary Tags => Model.Tags; + + /// + /// Gets the resource name. + /// + public override string Name => Model.Name; + + /// + /// Gets a unique read-only string that changes whenever the resource is updated. + /// + public string Etag => Model.Etag; + + /// + /// Gets the reference to a linked virtual machine. + /// + public SubResource VirtualMachine => Model.VirtualMachine; + + /// + /// Gets the reference to the linked NetworkSecurityGroup resource. + /// + public Azure.ResourceManager.Network.Models.NetworkSecurityGroup NetworkSecurityGroup + { + get => Model.NetworkSecurityGroup; + set => Model.NetworkSecurityGroup = value; + } + + /// + /// Gets a reference to the private endpoint to which the network interface is linked. + /// + public PrivateEndpoint PrivateEndpoint => Model.PrivateEndpoint; + + /// + /// Gets or sets a list of IPConfigurations of the network interface. + /// + public IList IpConfigurations + { + get => Model.IpConfigurations; + } + + /// + /// Gets a list of TapConfigurations of the newtork interface. + /// + public IReadOnlyList TapConfigurations=> Model.TapConfigurations; + + /// + /// Gets or sets the DNS settings in network interface. + /// + public NetworkInterfaceDnsSettings DnsSettings + { + get => Model.DnsSettings; + set => Model.DnsSettings = value; + } + + /// + /// Gets the MAC address of the network interface. + /// + public string MacAddress => Model.MacAddress; + + /// + /// Gets a value indicating whether this is a primary network interface on a virtual machine. + /// + public bool? Primary => Model.Primary; + + /// + /// Gets or sets a value determining if the network interface is accelerated networking enabled. + /// + public bool? EnableAcceleratedNetworking + { + get => Model.EnableAcceleratedNetworking; + set => Model.EnableAcceleratedNetworking = value; + } + + /// + /// Gets or sets a value Indicating whether IP forwarding is enabled on this network interface. + /// + public bool? EnableIPForwarding + { + get => Model.EnableIPForwarding; + set => Model.EnableIPForwarding = value; + } + + /// + /// Gets a list of references to linked BareMetal resources. + /// + public IReadOnlyList HostedWorkloads => Model.HostedWorkloads; + + /// + /// Gets the resource GUID property of the network interface resource. + /// + public string ResourceGuid => Model.ResourceGuid; + + /// + /// Gets the provisioning state of the network interface resource. + /// + public ProvisioningState? ProvisioningState => Model.ProvisioningState; + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/Placeholder/NetworkSecurityGroupData.cs b/sdk/resourcemanager/Proto.Client/network/Placeholder/NetworkSecurityGroupData.cs new file mode 100644 index 0000000000000..bfb5dfadc68db --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/Placeholder/NetworkSecurityGroupData.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Network.Models; +using System.Collections.Generic; + +namespace Proto.Network +{ + /// + /// A class representing the NetworkSecurityGroup data model. + /// + public class NetworkSecurityGroupData : + TrackedResource + { + /// + /// Initializes a new instance of the class. + /// + /// The network security group to initialize. + public NetworkSecurityGroupData(Azure.ResourceManager.Network.Models.NetworkSecurityGroup nsg) + : base(nsg.Id, nsg.Location, nsg) + { + } + + /// Resource tags. + public override IDictionary Tags => Model.Tags; + + /// The name property of the network security group resource. + public override string Name => Model.Name; + + /// A unique read-only string that changes whenever the resource is updated. + public string Etag => Model.Etag; + + /// A collection of security rules of the network security group. + public IList SecurityRules + { + get => Model.SecurityRules; + } + + /// The default security rules of network security group. + public IReadOnlyList DefaultSecurityRules => Model.DefaultSecurityRules; + + /// A collection of references to network interfaces. + public IReadOnlyList NetworkInterfaces => Model.NetworkInterfaces; + + /// A collection of references to subnets. + public IReadOnlyList Subnets => Model.Subnets; + + /// A collection of references to flow log resources. + + public IReadOnlyList FlowLogs => Model.FlowLogs; + + /// The resource GUID property of the network security group resource. + public string ResourceGuid => Model.ResourceGuid; + + /// The provisioning state of the network security group resource. + public ProvisioningState? ProvisioningState => Model.ProvisioningState; + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/Placeholder/PublicIPAddressData.cs b/sdk/resourcemanager/Proto.Client/network/Placeholder/PublicIPAddressData.cs new file mode 100644 index 0000000000000..84303c1f83fc3 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/Placeholder/PublicIPAddressData.cs @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.ResourceManager.Network.Models; +using Azure.ResourceManager.Core; +using System; +using System.Collections.Generic; + +namespace Proto.Network +{ + /// + /// A class representing the public IP address data model. + /// + public class PublicIPAddressData : TrackedResource + { + /// + /// Gets the resource type definition for a public IP address. + /// + public static ResourceType ResourceType => "Microsoft.Network/publicIpAddresses"; + + /// + /// Initializes a new instance of the class. + /// + /// The public IP address to initialize. + public PublicIPAddressData(PublicIPAddress ip) : base(ip.Id, ip.Location, ip) + { + } + + /// Resource tags. + public override IDictionary Tags => Model.Tags; + + /// The name property of the network security group resource. + public override string Name => Model.Name; + + /// The public IP address SKU. + public PublicIPAddressSku Sku + { + get => Model.Sku; + set => Model.Sku = value; + } + + /// A unique read-only string that changes whenever the resource is updated. + public string Etag => Model.Etag; + + /// A list of availability zones denoting the IP allocated for the resource needs to come from. + public IList Zones + { + get => Model.Zones; + } + + /// The public IP address allocation method. + public IPAllocationMethod? PublicIPAllocationMethod + { + get => Model.PublicIPAllocationMethod; + set => Model.PublicIPAllocationMethod = value; + } + + /// The public IP address version. + public IPVersion? PublicIPAddressVersion + { + get => Model.PublicIPAddressVersion; + set => Model.PublicIPAddressVersion = value; + } + + /// The IP configuration associated with the public IP address. + public IPConfiguration IpConfiguration => Model.IpConfiguration; + + /// The FQDN of the DNS record associated with the public IP address. + public PublicIPAddressDnsSettings DnsSettings + { + get => Model.DnsSettings; + set => Model.DnsSettings = value; + } + + /// The DDoS protection custom policy associated with the public IP address. + public DdosSettings DdosSettings + { + get => Model.DdosSettings; + set => Model.DdosSettings = value; + } + + /// The list of tags associated with the public IP address. + public IList IpTags + { + get => Model.IpTags; + } + + /// The IP address associated with the public IP address resource. + public string IpAddress + { + get => Model.IpAddress; + set => Model.IpAddress = value; + } + + /// The Public IP Prefix this Public IP Address should be allocated from. + public SubResource PublicIPPrefix + { + get => Model.PublicIPPrefix; + set => Model.PublicIPPrefix = value; + } + + /// The idle timeout of the public IP address. + public int? IdleTimeoutInMinutes + { + get => Model.IdleTimeoutInMinutes; + set => Model.IdleTimeoutInMinutes = value; + } + + /// The resource GUID property of the public IP address resource. + public string ResourceGuid => Model.ResourceGuid; + + /// The provisioning state of the public IP address resource. + public ProvisioningState? ProvisioningState => Model.ProvisioningState; + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/Placeholder/SubnetData.cs b/sdk/resourcemanager/Proto.Client/network/Placeholder/SubnetData.cs new file mode 100644 index 0000000000000..66fec3350b717 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/Placeholder/SubnetData.cs @@ -0,0 +1,124 @@ +using Azure.ResourceManager.Network.Models; +using Azure.ResourceManager.Core; +using System.Collections.Generic; + +namespace Proto.Network +{ + /// + /// A class representing the subnet data model. + /// + public class SubnetData : ProxyResource + { + /// + /// Initializes a new instance of the class. + /// + public SubnetData(Azure.ResourceManager.Network.Models.Subnet sub) : base(sub.Id, sub) + { + } + + /// + /// Gets the subnet id. + /// + public override string Name => Model.Name; + + /// + /// The provisioning state of the subnet resource. + /// + public ProvisioningState? ProvisioningState => Model.ProvisioningState; + + /// + /// A read-only string identifying the intention use for this subnet based on delegations and other user-defined properties. + /// + public string Purpose => Model.Purpose; + + /// An array of references to the delegations on the subnet. + public IList Delegations + { + get => Model.Delegations; + } + + /// An array of references to services injecting into this subnet. + public IReadOnlyList ServiceAssociationLinks => Model.ServiceAssociationLinks; + + /// An array of references to the external resources using subnet. + public IReadOnlyList ResourceNavigationLinks => Model.ResourceNavigationLinks; + + /// Array of IpAllocation which reference this subnet. + public IList IpAllocations + { + get => Model.IpAllocations; + } + + /// Array of IP configuration profiles which reference this subnet. + public IReadOnlyList IpConfigurationProfiles => Model.IpConfigurationProfiles; + + /// An array of references to the network interface IP configurations using subnet. + public IReadOnlyList IpConfigurations => Model.IpConfigurations; + + /// Enable or Disable apply network policies on private end point in the subnet. + public string PrivateEndpointNetworkPolicies + { + get => Model.PrivateEndpointNetworkPolicies; + set => Model.PrivateEndpointNetworkPolicies = value; + } + + /// An array of references to private endpoints. + public IReadOnlyList PrivateEndpoints => Model.PrivateEndpoints; + + /// An array of service endpoints. + public IList ServiceEndpoints + { + get => Model.ServiceEndpoints; + } + + /// Nat gateway associated with this subnet. + public SubResource NatGateway + { + get => Model.NatGateway; + set => Model.NatGateway = value; + } + + /// The reference to the RouteTable resource. + public RouteTable RouteTable + { + get => Model.RouteTable; + set => Model.RouteTable = value; + } + + /// The reference to the NetworkSecurityGroup resource. + public Azure.ResourceManager.Network.Models.NetworkSecurityGroup NetworkSecurityGroup + { + get => Model.NetworkSecurityGroup; + set => Model.NetworkSecurityGroup = value; + } + + /// List of address prefixes for the subnet. + public IList AddressPrefixes + { + get => Model.AddressPrefixes; + } + + /// The address prefix for the subnet. + public string AddressPrefix + { + get => Model.AddressPrefix; + set => Model.AddressPrefix = value; + } + + /// A unique read-only string that changes whenever the resource is updated. + public string Etag => Model.Etag; + + /// An array of service endpoint policies. + public IList ServiceEndpointPolicies + { + get => Model.ServiceEndpointPolicies; + } + + /// Enable or Disable apply network policies on private link service in the subnet. + public string PrivateLinkServiceNetworkPolicies + { + get => Model.PrivateLinkServiceNetworkPolicies; + set => Model.PrivateLinkServiceNetworkPolicies = value; + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/Placeholder/VirtualNetworkData.cs b/sdk/resourcemanager/Proto.Client/network/Placeholder/VirtualNetworkData.cs new file mode 100644 index 0000000000000..07e62b448ca98 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/Placeholder/VirtualNetworkData.cs @@ -0,0 +1,102 @@ +using Azure.ResourceManager.Network.Models; +using Azure.ResourceManager.Core; +using System; +using System.Collections.Generic; + +namespace Proto.Network +{ + /// + /// A class representing the virtual nerwork data model. + /// + public class VirtualNetworkData : TrackedResource + { + /// + /// Gets the resource type definition for a virtual nerwork. + /// + public static ResourceType ResourceType => "Microsoft.Network/virtualNetworks"; + + /// + /// Initializes a new instance of the class. + /// + /// The virtual nerwork to initialize. + public VirtualNetworkData(Azure.ResourceManager.Network.Models.VirtualNetwork vnet) : base(vnet.Id, vnet.Location, vnet) + { + } + + /// + public override IDictionary Tags => Model.Tags; + + /// + public override string Name => Model.Name; + + /// A unique read-only string that changes whenever the resource is updated. + public string Etag => Model.Etag; + + /// The AddressSpace that contains an array of IP address ranges that can be used by subnets. + public AddressSpace AddressSpace + { + get => Model.AddressSpace; + set => Model.AddressSpace = value; + } + + /// The dhcpOptions that contains an array of DNS servers available to VMs deployed in the virtual network. + public DhcpOptions DhcpOptions + { + get => Model.DhcpOptions; + set => Model.DhcpOptions = value; + } + + /// A list of subnet in a Virtual Network. + public IList Subnets + { + get => Model.Subnets; + } + + /// A list of peering in a Virtual Network. + public IList VirtualNetworkPeerings + { + get => Model.VirtualNetworkPeerings; + } + + /// The resourceGuid property of the Virtual Network resource. + public string ResourceGuid => Model.ResourceGuid; + + /// The provisioning state of the virtual network resource. + public ProvisioningState? ProvisioningState => Model.ProvisioningState; + + /// Indicates if DDoS protection is enabled for all the protected resources in the virtual network. It requires a DDoS protection plan associated with the resource. + public bool? EnableDdosProtection + { + get => Model.EnableDdosProtection; + set => Model.EnableDdosProtection = value; + } + + /// Indicates if VM protection is enabled for all the subnets in the virtual network. + public bool? EnableVmProtection + { + get => Model.EnableVmProtection; + set => Model.EnableVmProtection = value; + } + + /// The DDoS protection plan associated with the virtual network. + public SubResource DdosProtectionPlan + + { + get => Model.DdosProtectionPlan; + set => Model.DdosProtectionPlan = value; + } + + /// Bgp Communities sent over ExpressRoute with each route corresponding to a prefix in this VNET. + public VirtualNetworkBgpCommunities BgpCommunities + { + get => Model.BgpCommunities; + set => Model.BgpCommunities = value; + } + + /// Array of IpAllocation which reference this VNET. + public IList IpAllocations + { + get => Model.IpAllocations; + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/Proto.Network.csproj b/sdk/resourcemanager/Proto.Client/network/Proto.Network.csproj new file mode 100644 index 0000000000000..5bee3360da488 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/Proto.Network.csproj @@ -0,0 +1,20 @@ + + + + netstandard2.0 + Proto.Network + + + + C:\Git\azure-proto-sdk\azure-proto-network\obj\azure-proto-network.xml + + + + + + + + + + + diff --git a/sdk/resourcemanager/Proto.Client/network/PublicIpAddress.cs b/sdk/resourcemanager/Proto.Client/network/PublicIpAddress.cs new file mode 100644 index 0000000000000..12be1f48000c6 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/PublicIpAddress.cs @@ -0,0 +1,39 @@ +using System.Threading.Tasks; +using Azure.ResourceManager.Core; + +namespace Proto.Network +{ + /// + /// Class representing a PublicIpAddress resource along with the instance operations that can be performed on it. + /// + public class PublicIpAddress : PublicIpAddressOperations + { + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The resource that is the target of operations. + internal PublicIpAddress(ResourceOperationsBase options, PublicIPAddressData resource) + : base(options, resource.Id) + { + Data = resource; + } + + /// + /// Gets the data representing this PublicIPAddress. + /// + public PublicIPAddressData Data { get; private set; } + + /// + protected override PublicIpAddress GetResource() + { + return this; + } + + /// + protected override Task GetResourceAsync() + { + return Task.FromResult(this); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/PublicIpAddressContainer.cs b/sdk/resourcemanager/Proto.Client/network/PublicIpAddressContainer.cs new file mode 100644 index 0000000000000..6a0ab4e5dadbb --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/PublicIpAddressContainer.cs @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure; +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Core.Resources; +using Azure.ResourceManager.Network; +using Azure.ResourceManager.Network.Models; +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Network +{ + /// + /// A class representing collection of PublicIpAddress and their operations over a resource group. + /// + public class PublicIpAddressContainer : ResourceContainerBase + { + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + internal PublicIpAddressContainer(ResourceGroupOperations resourceGroup) + : base(resourceGroup) + { + } + + /// + /// Gets the valid resource type for this resource. + /// + protected override ResourceType ValidResourceType => ResourceGroupOperations.ResourceType; + + private PublicIPAddressesOperations Operations => new NetworkManagementClient( + Id.Subscription, + BaseUri, + Credential, + ClientOptions.Convert()).PublicIPAddresses; + + /// + public override ArmResponse CreateOrUpdate(string name, PublicIPAddressData resourceDetails) + { + var operation = Operations.StartCreateOrUpdate(Id.ResourceGroup, name, resourceDetails); + return new PhArmResponse( + operation.WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult(), + n => new PublicIpAddress(Parent, new PublicIPAddressData(n))); + } + + /// + public override async Task> CreateOrUpdateAsync(string name, PublicIPAddressData resourceDetails, CancellationToken cancellationToken = default) + { + var operation = await Operations.StartCreateOrUpdateAsync(Id.ResourceGroup, name, resourceDetails, cancellationToken).ConfigureAwait(false); + return new PhArmResponse( + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false), + n => new PublicIpAddress(Parent, new PublicIPAddressData(n))); + } + + /// + public override ArmOperation StartCreateOrUpdate(string name, PublicIPAddressData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + Operations.StartCreateOrUpdate(Id.ResourceGroup, name, resourceDetails, cancellationToken), + n => new PublicIpAddress(Parent, new PublicIPAddressData(n))); + } + + /// + public override async Task> StartCreateOrUpdateAsync(string name, PublicIPAddressData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + await Operations.StartCreateOrUpdateAsync(Id.ResourceGroup, name, resourceDetails, cancellationToken).ConfigureAwait(false), + n => new PublicIpAddress(Parent, new PublicIPAddressData(n))); + } + + /// + /// Construct an object used to create a public IP address. + /// + /// The location to create the network security group. + /// Object used to create a . + public ArmBuilder Construct(LocationData location = null) + { + var parent = GetParentResource(); + var ipAddress = new PublicIPAddress() + { + PublicIPAddressVersion = IPVersion.IPv4.ToString(), + PublicIPAllocationMethod = IPAllocationMethod.Dynamic, + Location = location ?? parent.Data.Location, + }; + + return new ArmBuilder(this, new PublicIPAddressData(ipAddress)); + } + + /// + /// List the public IP addresses for this resource group. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of that may take multiple service requests to iterate over. + public Pageable List(CancellationToken cancellationToken = default) + { + return new PhWrappingPageable( + Operations.List(Id.Name, cancellationToken), + Convertor()); + } + + /// + /// List the public IP addresses for this resource group. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of that may take multiple service requests to iterate over. + public AsyncPageable ListAsync(CancellationToken cancellationToken = default) + { + return new PhWrappingAsyncPageable( + Operations.ListAsync(Id.Name, cancellationToken), + Convertor()); + } + + /// + /// Filters the list of public IP addresses for this resource group represented as generic resources. + /// + /// The substring to filter by. + /// The number of items to truncate by. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of that may take multiple service requests to iterate over. + public Pageable ListByName(string filter, int? top = null, CancellationToken cancellationToken = default) + { + ResourceFilterCollection filters = new ResourceFilterCollection(PublicIPAddressData.ResourceType); + filters.SubstringFilter = filter; + return ResourceListOperations.ListAtContext(Parent as ResourceGroupOperations, filters, top, cancellationToken); + } + + /// + /// Filters the list of public IP addresses for this resource group represented as generic resources. + /// + /// The substring to filter by. + /// The number of items to truncate by. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of that may take multiple service requests to iterate over. + public AsyncPageable ListByNameAsync(string filter, int? top = null, CancellationToken cancellationToken = default) + { + ResourceFilterCollection filters = new ResourceFilterCollection(PublicIPAddressData.ResourceType); + filters.SubstringFilter = filter; + return ResourceListOperations.ListAtContextAsync(Parent as ResourceGroupOperations, filters, top, cancellationToken); + } + + /// + /// Filters the list of public IP addresses for this resource group represented as generic resources. + /// Makes an additional network call to retrieve the full data model for each network security group. + /// + /// The substring to filter by. + /// The number of items to truncate by. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of that may take multiple service requests to iterate over. + public Pageable ListByNameExpanded(string filter, int? top = null, CancellationToken cancellationToken = default) + { + var results = ListByName(filter, top, cancellationToken); + return new PhWrappingPageable(results, s => new PublicIpAddressOperations(s).Get().Value); + } + + /// + /// Filters the list of public IP addresses for this resource group represented as generic resources. + /// Makes an additional network call to retrieve the full data model for each network security group. + /// + /// The substring to filter by. + /// The number of items to truncate by. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of that may take multiple service requests to iterate over. + public AsyncPageable ListByNameExpandedAsync(string filter, int? top = null, CancellationToken cancellationToken = default) + { + var results = ListByNameAsync(filter, top, cancellationToken); + return new PhWrappingAsyncPageable(results, s => new PublicIpAddressOperations(s).Get().Value); + } + + private Func Convertor() + { + return s => new PublicIpAddress(Parent, new PublicIPAddressData(s)); + } + /// + public override ArmResponse Get(string publicIpAddressesName) + { + return new PhArmResponse(Operations.Get(Id.ResourceGroup, publicIpAddressesName), Convertor()); + } + + /// + public override async Task> GetAsync(string publicIpAddressesName, CancellationToken cancellationToken = default) + { + return new PhArmResponse(await Operations.GetAsync(Id.ResourceGroup, publicIpAddressesName), Convertor()); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/PublicIpAddressOperations.cs b/sdk/resourcemanager/Proto.Client/network/PublicIpAddressOperations.cs new file mode 100644 index 0000000000000..e4fb92f73b81b --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/PublicIpAddressOperations.cs @@ -0,0 +1,292 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure; +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Network; +using Azure.ResourceManager.Network.Models; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Network +{ + /// + /// A class representing the operations that can be performed over a specific NetworkSecurityGroup. + /// + public class PublicIpAddressOperations : ResourceOperationsBase, ITaggableResource, IDeletableResource + { + /// + /// Initializes a new instance of the class. + /// + /// An instance of that has an id for a virtual machine. + internal PublicIpAddressOperations(GenericResourceOperations genericOperations) + : base(genericOperations) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The public ip address name. + internal PublicIpAddressOperations(ResourceGroupOperations resourceGroup, string publicIpName) + : base(resourceGroup, $"{resourceGroup.Id}/providers/Microsoft.Network/publicIpAddresses/{publicIpName}") + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + protected PublicIpAddressOperations(ResourceOperationsBase options, ResourceIdentifier id) + : base(options, id) + { + } + + /// + /// Gets the resource type definition for a public IP address. + /// + public static readonly ResourceType ResourceType = "Microsoft.Network/publicIPAddresses"; + + /// + protected override ResourceType ValidResourceType => ResourceType; + + private PublicIPAddressesOperations Operations => new NetworkManagementClient( + Id.Subscription, + BaseUri, + Credential, + ClientOptions.Convert()).PublicIPAddresses; + + /// + /// The operation to delete a public IP address. + /// + /// A response with the operation for this resource. + public ArmResponse Delete() + { + return new ArmResponse(Operations.StartDelete(Id.ResourceGroup, Id.Name).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult()); + } + + /// + /// The operation to delete a public IP address. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + public async Task> DeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmResponse((await Operations.StartDeleteAsync(Id.ResourceGroup, Id.Name, cancellationToken)).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult()); + } + + /// + /// The operation to delete a public IP address. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// An that allows polling for completion of the operation. + public ArmOperation StartDelete(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(Operations.StartDelete(Id.ResourceGroup, Id.Name, cancellationToken)); + } + + /// + /// The operation to delete a public IP address. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> StartDeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(await Operations.StartDeleteAsync(Id.ResourceGroup, Id.Name, cancellationToken)); + } + + /// + public override ArmResponse Get() + { + return new PhArmResponse(Operations.Get(Id.ResourceGroup, Id.Name), + n => new PublicIpAddress(this, new PublicIPAddressData(n))); + } + + /// + public override async Task> GetAsync(CancellationToken cancellationToken = default) + { + return new PhArmResponse(await Operations.GetAsync(Id.ResourceGroup, Id.Name, null, cancellationToken), + n => new PublicIpAddress(this, new PublicIPAddressData(n))); + } + + /// + /// Add a tag to a public IP address. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// An that allows polling for completion of the operation. + public ArmResponse AddTag(string key, string value) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmResponse(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new PublicIpAddress(this, new PublicIPAddressData(n))); + } + + /// + /// Add a tag to a public IP address. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmResponse(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new PublicIpAddress(this, new PublicIPAddressData(n))); + } + + /// + /// Add a tag to a public IP address. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// An that allows polling for completion of the operation. + public ArmOperation StartAddTag(string key, string value) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmOperation(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new PublicIpAddress(this, new PublicIPAddressData(n))); + } + + /// + /// Add a tag to a public IP address. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> StartAddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmOperation(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new PublicIpAddress(this, new PublicIPAddressData(n))); + } + + /// + public ArmResponse SetTags(IDictionary tags) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmResponse(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new PublicIpAddress(this, new PublicIPAddressData(n))); + } + + /// + public async Task> SetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmResponse(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new PublicIpAddress(this, new PublicIPAddressData(n))); + } + + /// + public ArmOperation StartSetTags(IDictionary tags) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmOperation(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new PublicIpAddress(this, new PublicIPAddressData(n))); + } + + /// + public async Task> StartSetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmOperation(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new PublicIpAddress(this, new PublicIPAddressData(n))); + } + + /// + public ArmResponse RemoveTag(string key) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmResponse(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new PublicIpAddress(this, new PublicIPAddressData(n))); + } + + /// + public async Task> RemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmResponse(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new PublicIpAddress(this, new PublicIPAddressData(n))); + } + + /// + public ArmOperation StartRemoveTag(string key) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmOperation(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new PublicIpAddress(this, new PublicIPAddressData(n))); + } + + /// + public async Task> StartRemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmOperation(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new PublicIpAddress(this, new PublicIPAddressData(n))); + } + + /// + /// Lists all available geo-locations. + /// + /// A collection of location that may take multiple service requests to iterate over. + public IEnumerable ListAvailableLocations() + { + return ListAvailableLocations(ResourceType); + } + + /// + /// Lists all available geo-locations. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of location that may take multiple service requests to iterate over. + /// The default subscription id is null. + public async Task> ListAvailableLocationsAsync(CancellationToken cancellationToken = default) + { + return await ListAvailableLocationsAsync(ResourceType, cancellationToken); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/README.MD b/sdk/resourcemanager/Proto.Client/network/README.MD new file mode 100644 index 0000000000000..71ceaad3b35c1 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/README.MD @@ -0,0 +1,3 @@ +# Proto Network + +Prototype version of Azure.ResourceManager.Network used to showcase and test the new prototype track 2 management plane SDK \ No newline at end of file diff --git a/sdk/resourcemanager/Proto.Client/network/Subnet.cs b/sdk/resourcemanager/Proto.Client/network/Subnet.cs new file mode 100644 index 0000000000000..dbbe6abe87eda --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/Subnet.cs @@ -0,0 +1,37 @@ +using System.Threading.Tasks; +using Azure.ResourceManager.Core; + +namespace Proto.Network +{ + /// + /// A class representing a subnet along with the instance operations that can be performed on it. + /// + public class Subnet : SubnetOperations + { + /// + /// Initializes a new instance of the class. + /// + internal Subnet(ResourceOperationsBase options, SubnetData resource) + : base(options, resource.Id) + { + Data = resource; + } + + /// + /// Gets the data representing the subnet + /// + public SubnetData Data { get; private set; } + + /// + protected override Subnet GetResource() + { + return this; + } + + /// + protected override Task GetResourceAsync() + { + return Task.FromResult(this); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/SubnetBuilder.cs b/sdk/resourcemanager/Proto.Client/network/SubnetBuilder.cs new file mode 100644 index 0000000000000..b1c130ede655f --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/SubnetBuilder.cs @@ -0,0 +1,27 @@ +using Azure.ResourceManager.Core; + +namespace Proto.Network +{ + /// + /// A class representing a builder object to help create a subnet. + /// + public class SubnetBuilder : ArmBuilder + { + /// + /// Initializes a new instance of the class. + /// + /// The container to create the subnet in. + /// The data model representing the subnet to create. + internal SubnetBuilder(SubnetContainer container, SubnetData subnet) + : base(container, subnet) + { + + } + + /// + protected override void OnBeforeBuild() + { + Resource.Model.Name = ResourceName; + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/SubnetContainer.cs b/sdk/resourcemanager/Proto.Client/network/SubnetContainer.cs new file mode 100644 index 0000000000000..51da32cf51e44 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/SubnetContainer.cs @@ -0,0 +1,131 @@ +using Azure; +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Network; +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Network +{ + /// + /// A class representing collection of Subnets and their operations over a VirtualNetwork. + /// + public class SubnetContainer : ResourceContainerBase + { + /// + /// Initializes a new instance of the class. + /// + /// The virtual network associate with this subnet + internal SubnetContainer(VirtualNetworkOperations virtualNetwork) + : base(virtualNetwork) + { + } + + /// + protected override ResourceType ValidResourceType => VirtualNetworkOperations.ResourceType; + + private SubnetsOperations Operations => new NetworkManagementClient( + Id.Subscription, + BaseUri, + Credential, + ClientOptions.Convert()).Subnets; + + /// + public override ArmResponse CreateOrUpdate(string name, SubnetData resourceDetails) + { + var operation = Operations.StartCreateOrUpdate(Id.ResourceGroup, Id.Name, name, resourceDetails.Model); + return new PhArmResponse( + operation.WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult(), + s => new Subnet(Parent, new SubnetData(s))); + } + + /// + public override async Task> CreateOrUpdateAsync(string name, SubnetData resourceDetails, CancellationToken cancellationToken = default) + { + var operation = await Operations.StartCreateOrUpdateAsync(Id.ResourceGroup, Id.Name, name, resourceDetails.Model, cancellationToken).ConfigureAwait(false); + return new PhArmResponse( + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false), + s => new Subnet(Parent, new SubnetData(s))); + } + + /// + public override ArmOperation StartCreateOrUpdate(string name, SubnetData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + Operations.StartCreateOrUpdate(Id.ResourceGroup, Id.Name, name, resourceDetails.Model, cancellationToken), + s => new Subnet(Parent, new SubnetData(s))); + } + + /// + public async override Task> StartCreateOrUpdateAsync(string name, SubnetData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + await Operations.StartCreateOrUpdateAsync(Id.ResourceGroup, Id.Name, name, resourceDetails.Model, cancellationToken).ConfigureAwait(false), + s => new Subnet(Parent, new SubnetData(s))); + } + + /// + /// Constructs an object used to create a subnet. + /// + /// The CIDR of the resource. + /// The network security group of the resource. + /// A builder with and . + public SubnetBuilder Construct(string subnetCidr, NetworkSecurityGroupData group = null) + { + var subnet = new Azure.ResourceManager.Network.Models.Subnet() + { + AddressPrefix = subnetCidr, + }; + + if (null != group) + { + subnet.NetworkSecurityGroup = group.Model; + } + + return new SubnetBuilder(this, new SubnetData(subnet)); + } + + /// + /// Lists the subnets for this virtual network. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of resource operations that may take multiple service requests to iterate over. + public Pageable List(CancellationToken cancellationToken = default) + { + return new PhWrappingPageable( + Operations.List(Id.ResourceGroup, Id.Name, cancellationToken), + convertor()); + } + + /// + /// Lists the subnets for this virtual network. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of resource operations that may take multiple service requests to iterate over. + public AsyncPageable ListAsync(CancellationToken cancellationToken = default) + { + return new PhWrappingAsyncPageable( + Operations.ListAsync(Id.ResourceGroup, Id.Name, cancellationToken), + convertor()); + } + + private Func convertor() + { + return s => new Subnet(Parent, new SubnetData(s)); + } + + /// + public override ArmResponse Get(string subnetName) + { + return new PhArmResponse(Operations.Get(Id.ResourceGroup, Id.Name, subnetName), + n => new Subnet(Parent, new SubnetData(n))); + } + + /// + public override async Task> GetAsync(string subnetName, CancellationToken cancellationToken = default) + { + return new PhArmResponse(await Operations.GetAsync(Id.ResourceGroup, Id.Name, subnetName, null, cancellationToken), + n => new Subnet(Parent, new SubnetData(n))); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/SubnetOperations.cs b/sdk/resourcemanager/Proto.Client/network/SubnetOperations.cs new file mode 100644 index 0000000000000..ff99d20d914a6 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/SubnetOperations.cs @@ -0,0 +1,110 @@ +using Azure; +using Azure.ResourceManager.Network; +using Azure.ResourceManager.Core; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Network +{ + /// + /// A class representing the operations that can be performed over a specific subnet. + /// + public class SubnetOperations : ResourceOperationsBase, IDeletableResource + { + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The name of the subnet. + internal SubnetOperations(VirtualNetworkOperations virtualNetwork, string subnetName) + : base(virtualNetwork, $"{virtualNetwork.Id}/subnets/{subnetName}") + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + protected SubnetOperations(ResourceOperationsBase options, ResourceIdentifier id) + : base(options, id) + { + } + + /// + /// Gets the resource type definition for a subnet. + /// + public static readonly ResourceType ResourceType = "Microsoft.Network/virtualNetworks/subnets"; + + /// + /// Gets the valid resource type definition for a subnet. + /// + protected override ResourceType ValidResourceType => ResourceType; + + private SubnetsOperations Operations => new NetworkManagementClient( + Id.Subscription, + BaseUri, + Credential, + ClientOptions.Convert()).Subnets; + + /// + /// The operation to delete a subnet. + /// + /// A response with the operation for this resource. + public ArmResponse Delete() + { + return new ArmResponse(Operations.StartDelete(Id.ResourceGroup, Id.Parent.Name, Id.Name).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult()); + } + + /// + /// The operation to delete a subnet. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + public async Task> DeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmResponse((await Operations.StartDeleteAsync(Id.ResourceGroup, Id.Parent.Name, Id.Name)).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult()); + } + + + /// + /// The operation to delete a subnet. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// An that allows polling for completion of the operation. + public ArmOperation StartDelete(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(Operations.StartDelete(Id.ResourceGroup, Id.Parent.Name, Id.Name)); + } + + /// + /// The operation to delete a subnet. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> StartDeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(await Operations.StartDeleteAsync(Id.ResourceGroup, Id.Parent.Name, Id.Name, cancellationToken)); + } + + /// + public override ArmResponse Get() + { + return new PhArmResponse(Operations.Get(Id.ResourceGroup, Id.Parent.Name, Id.Name), + n => new Subnet(this, new SubnetData(n))); + } + + /// + public override async Task> GetAsync(CancellationToken cancellationToken = default) + { + return new PhArmResponse(await Operations.GetAsync(Id.ResourceGroup, Id.Parent.Name, Id.Name, null, cancellationToken), + n => new Subnet(this, new SubnetData(n))); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/VirtualNetwork.cs b/sdk/resourcemanager/Proto.Client/network/VirtualNetwork.cs new file mode 100644 index 0000000000000..2606705790af9 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/VirtualNetwork.cs @@ -0,0 +1,39 @@ +using System.Threading.Tasks; +using Azure.ResourceManager.Core; + +namespace Proto.Network +{ + /// + /// A class representing a virtual nerwork along with the instance operations that can be performed on it. + /// + public class VirtualNetwork : VirtualNetworkOperations + { + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The resource that is the target of operations. + internal VirtualNetwork(ResourceOperationsBase options, VirtualNetworkData resource) + : base(options, resource.Id) + { + Data = resource; + } + + /// + /// Gets or sets the virtual nerwork data. + /// + public VirtualNetworkData Data { get; private set; } + + /// + protected override VirtualNetwork GetResource() + { + return this; + } + + /// + protected override Task GetResourceAsync() + { + return Task.FromResult(this); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/VirtualNetworkContainer.cs b/sdk/resourcemanager/Proto.Client/network/VirtualNetworkContainer.cs new file mode 100644 index 0000000000000..8d4bb9475e1ae --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/VirtualNetworkContainer.cs @@ -0,0 +1,192 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure; +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Core.Resources; +using Azure.ResourceManager.Network; +using Azure.ResourceManager.Network.Models; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Network +{ + /// + /// A class representing collection of virtual nerwork and their operations over a resource group. + /// + public class VirtualNetworkContainer : ResourceContainerBase + { + /// + /// Initializes a new instance of the class. + /// + /// The parent resource group. + internal VirtualNetworkContainer(ResourceGroupOperations resourceGroup) + : base(resourceGroup) + { + } + + /// + protected override ResourceType ValidResourceType => ResourceGroupOperations.ResourceType; + + private VirtualNetworksOperations Operations => new NetworkManagementClient( + Id.Subscription, + BaseUri, + Credential, + ClientOptions.Convert()).VirtualNetworks; + + /// + public override ArmResponse CreateOrUpdate(string name, VirtualNetworkData resourceDetails) + { + var operation = Operations.StartCreateOrUpdate(Id.ResourceGroup, name, resourceDetails); + return new PhArmResponse( + operation.WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult(), + n => new VirtualNetwork(Parent, new VirtualNetworkData(n))); + } + + /// + public async override Task> CreateOrUpdateAsync(string name, VirtualNetworkData resourceDetails, CancellationToken cancellationToken = default) + { + var operation = await Operations.StartCreateOrUpdateAsync(Id.ResourceGroup, name, resourceDetails, cancellationToken).ConfigureAwait(false); + return new PhArmResponse( + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false), + n => new VirtualNetwork(Parent, new VirtualNetworkData(n))); + } + + /// + public override ArmOperation StartCreateOrUpdate(string name, VirtualNetworkData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + Operations.StartCreateOrUpdate(Id.ResourceGroup, name, resourceDetails, cancellationToken), + n => new VirtualNetwork(Parent, new VirtualNetworkData(n))); + } + + /// + public async override Task> StartCreateOrUpdateAsync(string name, VirtualNetworkData resourceDetails, CancellationToken cancellationToken = default) + { + return new PhArmOperation( + await Operations.StartCreateOrUpdateAsync(Id.ResourceGroup, name, resourceDetails, cancellationToken).ConfigureAwait(false), + n => new VirtualNetwork(Parent, new VirtualNetworkData(n))); + } + + /// + /// Constructs an object used to create a virtual nerwork. + /// + /// The CIDR of the resource. + /// The location of the resource. + /// A builder with and . + public ArmBuilder Construct(string vnetCidr, LocationData location = null) + { + var parent = GetParentResource(); + var vnet = new Azure.ResourceManager.Network.Models.VirtualNetwork() + { + Location = location ?? parent.Data.Location, + AddressSpace = new AddressSpace(), + }; + vnet.AddressSpace.AddressPrefixes.Add(vnetCidr); + + return new ArmBuilder(this, new VirtualNetworkData(vnet)); + } + + /// + /// Lists the virtual network for this resource group. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of resource operations that may take multiple service requests to iterate over. + public Pageable List(CancellationToken cancellationToken = default) + { + return new PhWrappingPageable( + Operations.List(Id.Name, cancellationToken), + Convertor()); + } + + /// + /// Lists the virtual network for this resource group. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of resource operations that may take multiple service requests to iterate over. + public AsyncPageable ListAsync(CancellationToken cancellationToken = default) + { + return new PhWrappingAsyncPageable( + Operations.ListAsync(Id.Name, cancellationToken), + Convertor()); + } + + /// + /// Filters the list of virtual nerwork for this resource group represented as generic resources. + /// + /// The filter used in this operation. + /// The number of results to return. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of resource that may take multiple service requests to iterate over. + public Pageable ListByName(string filter, int? top = null, CancellationToken cancellationToken = default) + { + ResourceFilterCollection filters = new ResourceFilterCollection(VirtualNetworkData.ResourceType); + filters.SubstringFilter = filter; + return ResourceListOperations.ListAtContext(Parent as ResourceGroupOperations, filters, top, cancellationToken); + } + + /// + /// Filters the list of virtual nerwork for this resource group represented as generic resources. + /// + /// The filter used in this operation. + /// The number of results to return. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of resource that may take multiple service requests to iterate over. + public AsyncPageable ListByNameAsync(string filter, int? top = null, CancellationToken cancellationToken = default) + { + ResourceFilterCollection filters = new ResourceFilterCollection(VirtualNetworkData.ResourceType); + filters.SubstringFilter = filter; + return ResourceListOperations.ListAtContextAsync(Parent as ResourceGroupOperations, filters, top, cancellationToken); + } + + /// + /// Filters the list of virtual nerwork for this resource group. + /// Makes an additional network call to retrieve the full data model for each virtual nerwork. + /// + /// The filter used in this operation. + /// The number of results to return. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A collection of resource that may take multiple service requests to iterate over. + public Pageable ListByNameExpanded(string filter, int? top = null, CancellationToken cancellationToken = default) + { + var results = ListByName(filter, top, cancellationToken); + return new PhWrappingPageable(results, s => new VirtualNetworkOperations(s).Get().Value); + } + + /// + /// Filters the list of virtual nerwork for this resource group. + /// Makes an additional network call to retrieve the full data model for each virtual nerwork. + /// + /// The filter used in this operation. + /// The number of results to return. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An asyc collection of availability set that may take multiple service requests to iterate over. + public AsyncPageable ListByNameExpandedAsync(string filter, int? top = null, CancellationToken cancellationToken = default) + { + var results = ListByNameAsync(filter, top, cancellationToken); + return new PhWrappingAsyncPageable(results, s => new VirtualNetworkOperations(s).Get().Value); + } + + private Func Convertor() + { + return s => new VirtualNetwork(Parent, new VirtualNetworkData(s)); + } + + /// + public override ArmResponse Get(string virtualNetworkName) + { + return new PhArmResponse(Operations.Get(Id.ResourceGroup, virtualNetworkName), + Convertor()); + } + + /// + public override async Task> GetAsync(string virtualNetworkName, CancellationToken cancellationToken = default) + { + return new PhArmResponse(await Operations.GetAsync(Id.ResourceGroup, virtualNetworkName, null, cancellationToken), + Convertor()); + } + + } +} diff --git a/sdk/resourcemanager/Proto.Client/network/VirtualNetworkOperations.cs b/sdk/resourcemanager/Proto.Client/network/VirtualNetworkOperations.cs new file mode 100644 index 0000000000000..a1157d5864747 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/network/VirtualNetworkOperations.cs @@ -0,0 +1,322 @@ +using Azure; +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Network; +using Azure.ResourceManager.Network.Models; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Proto.Network +{ + /// + /// A class representing the operations that can be performed over a specific virtual nerwork. + /// + public class VirtualNetworkOperations : ResourceOperationsBase, ITaggableResource, IDeletableResource + { + /// + /// Initializes a new instance of the class. + /// + /// An instance of that has an id for a virtual nerwork. + internal VirtualNetworkOperations(GenericResourceOperations genericOperations) + : base(genericOperations) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The name of the virtual network to use. + internal VirtualNetworkOperations(ResourceGroupOperations resourceGroup, string vnetName) + : base(resourceGroup, $"{resourceGroup.Id}/providers/Microsoft.Network/virtualNetworks/{vnetName}") + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + protected VirtualNetworkOperations(ResourceOperationsBase options, ResourceIdentifier id) + : base(options, id) + { + } + + /// + /// Gets the resource type definition for a virtual nerwork. + /// + public static readonly ResourceType ResourceType = "Microsoft.Network/virtualNetworks"; + + /// + /// Gets the valid resource type definition for a virtual nerwork. + /// + protected override ResourceType ValidResourceType => ResourceType; + + private VirtualNetworksOperations Operations => new NetworkManagementClient( + Id.Subscription, + BaseUri, + Credential, + ClientOptions.Convert()).VirtualNetworks; + + /// + /// The operation to delete a virtual nerwork. + /// + /// A response with the operation for this resource. + public ArmResponse Delete() + { + return new ArmResponse(Operations.StartDelete(Id.ResourceGroup, Id.Name).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult()); + } + + /// + /// The operation to delete a virtual nerwork. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// A that on completion returns a response with the operation for this resource. + public async Task> DeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmResponse((await Operations.StartDeleteAsync(Id.ResourceGroup, Id.Name, cancellationToken)).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult()); + } + + /// + /// The operation to delete a virtual nerwork. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// An that allows polling for completion of the operation. + public ArmOperation StartDelete(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(Operations.StartDelete(Id.ResourceGroup, Id.Name, cancellationToken)); + } + + /// + /// The operation to delete a virtual nerwork. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> StartDeleteAsync(CancellationToken cancellationToken = default) + { + return new ArmVoidOperation(await Operations.StartDeleteAsync(Id.ResourceGroup, Id.Name, cancellationToken)); + } + + /// + public override ArmResponse Get() + { + return new PhArmResponse(Operations.Get(Id.ResourceGroup, Id.Name), + n => new VirtualNetwork(this, new VirtualNetworkData(n))); + } + + /// + public async override Task> GetAsync(CancellationToken cancellationToken = default) + { + return new PhArmResponse(await Operations.GetAsync(Id.ResourceGroup, Id.Name, null, cancellationToken), + n => new VirtualNetwork(this, new VirtualNetworkData(n))); + } + + /// + /// Adds a tag to a virtual network. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// + /// Details on long running operation object. + /// + /// An that allows polling for completion of the operation. + public ArmResponse AddTag(string key, string value) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmResponse(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new VirtualNetwork(this, new VirtualNetworkData(n))); + } + + /// + /// Adds a tag to a virtual network. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmResponse(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new VirtualNetwork(this, new VirtualNetworkData(n))); + } + + /// + /// Adds a tag to a virtual network. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// + /// Details on long running operation object. + /// + /// An that allows polling for completion of the operation. + public ArmOperation StartAddTag(string key, string value) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmOperation(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new VirtualNetwork(this, new VirtualNetworkData(n))); + } + + /// + /// Adds a tag to a virtual network. + /// If the tag already exists it will be modified. + /// + /// The key for the tag. + /// The value for the tag. + /// A token to allow the caller to cancel the call to the service. The default value is . + /// + /// Details on long running operation object. + /// + /// A that on completion returns an that allows polling for completion of the operation. + public async Task> StartAddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags[key] = value; + return new PhArmOperation(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new VirtualNetwork(this, new VirtualNetworkData(n))); + } + + /// + /// Gets a subnet in the virtual nerwork. + /// + /// The name of the subnet. + /// An instance of SubnetOperations. + public SubnetOperations GetSubnetOperations(string subnet) + { + return new SubnetOperations(this, subnet); + } + + /// + /// Gets a list of subnet in the virtual nerwork. + /// + /// An object representing collection of subnets and their operations over a virtual network. + public SubnetContainer GetSubnetContainer() + { + return new SubnetContainer(this); + } + + /// + public ArmResponse SetTags(IDictionary tags) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmResponse(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new VirtualNetwork(this, new VirtualNetworkData(n))); + } + + /// + public async Task> SetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmResponse(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new VirtualNetwork(this, new VirtualNetworkData(n))); + } + + /// + public ArmOperation StartSetTags(IDictionary tags) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmOperation(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new VirtualNetwork(this, new VirtualNetworkData(n))); + } + + /// + public async Task> StartSetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(tags); + return new PhArmOperation(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new VirtualNetwork(this, new VirtualNetworkData(n))); + } + + /// + public ArmResponse RemoveTag(string key) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmResponse(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new VirtualNetwork(this, new VirtualNetworkData(n))); + } + + /// + public async Task> RemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmResponse(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new VirtualNetwork(this, new VirtualNetworkData(n))); + } + + /// + public ArmOperation StartRemoveTag(string key) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmOperation(Operations.UpdateTags(Id.ResourceGroup, Id.Name, patchable), + n => new VirtualNetwork(this, new VirtualNetworkData(n))); + } + + /// + public async Task> StartRemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + var resource = GetResource(); + var patchable = new TagsObject(); + patchable.Tags.ReplaceWith(resource.Data.Tags); + patchable.Tags.Remove(key); + return new PhArmOperation(await Operations.UpdateTagsAsync(Id.ResourceGroup, Id.Name, patchable, cancellationToken), + n => new VirtualNetwork(this, new VirtualNetworkData(n))); + } + + /// + /// Lists all available geo-locations. + /// + /// A collection of location that may take multiple service requests to iterate over. + public IEnumerable ListAvailableLocations() + { + return ListAvailableLocations(ResourceType); + } + + /// + /// Lists all available geo-locations. + /// + /// A token to allow the caller to cancel the call to the service. The default value is . + /// An async collection of location that may take multiple service requests to iterate over. + /// The default subscription id is null. + public async Task> ListAvailableLocationsAsync(CancellationToken cancellationToken = default) + { + return await ListAvailableLocationsAsync(ResourceType, cancellationToken); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Common/ScenarioHelper.cs b/sdk/resourcemanager/Proto.Client/src/Common/ScenarioHelper.cs new file mode 100644 index 0000000000000..a440264bb3904 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Common/ScenarioHelper.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Proto.Client.Common +{ + internal class ScenarioHelper + { + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Program.cs b/sdk/resourcemanager/Proto.Client/src/Program.cs new file mode 100644 index 0000000000000..1e4f6ee5de7a0 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Program.cs @@ -0,0 +1,35 @@ +using Azure.ResourceManager.Core; +using System; + +namespace Proto.Client +{ + class Program + { + static void Main(string[] args) + { + Scenario scenario = null; + try + { + scenario = ScenarioFactory.GetScenario(Scenarios.CreateSingleVmExample); + scenario.Execute(); + } + finally + { + foreach (var rgId in Scenario.CleanUp) + { + ResourceIdentifier id = new ResourceIdentifier(rgId); + var rg = new AzureResourceManagerClient().GetSubscriptionOperations(id.Subscription).GetResourceGroupOperations(id.ResourceGroup); + Console.WriteLine($"--------Deleting {rg.Id.Name}--------"); + try + { + _ = rg.DeleteAsync(); + } + catch + { + //ignore exceptions in case the rg doesn't exist + } + } + } + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Proto.Client.csproj b/sdk/resourcemanager/Proto.Client/src/Proto.Client.csproj new file mode 100644 index 0000000000000..57df41d88b2fd --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Proto.Client.csproj @@ -0,0 +1,19 @@ + + + + Exe + netcoreapp3.1 + + + + DEBUG;TRACE + + + + + + + + + + diff --git a/sdk/resourcemanager/Proto.Client/src/Scenario.cs b/sdk/resourcemanager/Proto.Client/src/Scenario.cs new file mode 100644 index 0000000000000..a6929c4c622bf --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenario.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Proto.Client +{ + abstract class Scenario + { + public ScenarioContext Context { get; private set; } + + public readonly static HashSet CleanUp = new HashSet(); + + public abstract void Execute(); + + public Scenario() : this(new ScenarioContext()) { } + + public Scenario(ScenarioContext context) + { + Context = context; + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/ScenarioContext.cs b/sdk/resourcemanager/Proto.Client/src/ScenarioContext.cs new file mode 100644 index 0000000000000..966196ef6c2ad --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/ScenarioContext.cs @@ -0,0 +1,30 @@ +using Azure.ResourceManager.Core; +using System; + +namespace Proto.Client +{ + class ScenarioContext + { + public static readonly string AzureSdkSandboxId = "db1ab6f0-4769-4b27-930e-01e2ef9c123c"; + + public string Hostname => $"{Environment.UserName}"; + public string VmName => $"{Environment.UserName}"; + public string RgName { get; private set; } + public string NsgName => $"{Environment.UserName}-test-nsg"; + public string SubscriptionId { get; private set; } + public string Loc => LocationData.WestUS2; + public string SubnetName => $"{Environment.UserName}-subnet"; + + public string PrincipalId => "4c5ce728-7350-4ae5-bcf1-42e8e33b00fe"; + + public string RoleId => "acdd72a7-3385-48ef-bd42-f606fba81ae7"; + + public ScenarioContext() : this(AzureSdkSandboxId) { } + + public ScenarioContext(string subscriptionId) + { + RgName = $"{Environment.UserName}-{Environment.TickCount}-rg"; + SubscriptionId = subscriptionId; + } + } +} \ No newline at end of file diff --git a/sdk/resourcemanager/Proto.Client/src/ScenarioFactory.cs b/sdk/resourcemanager/Proto.Client/src/ScenarioFactory.cs new file mode 100644 index 0000000000000..fb0a13747bad3 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/ScenarioFactory.cs @@ -0,0 +1,58 @@ +using System; +using System.Linq; +using System.Reflection; + +namespace Proto.Client +{ + enum Scenarios + { + All, + GetVMTaskExamples, + CreateSingleVmExample, + CreateSingleVMCheckLocation, + ShutdownVmsByName, + StartStopVm, + StartFromVm, + SetTagsOnVm, + ShutdownVmsByTag, + CreateMultipleVms, + GenericEntityLoop, + ShutdownVmsByLINQ, + ShutdownVmsByNameAcrossResourceGroups, + //ShutdownVmsByNameAcrossSubscriptions, + ListByNameExpanded, + ClientOptionsOverride, + GetSubscription, + NullDataValues, + //RoleAssignment, + //DeleteGeneric, + //AddTagToGeneric, + CheckResourceExists, + GetFromOperations, + CreateSingleVmExampleAsync, + StartCreateSingleVmExampleAsync, + StartCreateSingleVmExample, + DefaultSubscription, + SubscriptionExists, + UseParentLocation, + GetByContainers, + GetByContainersAsync, + CheckResourceGroupOpsAsync + } + + class ScenarioFactory + { + public static Scenario GetScenario(Scenarios scenario) + { + switch(scenario) + { + default: + var type = Assembly.GetExecutingAssembly() + .GetTypes() + .Where(t => t.Name == scenario.ToString()) + .First(); + return Activator.CreateInstance(type) as Scenario; + } + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/AddTagToGeneric.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/AddTagToGeneric.cs new file mode 100644 index 0000000000000..3178f20698f8f --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/AddTagToGeneric.cs @@ -0,0 +1,30 @@ +using Azure.ResourceManager.Core; +using Proto.Compute; +using System; + +namespace Proto.Client +{ + class AddTagToGeneric : Scenario + { + public override void Execute() + { + var createVm = new CreateSingleVmExample(Context); + createVm.Execute(); + + var rgOp = new AzureResourceManagerClient().GetResourceGroupOperations(Context.SubscriptionId, Context.RgName); + foreach (var genericOp in rgOp.GetVirtualMachineContainer().ListByName(Context.VmName)) + { + Console.WriteLine($"Adding tag to {genericOp.Id}"); + genericOp.StartAddTag("tagKey", "tagVaue"); + } + + var vmOp = rgOp.GetVirtualMachineOperations(Context.VmName); + Console.WriteLine($"Getting {vmOp.Id}"); + var vm = vmOp.Get().Value; + + if(!vm.Data.Tags.ContainsKey("tagKey")) + throw new InvalidOperationException("Failed"); + + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/All.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/All.cs new file mode 100644 index 0000000000000..c7ae7aeaa86af --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/All.cs @@ -0,0 +1,45 @@ +using Azure.ResourceManager.Core; +using System; +using System.Linq; +using System.Threading.Tasks; + +namespace Proto.Client +{ + class All : Scenario + { + public override void Execute() + { + var list = Enum.GetValues(typeof(Scenarios)).Cast().ToList(); + try + { + foreach(var scenario in list) + { + if (scenario != Scenarios.All) + { + Console.WriteLine($"########## Starting Scenario {scenario} ##########"); + var executable = ScenarioFactory.GetScenario(scenario); + executable.Execute(); + Console.WriteLine($"########## Finished Scenario {scenario} ##########"); + } + } + } + finally + { + foreach (var rgId in CleanUp) + { + ResourceIdentifier id = new ResourceIdentifier(rgId); + var rg = new AzureResourceManagerClient().GetResourceGroupOperations(rgId); + Console.WriteLine($"--------Deleting {rg.Id.Name}--------"); + try + { + _ = rg.DeleteAsync(); + } + catch + { + //ignore exceptions in case rg doesn't exist + } + } + } + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/CheckResourceExists.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/CheckResourceExists.cs new file mode 100644 index 0000000000000..c5988fe7c6eb5 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/CheckResourceExists.cs @@ -0,0 +1,55 @@ +using Azure.ResourceManager.Core; +using Proto.Compute; +using System; + +namespace Proto.Client +{ + class CheckResourceExists : Scenario + { + public override void Execute() + { + var client = new AzureResourceManagerClient(); + var subOp = client.DefaultSubscription; + var rgContainer = subOp.GetResourceGroupContainer(); + + Console.WriteLine($"Making sure {Context.RgName} doesn't exist yet."); + if (rgContainer.DoesExist(Context.RgName)) + throw new Exception($"The resource group {Context.RgName} should not have existed."); + + Console.WriteLine($"Creating {Context.RgName}"); + _ = rgContainer.Construct(LocationData.Default).CreateOrUpdate(Context.RgName).Value; + + Console.WriteLine($"Making sure {Context.RgName} exists now."); + if (!rgContainer.DoesExist(Context.RgName)) + throw new Exception($"The resource group {Context.RgName} should have existed."); + + Console.WriteLine($"Using try get value to retrieve {Context.RgName}"); + ArmResponse rgOutput; + if(!rgContainer.TryGetValue(Context.RgName, out rgOutput)) + throw new Exception($"The resource group {Context.RgName} should have existed."); + + var rg = rgOutput.Value; + + var asetContainer = rg.GetAvailabilitySetContainer(); + var asetName = Context.VmName + "_aSet"; + + Console.WriteLine($"Making sure {asetName} doesn't exist yet."); + if (asetContainer.DoesExist(asetName)) + throw new Exception($"The availability set {asetName} should not have existed."); + + Console.WriteLine($"Creating {asetName}"); + var aset = asetContainer.Construct("Aligned").CreateOrUpdate(asetName).Value; + + Console.WriteLine($"Making sure {asetName} exists now."); + if (!asetContainer.DoesExist(asetName)) + throw new Exception($"The availability set {asetName} should have existed."); + + Console.WriteLine("Using try get value to retrieve the rg"); + ArmResponse asetOutput; + if (!asetContainer.TryGetValue(asetName, out asetOutput)) + throw new Exception($"The availability set {asetName} should have existed."); + + + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/CheckResourceGroupOpsAsync.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/CheckResourceGroupOpsAsync.cs new file mode 100644 index 0000000000000..b0263b2c00e16 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/CheckResourceGroupOpsAsync.cs @@ -0,0 +1,144 @@ +using Azure.ResourceManager.Core; +using Proto.Compute; +using System; +using System.Threading.Tasks; + +namespace Proto.Client +{ + class CheckResourceGroupOpsAsync : Scenario + { + public CheckResourceGroupOpsAsync() : base() { } + + public CheckResourceGroupOpsAsync(ScenarioContext context) : base(context) { } + + public override void Execute() + { + ExecuteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + } + + private async System.Threading.Tasks.Task ExecuteAsync() + { + var client = new AzureResourceManagerClient(); + var subscription = client.GetSubscriptionOperations(Context.SubscriptionId); + + // Create Resource Group + Console.WriteLine($"--------Start create group {Context.RgName}--------"); + var resourceGroup = subscription.GetResourceGroupContainer().Construct(Context.Loc).CreateOrUpdate(Context.RgName).Value; + CleanUp.Add(resourceGroup.Id); + var rgOps = subscription.GetResourceGroupOperations(Context.RgName); + + ShouldThrow( + () => rgOps.AddTag("", ""), + "AddTag with empty string didn't throw", + "AddTag"); + + await ShouldThrowAsync( + async () => await rgOps.AddTagAsync(null, null), + "AddTagAsync with null string didn't throw", + "AddTagAsync"); + + ShouldThrow( + () => rgOps.StartAddTag("", null), + "StartAddTag with empty string didn't throw", + "StartAddTag"); + + await ShouldThrowAsync( + async () => await rgOps.StartAddTagAsync(" ", "test"), + "StartAddTagAsync with whitespaces only string didn't throw", + "StartAddTagAsync"); + + // Create AvailabilitySet + Console.WriteLine("--------Create AvailabilitySet async--------"); + var aset = (await (await resourceGroup.GetAvailabilitySetContainer().Construct("Aligned").StartCreateOrUpdateAsync(Context.VmName + "_aSet")).WaitForCompletionAsync()).Value; + var data = aset.Get().Value.Data; + + ShouldThrow( + () => rgOps.CreateResource("", data), + "CreateResource with empty string didn't throw", + "CreateResource"); + + await ShouldThrowAsync( + async () => await rgOps.CreateResourceAsync(" ", data), + "CreateResourceAsync with whitespaces string didn't throw", + "CreateResourceAsync"); + + ShouldThrow( + () => rgOps.SetTags(null), + "SetTags with null didn't throw", + "SetTags"); + + await ShouldThrowAsync( + async () => await rgOps.SetTagsAsync(null), + "SetTagsAsync with null didn't throw", + "SetTagsAsync"); + + ShouldThrow( + () => rgOps.StartSetTags(null), + "StartSetTags with null didn't throw", + "StartSetTags"); + + await ShouldThrowAsync( + async () => await rgOps.StartSetTagsAsync(null), + "StartSetTagsAsync with null didn't throw", + "StartSetTagsAsync"); + + ShouldThrow( + () => rgOps.RemoveTag(""), + "RemoveTag with empty string didn't throw", + "RemoveTag"); + + await ShouldThrowAsync( + async () => await rgOps.RemoveTagAsync(null), + "RemoveTagAsync with null didn't throw", + "RemoveTagAsync"); + + ShouldThrow( + () => rgOps.StartRemoveTag(" "), + "StartRemoveTag with whitespace string didn't throw", + "StartRemoveTag"); + + await ShouldThrowAsync( + async () => await rgOps.StartRemoveTagAsync(null), + "StartRemoveTagAsync with null didn't throw", + "StartRemoveTagAsync"); + + ShouldThrow( + () => rgOps.CreateResource("tester", null), + "CreateResource model exception not thrown", + "CreateResource"); + + await ShouldThrowAsync( + async () => await rgOps.CreateResourceAsync("tester", null), + "CreateResourceAsync model exception not thrown", + "CreateResourceAsync"); + + Console.WriteLine("--------Done--------"); + } + + private static void ShouldThrow(Action lambda, string failMessage, string method) + { + try + { + lambda(); + throw new Exception(failMessage); + } + catch (Exception e) when (e.GetType() == typeof(T)) + { + Console.WriteLine($"{method} Exception was thrown as expected."); + } + } + + private static async Task ShouldThrowAsync(Func lambda, string failMessage, string method) + { + try + { + await lambda(); + throw new Exception(failMessage); + } + catch (Exception e) when (e.GetType() == typeof(T)) + { + Console.WriteLine($"{method} Exception was thrown as expected."); + } + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/ClientOverrides.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/ClientOverrides.cs new file mode 100644 index 0000000000000..44e31dc3c1090 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/ClientOverrides.cs @@ -0,0 +1,62 @@ +using Azure.ResourceManager.Core; +using System; +using Azure.Core; +using Azure.Core.Pipeline; +using System.Threading; +using System.Diagnostics; + +namespace Proto.Client +{ + class ClientOptionsOverride : Scenario + { + public override void Execute() + { + + AzureResourceManagerClientOptions options1 = new AzureResourceManagerClientOptions(); + AzureResourceManagerClientOptions options2 = new AzureResourceManagerClientOptions(); + var dummyPolicy1 = new dummyPolicy(); + var dummyPolicy2 = new dummyPolicy2(); + options1.AddPolicy(dummyPolicy1, HttpPipelinePosition.PerCall); + options2.AddPolicy(dummyPolicy2, HttpPipelinePosition.PerCall); + var client1 = new AzureResourceManagerClient(options1); + var client2 = new AzureResourceManagerClient(options2); + + Console.WriteLine("-----Client 1-----"); + foreach (var sub in client1.GetSubscriptionContainer().List()) + { + Console.WriteLine($"Found {sub.Data.DisplayName}"); + } + + Console.WriteLine("-----Client 2-----"); + foreach (var sub in client2.GetSubscriptionContainer().List()) + { + Console.WriteLine($"Found {sub.Data.DisplayName}"); + } + + Debug.Assert(dummyPolicy1.numMsgGot * 2 == dummyPolicy2.numMsgGot); + Console.WriteLine("\nPASSED\n"); + + } + + private class dummyPolicy : HttpPipelineSynchronousPolicy + { + public int numMsgGot = 0; + + public override void OnReceivedResponse(HttpMessage message) + { + Interlocked.Increment(ref numMsgGot); + } + } + + private class dummyPolicy2 : HttpPipelineSynchronousPolicy + { + public int numMsgGot = 0; + + public override void OnReceivedResponse(HttpMessage message) + { + Interlocked.Add(ref numMsgGot, 2); + } + } + + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/CreateMultipleVms.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/CreateMultipleVms.cs new file mode 100644 index 0000000000000..b3eed9cac93e2 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/CreateMultipleVms.cs @@ -0,0 +1,70 @@ +using Proto.Compute; +using Azure.ResourceManager.Core; +using Proto.Network; +using System; +using System.Collections.Generic; + +namespace Proto.Client +{ + class CreateMultipleVms : Scenario + { + public CreateMultipleVms() : base() { } + + public CreateMultipleVms(ScenarioContext context) : base(context) { } + + public override void Execute() + { + var client = new AzureResourceManagerClient(); + var subscription = client.GetSubscriptionOperations(Context.SubscriptionId); + + // Create Resource Group + Console.WriteLine($"--------Start create group {Context.RgName}--------"); + var resourceGroup = subscription.GetResourceGroupContainer().Construct(Context.Loc).CreateOrUpdate(Context.RgName).Value; + CleanUp.Add(resourceGroup.Id); + + // Create AvailabilitySet + Console.WriteLine("--------Start create AvailabilitySet--------"); + var aset = resourceGroup.GetAvailabilitySetContainer().Construct("Aligned").CreateOrUpdate(Context.VmName + "_aSet").Value; + + // Create VNet + Console.WriteLine("--------Start create VNet--------"); + string vnetName = Context.VmName + "_vnet"; + var vnet = resourceGroup.GetVirtualNetworkContainer().Construct("10.0.0.0/16").CreateOrUpdate(vnetName).Value; + + //create subnet + Console.WriteLine("--------Start create Subnet--------"); + var subnet = vnet.GetSubnetContainer().Construct("10.0.0.0/24").CreateOrUpdate(Context.SubnetName).Value; + + //create network security group + Console.WriteLine("--------Start create NetworkSecurityGroup--------"); + _ = resourceGroup.GetNetworkSecurityGroupContainer().Construct(80).CreateOrUpdate(Context.NsgName).Value; + + CreateVms(resourceGroup, aset, subnet); + + } + + private void CreateVms(ResourceGroup resourceGroup, AvailabilitySet aset, SubnetOperations subnet) + { + List> operations = new List>(); + for (int i = 0; i < 10; i++) + { + // Create Network Interface + Console.WriteLine("--------Start create Network Interface--------"); + var nic = resourceGroup.GetNetworkInterfaceContainer().Construct(subnet.Id).CreateOrUpdate($"{Context.VmName}_{i}_nic").Value; + + // Create VM + string num = i % 2 == 0 ? "-e" : "-o"; + string name = $"{Context.VmName}{i}{num}"; + Console.WriteLine("--------Start create VM {0}--------", i); + var vmOp = resourceGroup.GetVirtualMachineContainer().Construct(Context.Hostname, "admin-user", "!@#$%asdfA", nic.Id, aset.Id).StartCreateOrUpdate(name); + operations.Add(vmOp); + } + + foreach (var operation in operations) + { + var vm = operation.WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult().Value; + Console.WriteLine($"--------Finished creating VM {vm.Id.Name}"); + } + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/CreateSingleVMCheckLocation.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/CreateSingleVMCheckLocation.cs new file mode 100644 index 0000000000000..0308cbbbf9c7b --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/CreateSingleVMCheckLocation.cs @@ -0,0 +1,90 @@ +using Azure.ResourceManager.Core; +using Proto.Compute; +using Proto.Network; +using System; +using System.Linq; + +namespace Proto.Client +{ + class CreateSingleVMCheckLocation : Scenario + { + public CreateSingleVMCheckLocation() : base() { } + + public CreateSingleVMCheckLocation(ScenarioContext context) : base(context) { } + + public override void Execute() + { + var client = new AzureResourceManagerClient(); + var subscription = client.GetSubscriptionOperations(Context.SubscriptionId); + + // Create Resource Group + Console.WriteLine($"--------Start create group {Context.RgName}--------"); + var resourceGroup = subscription.GetResourceGroupContainer().Construct(Context.Loc).CreateOrUpdate(Context.RgName).Value; + CleanUp.Add(resourceGroup.Id); + Console.WriteLine("\nResource Group List Available Locations: "); + var loc = resourceGroup.ListAvailableLocations(); + foreach(var l in loc) + { + Console.WriteLine(l.DisplayName); + } + + // Create AvailabilitySet + Console.WriteLine("--------Start create AvailabilitySet--------"); + var aset = resourceGroup.GetAvailabilitySetContainer().Construct("Aligned").CreateOrUpdate(Context.VmName + "_aSet").Value; + Console.WriteLine("\nAvailability Set List Available Locations: "); + loc = aset.ListAvailableLocations(); + foreach (var l in loc) + { + Console.WriteLine(l.DisplayName); + } + + // Create VNet + Console.WriteLine("--------Start create VNet--------"); + string vnetName = Context.VmName + "_vnet"; + var vnet = resourceGroup.GetVirtualNetworkContainer().Construct("10.0.0.0/16").CreateOrUpdate(vnetName).Value; + Console.WriteLine("\nVirtual Network List Available Locations: "); + loc = vnet.ListAvailableLocations(); + foreach (var l in loc) + { + Console.WriteLine(l.DisplayName); + } + + //create subnet + Console.WriteLine("--------Start create Subnet--------"); + var subnet = vnet.GetSubnetContainer().Construct("10.0.0.0/24").CreateOrUpdate(Context.SubnetName).Value; + + //create network security group + Console.WriteLine("--------Start create NetworkSecurityGroup--------"); + var nsg = resourceGroup.GetNetworkSecurityGroupContainer().Construct(80).CreateOrUpdate(Context.NsgName).Value; + Console.WriteLine("\nNetwork Security Group List Available Locations: "); + loc = nsg.ListAvailableLocations(); + foreach (var l in loc) + { + Console.WriteLine(l.DisplayName); + } + + // Create Network Interface + Console.WriteLine("--------Start create Network Interface--------"); + var nic = resourceGroup.GetNetworkInterfaceContainer().Construct(subnet.Id).CreateOrUpdate($"{Context.VmName}_nic").Value; + Console.WriteLine("\nNetwork Interface Container List Available Locations: "); + loc = nic.ListAvailableLocations(); + foreach (var l in loc) + { + Console.WriteLine(l.DisplayName); + } + + // Create VM + Console.WriteLine("--------Start create VM--------"); + var vm = resourceGroup.GetVirtualMachineContainer().Construct(Context.Hostname, "admin-user", "!@#$%asdfA", nic.Id, aset.Id).CreateOrUpdate(Context.VmName).Value; + Console.WriteLine("\nVirtual Machine List Available Locations: "); + loc = vm.ListAvailableLocations(); + foreach (var l in loc) + { + Console.WriteLine(l.DisplayName); + } + + Console.WriteLine("VM ID: " + vm.Id); + Console.WriteLine("--------Done create VM--------"); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/CreateSingleVmExample.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/CreateSingleVmExample.cs new file mode 100644 index 0000000000000..7ae8ff1d44db9 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/CreateSingleVmExample.cs @@ -0,0 +1,54 @@ +using Azure.ResourceManager.Core; +using Proto.Compute; +using Proto.Network; +using System; + +namespace Proto.Client +{ + class CreateSingleVmExample : Scenario + { + public CreateSingleVmExample() : base() { } + + public CreateSingleVmExample(ScenarioContext context) : base(context) { } + + public override void Execute() + { + var client = new AzureResourceManagerClient(); + var subscription = client.GetSubscriptionOperations(Context.SubscriptionId); + + // Create Resource Group + Console.WriteLine($"--------Start create group {Context.RgName}--------"); + var resourceGroup = subscription.GetResourceGroupContainer().Construct(Context.Loc).CreateOrUpdate(Context.RgName).Value; + CleanUp.Add(resourceGroup.Id); + + // Create AvailabilitySet + Console.WriteLine("--------Start create AvailabilitySet--------"); + var aset = resourceGroup.GetAvailabilitySetContainer().Construct("Aligned").CreateOrUpdate(Context.VmName + "_aSet").Value; + + // Create VNet + Console.WriteLine("--------Start create VNet--------"); + string vnetName = Context.VmName + "_vnet"; + var vnet = resourceGroup.GetVirtualNetworkContainer().Construct("10.0.0.0/16").CreateOrUpdate(vnetName).Value; + + //create subnet + Console.WriteLine("--------Start create Subnet async--------"); + var subnet = vnet.GetSubnetContainer().Construct("10.0.0.0/24").CreateOrUpdateAsync(Context.SubnetName).ConfigureAwait(false).GetAwaiter().GetResult().Value; + + //create network security group + Console.WriteLine("--------Start create NetworkSecurityGroup--------"); + _ = resourceGroup.GetNetworkSecurityGroupContainer().Construct(80).CreateOrUpdate(Context.NsgName).Value; + + // Create Network Interface + Console.WriteLine("--------Start create Network Interface--------"); + var nic = resourceGroup.GetNetworkInterfaceContainer().Construct(subnet.Id).CreateOrUpdate($"{Context.VmName}_nic").Value; + + // Create VM + Console.WriteLine("--------Start create VM--------"); + var vm = resourceGroup.GetVirtualMachineContainer().Construct(Context.Hostname, "admin-user", "!@#$%asdfA", nic.Id, aset.Id).CreateOrUpdate(Context.VmName).Value; + + Console.WriteLine("VM ID: " + vm.Id); + Console.WriteLine("--------Done create VM--------"); + + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/CreateSingleVmExampleAsync.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/CreateSingleVmExampleAsync.cs new file mode 100644 index 0000000000000..52218cbec5b69 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/CreateSingleVmExampleAsync.cs @@ -0,0 +1,58 @@ +using Azure.ResourceManager.Core; +using Proto.Compute; +using Proto.Network; +using System; + +namespace Proto.Client +{ + class CreateSingleVmExampleAsync : Scenario + { + public CreateSingleVmExampleAsync() : base() { } + + public CreateSingleVmExampleAsync(ScenarioContext context) : base(context) { } + + public override void Execute() + { + ExcuteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + } + + private async System.Threading.Tasks.Task ExcuteAsync() + { + var client = new AzureResourceManagerClient(); + var subscription = client.GetSubscriptionOperations(Context.SubscriptionId); + + // Create Resource Group + Console.WriteLine($"--------Start create group async {Context.RgName}--------"); + var resourceGroup = (await subscription.GetResourceGroupContainer().Construct(Context.Loc).CreateOrUpdateAsync(Context.RgName)).Value; + CleanUp.Add(resourceGroup.Id); + + // Create AvailabilitySet + Console.WriteLine("--------Start create AvailabilitySet async--------"); + var aset = (await resourceGroup.GetAvailabilitySetContainer().Construct("Aligned").CreateOrUpdateAsync(Context.VmName + "_aSet")).Value; + + // Create VNet + Console.WriteLine("--------Start create VNet async--------"); + string vnetName = Context.VmName + "_vnet"; + var vnet = (await resourceGroup.GetVirtualNetworkContainer().Construct("10.0.0.0/16").CreateOrUpdateAsync(vnetName)).Value; + + //create subnet + Console.WriteLine("--------Start create Subnet async--------"); + var subnet = (await vnet.GetSubnetContainer().Construct("10.0.0.0/24").CreateOrUpdateAsync(Context.SubnetName)).Value; + + //create network security group + Console.WriteLine("--------Start create NetworkSecurityGroup async--------"); + _ = (await resourceGroup.GetNetworkSecurityGroupContainer().Construct(80).CreateOrUpdateAsync(Context.NsgName)).Value; + + // Create Network Interface + Console.WriteLine("--------Start create Network Interface async--------"); + var nic = (await resourceGroup.GetNetworkInterfaceContainer().Construct(subnet.Id).CreateOrUpdateAsync($"{Context.VmName}_nic")).Value; + + // Create VM + Console.WriteLine("--------Start create VM async--------"); + var vm = (await resourceGroup.GetVirtualMachineContainer().Construct(Context.Hostname, "admin-user", "!@#$%asdfA", nic.Id, aset.Id).CreateOrUpdateAsync(Context.VmName)).Value; + + Console.WriteLine("VM ID: " + vm.Id); + Console.WriteLine("--------Done create VM--------"); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/DefaultSubscription.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/DefaultSubscription.cs new file mode 100644 index 0000000000000..b2a3692a0c416 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/DefaultSubscription.cs @@ -0,0 +1,30 @@ +using Azure.Identity; +using Azure.ResourceManager.Core; +using System; + +namespace Proto.Client +{ + class DefaultSubscription : Scenario + { + public override void Execute() + { + var client = new AzureResourceManagerClient(Context.SubscriptionId, new DefaultAzureCredential()); + + var sub = client.DefaultSubscription; + + if (sub.Data.SubscriptionGuid != Context.SubscriptionId) + throw new Exception($"Didn't get back expected subscription. Got {sub.Data.SubscriptionGuid} expected {Context.SubscriptionId}"); + + Console.WriteLine("Found correct subscription"); + + client = new AzureResourceManagerClient(); + + sub = client.DefaultSubscription; + + if (sub.Data.SubscriptionGuid != Context.SubscriptionId) + throw new Exception($"Didn't get back expected subscription. Got {sub.Data.SubscriptionGuid} expected {Context.SubscriptionId}"); + + Console.WriteLine("Found correct subscription"); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/DeleteGeneric.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/DeleteGeneric.cs new file mode 100644 index 0000000000000..12ca505e5a36d --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/DeleteGeneric.cs @@ -0,0 +1,37 @@ +using Azure; +using Azure.ResourceManager.Core; +using Proto.Compute; +using System; + +namespace Proto.Client +{ + class DeleteGeneric : Scenario + { + public override void Execute() + { + var createVm = new CreateSingleVmExample(Context); + createVm.Execute(); + + var rgOp = new AzureResourceManagerClient().GetResourceGroupOperations(Context.SubscriptionId, Context.RgName); + foreach(var genericOp in rgOp.GetVirtualMachineContainer().ListByName(Context.VmName)) + { + Console.WriteLine($"Deleting {genericOp.Id}"); + genericOp.Delete(); + } + + try + { + var vmOp = rgOp.GetVirtualMachineOperations(Context.VmName); + Console.WriteLine($"Trying to get {vmOp.Id}"); + var response = vmOp.Get(); + } + catch(RequestFailedException e) when (e.Status == 404) + { + Console.WriteLine("Got 404 returned as expected"); + + } + + throw new InvalidOperationException("Failed"); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/GenericEntityLoop.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/GenericEntityLoop.cs new file mode 100644 index 0000000000000..1676cde944b10 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/GenericEntityLoop.cs @@ -0,0 +1,23 @@ +using Proto.Compute; +using Azure.ResourceManager.Core; +using System; + +namespace Proto.Client +{ + class GenericEntityLoop : Scenario + { + public override void Execute() + { + var createVm = new CreateSingleVmExample(Context); + createVm.Execute(); + + var rgOp = new AzureResourceManagerClient().GetResourceGroupOperations(Context.SubscriptionId, Context.RgName); + foreach(var entity in rgOp.GetVirtualMachineContainer().List()) + { + Console.WriteLine($"{entity.Id.Name}"); + entity.StartAddTag("name", "Value"); + } + + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/GetByContainerAsync.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/GetByContainerAsync.cs new file mode 100644 index 0000000000000..13c50526d4e50 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/GetByContainerAsync.cs @@ -0,0 +1,45 @@ +using Azure.ResourceManager.Core; +using Proto.Compute; +using Proto.Network; +using System; +using System.Diagnostics; +using System.Threading.Tasks; + +namespace Proto.Client +{ + class GetByContainersAsync: Scenario + { + public override void Execute() + { + ExecuteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + } + private async Task ExecuteAsync() + { + var createMultipleVms = new CreateMultipleVms(Context); + createMultipleVms.Execute(); + + var sub = new AzureResourceManagerClient().GetSubscriptionOperations(Context.SubscriptionId); + var rg = sub.GetResourceGroupOperations(Context.RgName); + var virtualMachineContainer = rg.GetVirtualMachineContainer(); + await foreach (var response in virtualMachineContainer.ListAsync()) + { + var virtualMachine = await virtualMachineContainer.GetAsync(response.Data.Id.Name); + Debug.Assert(virtualMachine.Value.Data.Name.Equals(response.Data.Id.Name)); + } + var virtualNetworkContainer = rg.GetVirtualNetworkContainer(); + await foreach (var response in virtualNetworkContainer.ListAsync()) + { + var virtualNetwork = await virtualNetworkContainer.GetAsync(response.Data.Id.Name); + Debug.Assert(virtualNetwork.Value.Data.Name.Equals(response.Data.Id.Name)); + await foreach (var subnetResponse in response.GetSubnetContainer().ListAsync()) + { + var actualSubnet = await subnetResponse.GetAsync(); + var subnets = await response.GetSubnetContainer().GetAsync(actualSubnet.Value.Data.Name); + Debug.Assert(subnets.Value.Data.Name.Equals(actualSubnet.Value.Data.Name)); + } + } + Console.WriteLine("\nDone all asserts passed ..."); + + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/GetByContainers.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/GetByContainers.cs new file mode 100644 index 0000000000000..6358e890ab3da --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/GetByContainers.cs @@ -0,0 +1,40 @@ +using Azure.ResourceManager.Core; +using Proto.Compute; +using Proto.Network; +using System; +using System.Diagnostics; + +namespace Proto.Client +{ + class GetByContainers: Scenario + { + public override void Execute() + { + var createMultipleVms = new CreateMultipleVms(Context); + createMultipleVms.Execute(); + + var sub = new AzureResourceManagerClient().GetSubscriptionOperations(Context.SubscriptionId); + var rg = sub.GetResourceGroupOperations(Context.RgName); + var virtualMachineContainer = rg.GetVirtualMachineContainer(); + foreach (var response in virtualMachineContainer.List()) + { + var virtualMachine = virtualMachineContainer.Get(response.Data.Id.Name); + Debug.Assert(virtualMachine.Value.Data.Name.Equals(response.Data.Id.Name)); + } + var virtualNetworkContainer = rg.GetVirtualNetworkContainer(); + foreach (var response in virtualNetworkContainer.List()) + { + var virtualNetwork = virtualNetworkContainer.Get(response.Data.Id.Name); + Debug.Assert(virtualNetwork.Value.Data.Name.Equals(response.Data.Id.Name)); + foreach (var subnetResponse in response.GetSubnetContainer().List()) + { + var actualSubnet = subnetResponse.Get(); + var subnets = response.GetSubnetContainer().Get(actualSubnet.Value.Data.Name); + Debug.Assert(subnets.Value.Data.Name.Equals(actualSubnet.Value.Data.Name)); + } + } + Console.WriteLine("\nDone all asserts passed ..."); + + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/GetFromOperations.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/GetFromOperations.cs new file mode 100644 index 0000000000000..a8b5cbaf027c0 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/GetFromOperations.cs @@ -0,0 +1,26 @@ +using Azure.ResourceManager.Core; +using Proto.Compute; +using Proto.Network; + +namespace Proto.Client +{ + class GetFromOperations : Scenario + { + public override void Execute() + { + var createVm = new CreateSingleVmExample(Context); + createVm.Execute(); + + var client = new AzureResourceManagerClient(); + var subscription = client.GetSubscriptionOperations(Context.SubscriptionId); + + var resourceGroup = subscription.GetResourceGroupOperations(Context.RgName).Get().Value; + _ = resourceGroup.GetAvailabilitySetOperations(Context.VmName + "_aSet").Get().Value; + var vnet = resourceGroup.GetVirtualNetworkOperations(Context.VmName + "_vnet").Get().Value; + _ = vnet.GetSubnetOperations(Context.SubnetName).Get().Value; + _ = resourceGroup.GetNetworkSecurityGroupOperations(Context.NsgName).Get().Value; + _ = resourceGroup.GetNetworkInterfaceOperations($"{Context.VmName}_nic").Get().Value; + _ = resourceGroup.GetVirtualMachineOperations(Context.VmName).Get().Value; + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/GetSubscription.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/GetSubscription.cs new file mode 100644 index 0000000000000..a60e07d9dac77 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/GetSubscription.cs @@ -0,0 +1,20 @@ +using Azure.ResourceManager.Core; +using System; +using System.Diagnostics; + +namespace Proto.Client +{ + class GetSubscription : Scenario + { + public override void Execute() + { + var sandboxId = "db1ab6f0-4769-4b27-930e-01e2ef9c123c"; + var expectDisplayName = "Azure SDK sandbox"; + var subOp = new AzureResourceManagerClient().GetSubscriptionOperations(sandboxId); + var result = subOp.Get(); + Debug.Assert(expectDisplayName == result.Value.Data.DisplayName); + Console.WriteLine("Passed, got " + result.Value.Data.DisplayName); + + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/GetVMTaskExamples.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/GetVMTaskExamples.cs new file mode 100644 index 0000000000000..925854a92448a --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/GetVMTaskExamples.cs @@ -0,0 +1,54 @@ +using Azure.ResourceManager.Core; +using Azure.ResourceManager.Network; +using Proto.Compute; +using Proto.Network; +using System; +using System.Linq; + +namespace Proto.Client +{ + class GetVMTaskExamples : Scenario + { + public GetVMTaskExamples() : base() { } + + public GetVMTaskExamples(ScenarioContext context) : base(context) { } + + public override void Execute() + { + var createVm = new CreateSingleVmExample(Context); + createVm.Execute(); + + var client = new AzureResourceManagerClient(); + var subscription = client.GetSubscriptionOperations(Context.SubscriptionId); + var resourceGroup = subscription.GetResourceGroupOperations(Context.RgName); + var vmId = resourceGroup.GetVirtualMachineOperations(Context.VmName).Id; + var vnId = resourceGroup.GetVirtualNetworkOperations(Context.VmName + "_vnet").Id; + var subnetId = resourceGroup.GetVirtualNetworkOperations(Context.VmName + "_vnet").GetSubnetOperations(Context.SubnetName).Id; + var asId = resourceGroup.GetAvailabilitySetOperations(Context.VmName + "_aSet").Id; + var nsgId = resourceGroup.GetNetworkSecurityGroupOperations(Context.NsgName).Id; + var niId = resourceGroup.GetNetworkInterfaceOperations(Context.VmName + "_nic").Id; + + var vmOps = client.GetVirtualMachineOperations(vmId); + Console.WriteLine("\nclient.GetVirtualMachineOperations(vmResourceId)"); + vmOps.PowerOff(); + Console.WriteLine("Option 1 vm is " + vmOps.Get().Value.Data.InstanceView.Statuses.Last().Code); + vmOps.PowerOn(); + Console.WriteLine("Option 1 vm is " + vmOps.Get().Value.Data.InstanceView.Statuses.Last().Code); + + var subnetOps = client.GetSubnetOperations(subnetId); + Console.WriteLine("Option 1 subnet is " + subnetOps.Id); + + var vnOps = client.GetVirtualNetworkOperations(vnId); + var nsgOps = client.GetNetworkSecurityGroupOperations(nsgId); + var niOps = client.GetNetworkInterfaceOperations(niId); + var asOps = client.GetAvailabilitySetOperations(asId); + + Console.WriteLine(vnOps.Id); + Console.WriteLine(nsgOps.Id); + Console.WriteLine(niOps.Id); + Console.WriteLine(asOps.Id); + + Console.WriteLine("Demo complete"); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/ListByNameExpanded.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/ListByNameExpanded.cs new file mode 100644 index 0000000000000..1b4db26be8cd8 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/ListByNameExpanded.cs @@ -0,0 +1,133 @@ +using Proto.Compute; +using Azure.ResourceManager.Core; +using Proto.Network; +using System; +using System.Threading.Tasks; + +namespace Proto.Client +{ + class ListByNameExpanded : Scenario + { + public override void Execute() + { + var createMultipleVms = new CreateMultipleVms(Context); + createMultipleVms.Execute(); + + var rg = new AzureResourceManagerClient().GetResourceGroupOperations(Context.SubscriptionId, Context.RgName).Get().Value; + foreach (var availabilitySet in rg.GetAvailabilitySetContainer().ListByName(Environment.UserName)) + { + Console.WriteLine($"--------AvailabilitySet operation id--------: {availabilitySet.Id}"); + } + + foreach (var availabilitySet in rg.GetAvailabilitySetContainer().ListByNameExpanded(Environment.UserName)) + { + Console.WriteLine($"--------AvailabilitySet id--------: {availabilitySet.Data.Id}"); + } + + foreach (var vm in rg.GetVirtualMachineContainer().ListByName(Environment.UserName)) + { + Console.WriteLine($"--------VM operation id--------: {vm.Id}"); + } + + foreach (var vm in rg.GetVirtualMachineContainer().ListByNameExpanded(Environment.UserName)) + { + Console.WriteLine($"--------VM id--------: {vm.Data.Id}"); + } + + foreach (var networkInterface in rg.GetNetworkInterfaceContainer().ListByName(Environment.UserName)) + { + Console.WriteLine($"--------NetworkInterface operation id--------: {networkInterface.Id}"); + } + + foreach (var networkInterface in rg.GetNetworkInterfaceContainer().ListByNameExpanded(Environment.UserName)) + { + Console.WriteLine($"--------NetworkInterface id--------: {networkInterface.Data.Id}"); + } + + foreach (var networkSecurityGroup in rg.GetNetworkSecurityGroupContainer().ListByName(Environment.UserName)) + { + Console.WriteLine($"--------NetworkSecurityGroup operation id--------: {networkSecurityGroup.Id}"); + } + + foreach (var networkSecurityGroup in rg.GetNetworkSecurityGroupContainer().ListByNameExpanded(Environment.UserName)) + { + Console.WriteLine($"--------NetworkSecurityGroup id--------: {networkSecurityGroup.Data.Id}"); + } + + foreach (var publicIpAddress in rg.GetNetworkSecurityGroupContainer().ListByNameExpanded(Environment.UserName)) + { + Console.WriteLine($"--------PublicIpAddress id--------: {publicIpAddress.Data.Id}"); + } + + foreach (var VNet in rg.GetVirtualNetworkContainer().ListByName(Environment.UserName)) + { + Console.WriteLine($"--------VNet operation id--------: {VNet.Id}"); + } + + foreach (var VNet in rg.GetVirtualNetworkContainer().ListByNameExpanded(Environment.UserName)) + { + Console.WriteLine($"--------VNet id--------: {VNet.Data.Id}"); + } + ExecuteAsync(rg).GetAwaiter().GetResult(); + + } + + private async Task ExecuteAsync(ResourceGroup rg) + { + await foreach (var availabilitySet in rg.GetAvailabilitySetContainer().ListByNameAsync(Environment.UserName)) + { + Console.WriteLine($"--------AvailabilitySet operation id--------: {availabilitySet.Id}"); + } + + await foreach (var availabilitySet in rg.GetAvailabilitySetContainer().ListByNameExpandedAsync(Environment.UserName)) + { + Console.WriteLine($"--------AvailabilitySet id--------: {availabilitySet.Data.Id}"); + } + + await foreach (var vm in rg.GetVirtualMachineContainer().ListByNameAsync(Environment.UserName)) + { + Console.WriteLine($"--------VM operation id--------: {vm.Id}"); + } + + await foreach (var vm in rg.GetVirtualMachineContainer().ListByNameExpandedAsync(Environment.UserName)) + { + Console.WriteLine($"--------VM id--------: {vm.Data.Id}"); + } + + await foreach (var networkInterface in rg.GetNetworkInterfaceContainer().ListByNameAsync(Environment.UserName)) + { + Console.WriteLine($"--------NetworkInterface operation id--------: {networkInterface.Id}"); + } + + await foreach (var networkInterface in rg.GetNetworkInterfaceContainer().ListByNameExpandedAsync(Environment.UserName)) + { + Console.WriteLine($"--------NetworkInterface id--------: {networkInterface.Data.Id}"); + } + + await foreach (var networkSecurityGroup in rg.GetNetworkSecurityGroupContainer().ListByNameAsync(Environment.UserName)) + { + Console.WriteLine($"--------NetworkSecurityGroup operation id--------: {networkSecurityGroup.Id}"); + } + + await foreach (var networkSecurityGroup in rg.GetNetworkSecurityGroupContainer().ListByNameExpandedAsync(Environment.UserName)) + { + Console.WriteLine($"--------NetworkSecurityGroup id--------: {networkSecurityGroup.Data.Id}"); + } + + await foreach (var publicIpAddress in rg.GetNetworkSecurityGroupContainer().ListByNameExpandedAsync(Environment.UserName)) + { + Console.WriteLine($"--------PublicIpAddress id--------: {publicIpAddress.Data.Id}"); + } + + await foreach (var VNet in rg.GetVirtualNetworkContainer().ListByNameAsync(Environment.UserName)) + { + Console.WriteLine($"--------VNet operation id--------: {VNet.Id}"); + } + + await foreach (var VNet in rg.GetVirtualNetworkContainer().ListByNameExpandedAsync(Environment.UserName)) + { + Console.WriteLine($"--------VNet id--------: {VNet.Data.Id}"); + } + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/NullDataValues.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/NullDataValues.cs new file mode 100644 index 0000000000000..474cfe26a0098 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/NullDataValues.cs @@ -0,0 +1,23 @@ +using Azure.ResourceManager.Core; +using System; +using Azure.ResourceManager.Resources.Models; +using Proto.Network; +using Proto.Compute; + +namespace Proto.Client +{ + class NullDataValues : Scenario + { + public override void Execute() + { + var rg = new Azure.ResourceManager.Resources.Models.ResourceGroup("East US"); + var resourceGroupData = new ResourceGroupData(rg); + var nic = new Azure.ResourceManager.Network.Models.NetworkInterface(); + var networkInterfaceData = new NetworkInterfaceData(nic); + var aset = new Azure.ResourceManager.Compute.Models.AvailabilitySet("East US"); + var availabilitySet = new AvailabilitySetData(aset); + + + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/RoleAssignment.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/RoleAssignment.cs new file mode 100644 index 0000000000000..0b840914f8e2c --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/RoleAssignment.cs @@ -0,0 +1,68 @@ +using Azure.ResourceManager.Core; +using Proto.Authorization; +using Proto.Compute; +using Proto.Network; +using System; + +namespace Proto.Client +{ + class RoleAssignment : Scenario + { + public override void Execute() + { + var client = new AzureResourceManagerClient(); + var subscription = client.GetSubscriptionOperations(Context.SubscriptionId); + + // Create Resource Group + Console.WriteLine($"--------Start create group {Context.RgName}--------"); + var resourceGroup = subscription.GetResourceGroupContainer().Construct(Context.Loc).CreateOrUpdate(Context.RgName).Value; + CleanUp.Add(resourceGroup.Id); + + Console.WriteLine("--------Start create Assignment--------"); + var input = new RoleAssignmentCreateParameters($"/subscriptions/{Context.SubscriptionId}/resourceGroups/{Context.RgName}/providers/Microsoft.Authorization/roleDefinitions/{Context.RoleId}", Context.PrincipalId); + var assign = resourceGroup.GetRoleAssignmentContainer().Create(Guid.NewGuid().ToString(), input).Value; + Console.WriteLine("--------Done create Assignment--------"); + + assign = assign.Get().Value; + + // Create AvailabilitySet + Console.WriteLine("--------Start create AvailabilitySet--------"); + var aset = resourceGroup.GetAvailabilitySetContainer().Construct("Aligned").CreateOrUpdate(Context.VmName + "_aSet").Value; + + // Create VNet + Console.WriteLine("--------Start create VNet--------"); + string vnetName = Context.VmName + "_vnet"; + var vnet = resourceGroup.GetVirtualNetworkContainer().Construct("10.0.0.0/16").CreateOrUpdate(vnetName).Value; + + //create subnet + Console.WriteLine("--------Start create Subnet--------"); + var subnet = vnet.GetSubnetContainer().Construct("10.0.0.0/24").CreateOrUpdate(Context.SubnetName).Value; + + //create network security group + Console.WriteLine("--------Start create NetworkSecurityGroup--------"); + _ = resourceGroup.GetNetworkSecurityGroupContainer().Construct(80).CreateOrUpdate(Context.NsgName).Value; + + // Create Network Interface + Console.WriteLine("--------Start create Network Interface--------"); + var nic = resourceGroup.GetNetworkInterfaceContainer().Construct(subnet.Id).CreateOrUpdate($"{Context.VmName}_nic").Value; + + // Create VM + Console.WriteLine("--------Start create VM--------"); + var vm = resourceGroup.GetVirtualMachineContainer().Construct(Context.Hostname, "admin-user", "!@#$%asdfA", nic.Id, aset.Id).CreateOrUpdate(Context.VmName).Value; + + Console.WriteLine("VM ID: " + vm.Id); + Console.WriteLine("--------Done create VM--------"); + + + Console.WriteLine("--------Start create Assignment--------"); + var input2 = new RoleAssignmentCreateParameters($"{vm.Id}/providers/Microsoft.Authorization/roleDefinitions/{Context.RoleId}", Context.PrincipalId); + var assign2 = vm.GetRoleAssignmentContainer().Create(Guid.NewGuid().ToString(), input2).Value; + Console.WriteLine("--------Done create Assignment--------"); + + assign2 = assign2.Get().Value; + Console.WriteLine($"Created assignment: '{assign.Data.Id}'"); + + + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/SetTagsOnVm.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/SetTagsOnVm.cs new file mode 100644 index 0000000000000..f4d978ae48cae --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/SetTagsOnVm.cs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; +using Azure.ResourceManager.Core; +using Proto.Compute; + +namespace Proto.Client +{ + class SetTagsOnVm : Scenario + { + public override void Execute() + { + var createVm = new CreateSingleVmExample(Context); + createVm.Execute(); + + ExecuteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + } + + private void DumpDictionary(IDictionary dic) + { + Console.WriteLine(string.Join( + ", ", + dic.Select(kvp => kvp.Key + ":" + kvp.Value))); + } + + private async Task ExecuteAsync() + { + // Update Tag for a known resource + var rgOp = new AzureResourceManagerClient().GetResourceGroupOperations(Context.SubscriptionId, Context.RgName); + var vmOp = rgOp.GetVirtualMachineOperations(Context.VmName); + + Console.WriteLine($"Adding tags to {vmOp.Id.Name}"); + + var vm = (await vmOp.StartAddTag("key1", "value1").WaitForCompletionAsync()).Value; + Debug.Assert(vm.Data.Tags.Where(x => x.Key.StartsWith("key")).Count() == 1); + DumpDictionary(vm.Data.Tags); + + vm = (await vm.StartAddTag("key2", "value2").WaitForCompletionAsync()).Value; + Debug.Assert(vm.Data.Tags.Where(x => x.Key.StartsWith("key")).Count() == 2); + DumpDictionary(vm.Data.Tags); + + vm = (await (await vmOp.StartAddTagAsync("key3", "value3")).WaitForCompletionAsync()).Value; + Debug.Assert(vm.Data.Tags.Where(x => x.Key.StartsWith("key")).Count() == 3); + DumpDictionary(vm.Data.Tags); + + vm = (await vm.StartAddTagAsync("key4", "value4")).WaitForCompletionAsync().Result.Value; + Debug.Assert(vm.Data.Tags.Where(x => x.Key.StartsWith("key")).Count() == 4); + DumpDictionary(vm.Data.Tags); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByLINQ.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByLINQ.cs new file mode 100644 index 0000000000000..c0b0fda0dc4c1 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByLINQ.cs @@ -0,0 +1,49 @@ +using Proto.Compute; +using Azure.ResourceManager.Core; +using System; +using System.Linq; + +namespace Proto.Client +{ + class ShutdownVmsByLINQ : Scenario + { + public override void Execute() + { + var createMultipleVms = new CreateMultipleVms(Context); + createMultipleVms.Execute(); + + var client = new AzureResourceManagerClient(); + foreach (var sub in client.GetSubscriptionContainer().List()) + { + var vmList = sub.ListVirtualMachines(); + foreach (var vm in vmList.Where(armResource => armResource.Data.Name.Contains("-o"))) + { + Console.WriteLine($"In subscription list: Stopping {vm.Id}"); + vm.PowerOff(); + Console.WriteLine($"In subscription list: Starting {vm.Id}"); + vm.PowerOn(); + } + } + + var resourceGroup = new AzureResourceManagerClient().GetResourceGroupOperations(Context.SubscriptionId, Context.RgName); + + resourceGroup.GetVirtualMachineContainer().List().Select(vm => + { + var parts = vm.Id.Name.Split('-'); + var n = Convert.ToInt32(parts[0].Last()); + return (vm, n); + }) + .Where(tuple => tuple.n % 2 == 0) + .ToList() + .ForEach(tuple => + { + Console.WriteLine($"In resource group list: Stopping {tuple.vm.Id.Name}"); + tuple.vm.PowerOff(); + Console.WriteLine($"In resource group list: Starting {tuple.vm.Id.Name}"); + tuple.vm.PowerOn(); + }); + + + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByName.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByName.cs new file mode 100644 index 0000000000000..e86d36e0837e5 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByName.cs @@ -0,0 +1,28 @@ +using Proto.Compute; +using Azure.ResourceManager.Core; +using System; + +namespace Proto.Client +{ + class ShutdownVmsByName: Scenario + { + public override void Execute() + { + var createMultipleVms = new CreateMultipleVms(Context); + createMultipleVms.Execute(); + + var sub = new AzureResourceManagerClient().GetSubscriptionOperations(Context.SubscriptionId); + + foreach(var armResource in sub.ListVirtualMachinesByName("-e")) + { + var vmOperations = VirtualMachineOperations.FromGeneric(armResource); + Console.WriteLine($"Stopping {armResource.Id.ResourceGroup} : {armResource.Id.Name}"); + vmOperations.PowerOff(); + Console.WriteLine($"Starting {armResource.Id.ResourceGroup} : {armResource.Id.Name}"); + vmOperations.PowerOn(); + } + + + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByNameAcrossResourceGroups.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByNameAcrossResourceGroups.cs new file mode 100644 index 0000000000000..d9842ab8bdb8c --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByNameAcrossResourceGroups.cs @@ -0,0 +1,38 @@ +using Proto.Compute; +using Azure.ResourceManager.Core; +using System; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace Proto.Client +{ + class ShutdownVmsByNameAcrossResourceGroups : Scenario + { + public override void Execute() + { + int numberOfRgs = 2; + var context = Context; + for (int i = 0; i < numberOfRgs; i++) + { + var createMultipleVms = new CreateMultipleVms(context); + createMultipleVms.Execute(); + context = new ScenarioContext(); + } + + var subscription = new AzureResourceManagerClient().GetSubscriptionOperations(Context.SubscriptionId); + + Regex reg = new Regex($"{Context.VmName}.*-e"); + Parallel.ForEach(subscription.ListVirtualMachines(), vm => + { + if (reg.IsMatch(vm.Id.Name)) + { + Console.WriteLine($"Stopping {vm.Id.ResourceGroup} {vm.Id.Name}"); + vm.PowerOff(); + Console.WriteLine($"Starting {vm.Id.ResourceGroup} {vm.Id.Name}"); + vm.PowerOn(); + } + }); + + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByNameAcrossSubscriptions.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByNameAcrossSubscriptions.cs new file mode 100644 index 0000000000000..263ccdaa88154 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByNameAcrossSubscriptions.cs @@ -0,0 +1,57 @@ +using Azure.ResourceManager.Compute; +using Proto.Compute; +using Azure.ResourceManager.Core; +using System; +using System.Threading.Tasks; + +namespace Proto.Client +{ + class ShutdownVmsByNameAcrossSubscriptions : Scenario + { + public async void ShutdownAsync() + { + var client = new AzureResourceManagerClient(); + + await foreach (var subscription in client.GetSubscriptionContainer().ListAsync()) + { + await foreach (var armResource in subscription.ListVirtualMachinesByNameAsync("-e")) + { + var vmOperations = VirtualMachineOperations.FromGeneric(armResource); + await vmOperations.PowerOffAsync(); + await vmOperations.PowerOnAsync(); + } + } + } + + public async override void Execute() + { + #region SETUP + ScenarioContext[] contexts = new ScenarioContext[] { new ScenarioContext(), new ScenarioContext("c9cbd920-c00c-427c-852b-8aaf38badaeb") }; + ParallelOptions options = new ParallelOptions + { + MaxDegreeOfParallelism = 1 + }; + + Parallel.ForEach(contexts, options, context => + { + var createMultipleVms = new CreateMultipleVms(context); + createMultipleVms.Execute(); + }); + #endregion + + + var client = new AzureResourceManagerClient(); + foreach (var sub in client.GetSubscriptionContainer().List()) + { + await foreach (var armResource in sub.ListVirtualMachinesByNameAsync("-e")) + { + var vmOperations = VirtualMachineOperations.FromGeneric(armResource); + Console.WriteLine($"Stopping {vmOperations.Id.Subscription} {vmOperations.Id.ResourceGroup} {vmOperations.Id.Name}"); + vmOperations.PowerOff(); + Console.WriteLine($"Starting {vmOperations.Id.Subscription} {vmOperations.Id.ResourceGroup} {vmOperations.Id.Name}"); + vmOperations.PowerOn(); + } + } + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByTag.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByTag.cs new file mode 100644 index 0000000000000..b62af442f7102 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/ShutdownVmsByTag.cs @@ -0,0 +1,44 @@ +using Proto.Compute; +using Azure.ResourceManager.Core; +using System; +using System.Linq; + +namespace Proto.Client +{ + class ShutdownVmsByTag : Scenario + { + public override void Execute() + { + var createMultipleVms = new CreateMultipleVms(Context); + createMultipleVms.Execute(); + + var rg = new AzureResourceManagerClient().GetResourceGroupOperations(Context.SubscriptionId, Context.RgName).Get().Value; + + //set tags on random vms + Random rand = new Random(Environment.TickCount); + foreach (var generic in rg.GetVirtualMachineContainer().ListByName(Environment.UserName)) + { + var vm = VirtualMachineOperations.FromGeneric(generic); + if (rand.NextDouble() > 0.5) + { + Console.WriteLine("adding tag to {0}", vm.Id.Name); + vm.StartAddTag("tagkey", "tagvalue"); + } + } + + var filteredList = rg.GetVirtualMachineContainer().List().Where(vm => + { + string value; + return (vm.Data.Tags.TryGetValue("tagkey", out value) && value == "tagvalue"); + }); + + foreach (var vm in filteredList) + { + Console.WriteLine("--------Stopping VM {0}--------", vm.Id.Name); + vm.PowerOff(); + Console.WriteLine("--------Starting VM {0}--------", vm.Id.Name); + vm.PowerOn(); + } + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/StartCreateSingleVmExample.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/StartCreateSingleVmExample.cs new file mode 100644 index 0000000000000..69c7507675c19 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/StartCreateSingleVmExample.cs @@ -0,0 +1,58 @@ +using Azure.ResourceManager.Core; +using Proto.Compute; +using Proto.Network; +using System; + +namespace Proto.Client +{ + class StartCreateSingleVmExample : Scenario + { + public StartCreateSingleVmExample() : base() { } + + public StartCreateSingleVmExample(ScenarioContext context) : base(context) { } + + public override void Execute() + { + ExcuteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + } + + private async System.Threading.Tasks.Task ExcuteAsync() + { + var client = new AzureResourceManagerClient(); + var subscription = client.GetSubscriptionOperations(Context.SubscriptionId); + + // Create Resource Group + Console.WriteLine($"--------Start StartCreate group {Context.RgName}--------"); + var resourceGroup = (await(subscription.GetResourceGroupContainer().Construct(Context.Loc).StartCreateOrUpdate(Context.RgName)).WaitForCompletionAsync()).Value; + CleanUp.Add(resourceGroup.Id); + + // Create AvailabilitySet + Console.WriteLine("--------Start StartCreate AvailabilitySet async--------"); + var aset = (await(resourceGroup.GetAvailabilitySetContainer().Construct("Aligned").StartCreateOrUpdate(Context.VmName + "_aSet")).WaitForCompletionAsync()).Value; + + // Create VNet + Console.WriteLine("--------Start StartCreate VNet--------"); + string vnetName = Context.VmName + "_vnet"; + var vnet = (await(resourceGroup.GetVirtualNetworkContainer().Construct("10.0.0.0/16").StartCreateOrUpdate(vnetName)).WaitForCompletionAsync()).Value; + + //create subnet + Console.WriteLine("--------Start StartCreate Subnet--------"); + var subnet = (await(vnet.GetSubnetContainer().Construct("10.0.0.0/24").StartCreateOrUpdate(Context.SubnetName)).WaitForCompletionAsync()).Value; + + //create network security group + Console.WriteLine("--------Start StartCreate NetworkSecurityGroup--------"); + _ = (await(resourceGroup.GetNetworkSecurityGroupContainer().Construct(80).StartCreateOrUpdate(Context.NsgName)).WaitForCompletionAsync()).Value; + + // Create Network Interface + Console.WriteLine("--------Start StartCreate Network Interface--------"); + var nic = (await(resourceGroup.GetNetworkInterfaceContainer().Construct(subnet.Id).StartCreateOrUpdate($"{Context.VmName}_nic")).WaitForCompletionAsync()).Value; + + // Create VM + Console.WriteLine("--------Start StartCreate VM --------"); + var vm = (await(resourceGroup.GetVirtualMachineContainer().Construct(Context.Hostname, "admin-user", "!@#$%asdfA", nic.Id, aset.Id).StartCreateOrUpdate(Context.VmName)).WaitForCompletionAsync()).Value; + + Console.WriteLine("VM ID: " + vm.Id); + Console.WriteLine("--------Done StartCreate VM--------"); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/StartCreateSingleVmExampleAsync.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/StartCreateSingleVmExampleAsync.cs new file mode 100644 index 0000000000000..86937eae74768 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/StartCreateSingleVmExampleAsync.cs @@ -0,0 +1,57 @@ +using Azure.ResourceManager.Core; +using Proto.Compute; +using Proto.Network; +using System; + +namespace Proto.Client +{ + class StartCreateSingleVmExampleAsync : Scenario + { + public StartCreateSingleVmExampleAsync() : base() { } + + public StartCreateSingleVmExampleAsync(ScenarioContext context) : base(context) { } + + public override void Execute() + { + ExecuteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + } + private async System.Threading.Tasks.Task ExecuteAsync() + { + var client = new AzureResourceManagerClient(); + var subscription = client.GetSubscriptionOperations(Context.SubscriptionId); + + // Create Resource Group + Console.WriteLine($"--------Start StartCreate group async {Context.RgName}--------"); + var resourceGroup = (await (await subscription.GetResourceGroupContainer().Construct(Context.Loc).StartCreateOrUpdateAsync(Context.RgName)).WaitForCompletionAsync()).Value; + CleanUp.Add(resourceGroup.Id); + + // Create AvailabilitySet + Console.WriteLine("--------Start StartCreate AvailabilitySet async--------"); + var aset = (await (await resourceGroup.GetAvailabilitySetContainer().Construct("Aligned").StartCreateOrUpdateAsync(Context.VmName + "_aSet")).WaitForCompletionAsync()).Value; + + // Create VNet + Console.WriteLine("--------Start StartCreate VNet async--------"); + string vnetName = Context.VmName + "_vnet"; + var vnet = (await (await resourceGroup.GetVirtualNetworkContainer().Construct("10.0.0.0/16").StartCreateOrUpdateAsync(vnetName)).WaitForCompletionAsync()).Value; + + //create subnet + Console.WriteLine("--------Start StartCreate Subnet async--------"); + var subnet = (await (await vnet.GetSubnetContainer().Construct("10.0.0.0/24").StartCreateOrUpdateAsync(Context.SubnetName)).WaitForCompletionAsync()).Value; + + //create network security group + Console.WriteLine("--------Start StartCreate NetworkSecurityGroup async--------"); + _ = (await (await resourceGroup.GetNetworkSecurityGroupContainer().Construct(80).StartCreateOrUpdateAsync(Context.NsgName)).WaitForCompletionAsync()).Value; + + // Create Network Interface + Console.WriteLine("--------Start StartCreate Network Interface async--------"); + var nic = (await (await resourceGroup.GetNetworkInterfaceContainer().Construct(subnet.Id).StartCreateOrUpdateAsync($"{Context.VmName}_nic")).WaitForCompletionAsync()).Value; + + // Create VM + Console.WriteLine("--------Start StartCreate VM async--------"); + var vm = (await (await resourceGroup.GetVirtualMachineContainer().Construct(Context.Hostname, "admin-user", "!@#$%asdfA", nic.Id, aset.Id).StartCreateOrUpdateAsync(Context.VmName)).WaitForCompletionAsync()).Value; + + Console.WriteLine("VM ID: " + vm.Id); + Console.WriteLine("--------Done StartCreate VM--------"); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/StartFromVm.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/StartFromVm.cs new file mode 100644 index 0000000000000..f8aa2100cf50c --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/StartFromVm.cs @@ -0,0 +1,26 @@ +using Proto.Compute; +using Azure.ResourceManager.Core; +using System; + +namespace Proto.Client +{ + class StartFromVm : Scenario + { + public override void Execute() + { + var createVm = new CreateSingleVmExample(Context); + createVm.Execute(); + var client = new AzureResourceManagerClient(); + + //retrieve from lowest level, doesn't give ability to walk up and down the container structure + var vmOp = client.GetResourceOperations(Context.SubscriptionId, Context.RgName, Context.VmName); + var vm = vmOp.Get().Value.Data; + Console.WriteLine($"Found VM {vm.Id}"); + + //retrieve from lowest level inside management package gives ability to walk up and down + var rg = client.GetResourceGroupOperations(Context.SubscriptionId, Context.RgName); + var vm2 = rg.GetVirtualMachineOperations(Context.VmName).Get().Value.Data; + Console.WriteLine($"Found VM {vm2.Id}"); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/StartStopVm.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/StartStopVm.cs new file mode 100644 index 0000000000000..4f6dd70d71825 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/StartStopVm.cs @@ -0,0 +1,25 @@ +using Proto.Compute; +using Azure.ResourceManager.Core; +using System; + +namespace Proto.Client +{ + class StartStopVm : Scenario + { + public override void Execute() + { + var createVm = new CreateSingleVmExample(Context); + createVm.Execute(); + + var client = new AzureResourceManagerClient(); + var subscription = client.GetSubscriptionOperations(Context.SubscriptionId); + var resourceGroup = subscription.GetResourceGroupOperations(Context.RgName); + var vm = resourceGroup.GetVirtualMachineOperations(Context.VmName); + Console.WriteLine($"Found VM {Context.VmName}"); + Console.WriteLine("--------Stopping VM--------"); + vm.PowerOff(); + Console.WriteLine("--------Starting VM--------"); + vm.PowerOn(); + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/SubscriptionExists.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/SubscriptionExists.cs new file mode 100644 index 0000000000000..41ab8df56a553 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/SubscriptionExists.cs @@ -0,0 +1,21 @@ +using Azure.ResourceManager.Core; +using System; + +namespace Proto.Client +{ + class SubscriptionExists : Scenario + { + public override void Execute() + { + var client = new AzureResourceManagerClient(); + if(client.GetSubscriptionContainer().DoesExist(Context.SubscriptionId)) + { + Console.WriteLine($"Found {Context.SubscriptionId}"); + } + else + { + throw new Exception($"Did not find {Context.SubscriptionId}"); + } + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/UseParentLocation.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/UseParentLocation.cs new file mode 100644 index 0000000000000..636586e3a67a3 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/UseParentLocation.cs @@ -0,0 +1,60 @@ +using Azure.ResourceManager.Core; +using Proto.Compute; +using Proto.Network; +using System; + +namespace Proto.Client +{ + class UseParentLocation : Scenario + { + public override void Execute() + { + var client = new AzureResourceManagerClient(); + var subscription = client.GetSubscriptionOperations(Context.SubscriptionId); + + // Create Resource Group + Console.WriteLine($"--------Start create group {Context.RgName}--------"); + var resourceGroup = subscription.GetResourceGroupContainer().Construct(Context.Loc).CreateOrUpdate(Context.RgName).Value; + CleanUp.Add(resourceGroup.Id); + + // Create AvailabilitySet + Console.WriteLine("--------Start create AvailabilitySet--------"); + var aset = resourceGroup.GetAvailabilitySetContainer().Construct("Aligned").CreateOrUpdate(Context.VmName + "_aSet").Value; + if (aset.Data.Location != Context.Loc) + throw new Exception($"aset was on the wrong location expected {Context.Loc} actual {aset.Data.Location}"); + + // Create VNet + Console.WriteLine("--------Start create VNet--------"); + string vnetName = Context.VmName + "_vnet"; + var vnet = resourceGroup.GetVirtualNetworkContainer().Construct("10.0.0.0/16").CreateOrUpdate(vnetName).Value; + if (vnet.Data.Location != Context.Loc) + throw new Exception($"vnet was on the wrong location expected {Context.Loc} actual {vnet.Data.Location}"); + + //create subnet + Console.WriteLine("--------Start create Subnet async--------"); + var subnet = vnet.GetSubnetContainer().Construct("10.0.0.0/24").CreateOrUpdateAsync(Context.SubnetName).ConfigureAwait(false).GetAwaiter().GetResult().Value; + + //create network security group + Console.WriteLine("--------Start create NetworkSecurityGroup--------"); + var nsg = resourceGroup.GetNetworkSecurityGroupContainer().Construct(80).CreateOrUpdate(Context.NsgName).Value; + if (nsg.Data.Location != Context.Loc) + throw new Exception($"nsg was on the wrong location expected {Context.Loc} actual {nsg.Data.Location}"); + + // Create Network Interface + Console.WriteLine("--------Start create Network Interface--------"); + var nic = resourceGroup.GetNetworkInterfaceContainer().Construct(subnet.Id).CreateOrUpdate($"{Context.VmName}_nic").Value; + if (nic.Data.Location != Context.Loc) + throw new Exception($"nic was on the wrong location expected {Context.Loc} actual {nic.Data.Location}"); + + // Create VM + Console.WriteLine("--------Start create VM--------"); + var vm = resourceGroup.GetVirtualMachineContainer().Construct(Context.Hostname, "admin-user", "!@#$%asdfA", nic.Id, aset.Id).CreateOrUpdate(Context.VmName).Value; + if (vm.Data.Location != Context.Loc) + throw new Exception($"vm was on the wrong location expected {Context.Loc} actual {vm.Data.Location}"); + + Console.WriteLine("VM ID: " + vm.Id); + Console.WriteLine("--------Done create VM--------"); + + } + } +} diff --git a/sdk/resourcemanager/Proto.Client/src/Scenarios/VmModelBuilder.cs b/sdk/resourcemanager/Proto.Client/src/Scenarios/VmModelBuilder.cs new file mode 100644 index 0000000000000..2f71a2cda5f21 --- /dev/null +++ b/sdk/resourcemanager/Proto.Client/src/Scenarios/VmModelBuilder.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Threading.Tasks; +using Proto.Compute; +using Azure.ResourceManager.Core; +using Proto.Network; +using Proto.Compute.Convenience; + +namespace Proto.Client +{ + class VmModelBuilder : Scenario + { + public override void Execute() + { + throw new NotImplementedException(); + } + + private Task CreateVmWithBuilderAsync() + { + var client = new AzureResourceManagerClient(); + var subscription = client.GetSubscriptionOperations(Context.SubscriptionId); + + // Create Resource Group + Console.WriteLine($"--------Start create group {Context.RgName}--------"); + var resourceGroup = subscription.GetResourceGroupContainer().Construct(Context.Loc).CreateOrUpdate(Context.RgName).Value; + + // Create AvailabilitySet + Console.WriteLine("--------Start create AvailabilitySet--------"); + var aset = resourceGroup.GetAvailabilitySetContainer().Construct("Aligned").CreateOrUpdate(Context.VmName + "_aSet").Value; + + // Create VNet + Console.WriteLine("--------Start create VNet--------"); + string vnetName = Context.VmName + "_vnet"; + var vnet = resourceGroup.GetVirtualNetworkContainer().Construct("10.0.0.0/16").CreateOrUpdate(vnetName).Value; + + //create subnet + Console.WriteLine("--------Start create Subnet--------"); + var nsg = resourceGroup.GetNetworkSecurityGroupContainer().Construct(80).CreateOrUpdate(Context.NsgName).Value; + var subnet = vnet.GetSubnetContainer().Construct("10.0.0.0/24").CreateOrUpdate(Context.SubnetName).Value; + + // Create Network Interface + Console.WriteLine("--------Start create Network Interface--------"); + var nic = resourceGroup.GetNetworkInterfaceContainer().Construct(subnet.Id).CreateOrUpdate($"{Context.VmName}_nic").Value; + + // Options: required parameters on in the constructor + VirtualMachineModelBuilder vmBuilder = new VirtualMachineModelBuilder( + resourceGroup.GetVirtualMachineContainer(), + new VirtualMachineData(new Azure.ResourceManager.Compute.Models.VirtualMachine(Context.Loc))); ; + var vm = vmBuilder.UseWindowsImage("admin-user", "!@#$%asdfA") + .RequiredNetworkInterface(nic.Id) + .RequiredAvalabilitySet(aset.Id) + .CreateOrUpdate(Context.VmName).Value; + + return Task.FromResult(vm); + } + } +} diff --git a/sdk/resourcemanager/ci.yml b/sdk/resourcemanager/ci.yml new file mode 100644 index 0000000000000..68b222242f134 --- /dev/null +++ b/sdk/resourcemanager/ci.yml @@ -0,0 +1,31 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - master + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/ + +pr: + branches: + include: + - master + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/ + +extends: + template: ../../eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: resourcemanager + ArtifactName: packages + Artifacts: + - name: Azure.ResourceManager.Core + safeName: AzureResourceManagerCore