stack resources module for 2018-03-01-hybrid profile
This commit is contained in:
Родитель
8dbadd20a6
Коммит
addd84178a
|
@ -0,0 +1,159 @@
|
|||
<!--
|
||||
Please leave this section at the top of the change log.
|
||||
|
||||
Changes for the current release should go under the section titled "Current Release", and should adhere to the following format:
|
||||
|
||||
## Current Release
|
||||
* Overview of change #1
|
||||
- Additional information about change #1
|
||||
* Overview of change #2
|
||||
- Additional information about change #2
|
||||
- Additional information about change #2
|
||||
* Overview of change #3
|
||||
* Overview of change #4
|
||||
- Additional information about change #4
|
||||
|
||||
## YYYY.MM.DD - Version X.Y.Z (Previous Release)
|
||||
* Overview of change #1
|
||||
- Additional information about change #1
|
||||
-->
|
||||
## Current Release
|
||||
|
||||
## Version 6.0.0
|
||||
* Set minimum dependency of module to PowerShell 5.0
|
||||
* Remove obsolete parameter -AtScopeAndBelow from Get-AzureRmRoledefinition call
|
||||
* Include assignments to deleted Users/Groups/ServicePrincipals in Get-AzureRmRoleAssignment result
|
||||
* Add convenience cmdlet for creating ServicePrincipals
|
||||
* Add Tab completers for Scope and ResourceType
|
||||
* Merge Get- and Find- functionality in Get-AzureRmResource
|
||||
* Add AD Cmdlets:
|
||||
- Remove-AzureRmADGroupMember
|
||||
- Get-AzureRmADGroup
|
||||
- New-AzureRmADGroup
|
||||
- Remove-AzureRmADGroup
|
||||
- Remove-AzureRmADUser
|
||||
- Update-AzureRmADApplication
|
||||
- Update-AzureRmADServicePrincipal
|
||||
- Update-AzureRmADUser
|
||||
|
||||
## Version 5.5.2
|
||||
* Updated to the latest version of the Azure ClientRuntime
|
||||
|
||||
## Version 5.5.1
|
||||
* Fix issue with Default Resource Group in CloudShell
|
||||
|
||||
## Version 5.5.0
|
||||
* Fixed issue with importing aliases
|
||||
* Add Support for DataActions and NotDataActions to be passed in roledefinition create calls
|
||||
* Fix Roledefinitions calls to use the type filter
|
||||
|
||||
## Version 5.4.0
|
||||
* Register-AzureRmProviderFeature: Added missing example in the docs
|
||||
* Register-AzureRmResourceProvider: Added missing example in the docs
|
||||
* Add proper error handling for Insufficient graph permission Issue whilst performing Roleassignment calls.
|
||||
* Fix roleassignment get calls when there are duplicate objectIds.
|
||||
* Fix RoleAssignment get to respect the ExpandPrincipalGroups parameter
|
||||
* Fix Roleassignment get calls to be used with roledefinition ID.
|
||||
|
||||
## Version 5.3.0
|
||||
* Get-AzureRmADServicePrincipal: Removed -ServicePrincipalName from the default Empty parameter set as it was redundant with the SPN parameter set
|
||||
|
||||
## Version 5.2.0
|
||||
* Added Location Completer to -Location parameters allowing tab completion through valid Locations
|
||||
* Added ResourceGroup Completer to -ResourceGroup parameters allowing tab completion through resource groups in current subscription
|
||||
* Added -AsJob support for long-running Resources cmdlets. Allows selected cmdlets to run in the background and return a job to track and control progress.
|
||||
* Added alias from Get-AzureRmProviderOperation to Get-AzureRmResourceProviderAction to conform with naming conventions
|
||||
* Get-AzureRmProviderOperation: Added alias from -OperationSearchString to -Name and set default value of -OperationSearchString to "*", which will return all provider operations.
|
||||
|
||||
## Version 5.1.1
|
||||
* Fixed issue where Get-AzureRMRoleAssignment would result in a assignments without roledefiniton name for custom roles
|
||||
- Users can now use Get-AzureRMRoleAssignment with assignments having roledefinition names irrespective of the type of role
|
||||
* Fixed issue where Set-AzureRMRoleRoleDefinition used to throw RD not found error when there was a new scope in assignablescopes
|
||||
- Users can now use Set-AzureRMRoleRoleDefinition with assignable scopes including new scopes irrespective of the position of the scope
|
||||
* Allow scopes to end with "/"
|
||||
- Users can now use RoleDefinition and RoleAssignment commandlets with scopes ending with "/" ,consistent with API and CLI
|
||||
* Allow users to create RoleAssignment using delegation flag
|
||||
- Users can now use New-AzureRMRoleAssignment with an option of adding the delegation flag
|
||||
* Fix RoleAssignment get to respect the scope parameter
|
||||
* Add an alias for ServicePrincipalName in the New-AzureRmRoleAssignment Commandlet
|
||||
- Users can now use the ApplicationId instead of the ServicePrincipalName when using the New-AzureRmRoleAssignment commandlet
|
||||
|
||||
## Version 5.0.0
|
||||
* Add support for online help
|
||||
- Run Get-Help with the -Online parameter to open the online help in your default Internet browser
|
||||
|
||||
## Version 4.4.1
|
||||
|
||||
## Version 4.4.0
|
||||
* Add ManagedApplication cmdlets
|
||||
- New-AzureRmManagedApplication cmdlet to create a managed application
|
||||
- Get-AzureRmManagedApplication cmdlet to list all managed applications under a subscription or to get a specific managed application
|
||||
- Remove-AzureRmManagedApplication cmdlet to delete a managed application
|
||||
- Set-AzureRmManagedApplication cmdlet to update an existing managed application
|
||||
* Add ManagedApplicationDefinition cmdlets
|
||||
- New-AzureRmManagedApplicationDefinition cmdlet to create a managed application definition using a zip file uri or using mainTemplate and createUiDefinition json files
|
||||
- Get-AzureRmManagedApplicationDefinition cmdlet to list all managed application definitions under a resource group or to get a specific managed application definition
|
||||
- Remove-AzureRmManagedApplicationDefinition cmdlet to delete a managed application definition
|
||||
- Set-AzureRmManagedApplicationDefinition cmdlet to update an existing managed application definition
|
||||
* Add PolicySetDefinition cmdlets
|
||||
- New-AzureRmPolicySetDefinition cmdlet to create a policy set definition
|
||||
- Get-AzureRmPolicySetDefinition cmdlet to list all policy set definitions or to get a specific policy set definition
|
||||
- Remove-AzureRmPolicySetDefinition cmdlet to delete a policy set definition
|
||||
- Set-AzureRmPolicySetDefinition cmdlet to update an existing policy set definition
|
||||
* Add -PolicySetDefinition, -Sku and -NotScope parameters to New-AzureRmPolicyAssignment and Set-AzureRmPolicyAssignment cmdlets
|
||||
* Add support to pass in policy url to New-AzureRmPolicyDefinition and Set-AzureRmPolicyDefinition cmdlets
|
||||
* Add -Mode parameter to New-AzureRmPolicyDefinition cmdlet
|
||||
* Add Support for removal of roleassignment using PSRoleAssignment object
|
||||
- Users can now use PSRoleassignmnet inputobject with Remove-AzureRMRoleAssignment commandlet to remove the roleassignment.
|
||||
|
||||
## Version 4.3.1
|
||||
|
||||
## Version 4.3.0
|
||||
* Add Support for validation of scopes for the following roledefinition and roleassignment commandlets before sending the request to ARM
|
||||
- Get-AzureRMRoleAssignment
|
||||
- New-AzureRMRoleAssignment
|
||||
- Remove-AzureRMRoleAssignment
|
||||
- Get-AzureRMRoleDefinition
|
||||
- New-AzureRMRoleDefinition
|
||||
- Remove-AzureRMRoleDefinition
|
||||
- Set-AzureRMRoleDefinition
|
||||
|
||||
## Version 4.2.1
|
||||
|
||||
## Version 4.2.0
|
||||
|
||||
## Version 4.1.0
|
||||
* Fixed issue where Get-AzureRMRoleAssignment would result in a Bad Request if the number of roleassignments where greater than 1000
|
||||
- Users can now use Get-AzureRMRoleAssignment even if the roleassignments to be returned is greater than 1000
|
||||
|
||||
## Version 4.0.1
|
||||
|
||||
## Version 4.0.0
|
||||
* Support cross-resource-group deployments for New-AzureRmResourceGroupDeployment
|
||||
- Users can now use nested deployments to deploy to different resource groups.
|
||||
|
||||
## Version 3.8.0
|
||||
|
||||
## Version 3.7.0
|
||||
|
||||
## Version 3.6.0
|
||||
* Support policy parameters for New-AzureRmPolicyDefinition and New-AzureRmPolicyAssignment
|
||||
- Users can now use Parameter parameter with New-AzureRmPolicyDefinition. This accepts both JSON string and file path.
|
||||
- Users can now provide policy parameter values in New-AzureRmPolicyAssignment in a couple of ways, including JSON string, file path, PS object, and through PowerShell parameters.
|
||||
|
||||
## Version 3.5.0
|
||||
* Support Tag as parameters for Find-AzureRmResource
|
||||
- Users can now use Tag parameter with Find-AzureRmResource
|
||||
- Fixed the issue where illegal combinations of TagName, TagValue with other search parameters was allowed in Find-AzureRmResource and would result in users getting exception from the service by disallowing such combinations.
|
||||
|
||||
## Version 3.4.0
|
||||
* Support ResourceNameEquals and ResourceGroupNameEquals as parameters for Find-AzureRmResource
|
||||
- Users can now use ResourceNameEquals and ResourceGroupNameEquals with Find-AzureRmResource
|
||||
|
||||
## Version 3.3.0
|
||||
* Lookup of AAD group by Id now uses GetObjectsByObjectId AAD Graph call instead of Groups/<id>
|
||||
- This will enable Groups lookup in CSP scenario
|
||||
* Remove unnecessary AAD graph call in Get role assignments logic
|
||||
- Only make call when needed instead of always
|
||||
* Fixed issue where Remove-AzureRmResource would throw an exception if one of the resources passed through the pipeline failed to be removed
|
||||
- If cmdlet fails to remove one of the resources, the result will not have an effect on the removal of other resources
|
|
@ -0,0 +1,60 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Collections
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Commands.Common.Authentication.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// The insensitive version of dictionary.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type of the value.</typeparam>
|
||||
[JsonPreserveCaseDictionary]
|
||||
public class InsensitiveDictionary<TValue> : Dictionary<string, TValue>
|
||||
{
|
||||
/// <summary>
|
||||
/// The empty dictionary.
|
||||
/// </summary>
|
||||
public static readonly InsensitiveDictionary<TValue> Empty = new InsensitiveDictionary<TValue>();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InsensitiveDictionary{TValue}"/> class.
|
||||
/// </summary>
|
||||
public InsensitiveDictionary()
|
||||
: base(StringComparer.InvariantCultureIgnoreCase)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InsensitiveDictionary{TValue}"/> class.
|
||||
/// </summary>
|
||||
/// <param name="capacity">The initial number of elements that the <see cref="T:System.Collections.Generic.Dictionary`2" /> can contain.</param>
|
||||
public InsensitiveDictionary(int capacity)
|
||||
: base(capacity, StringComparer.InvariantCultureIgnoreCase)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InsensitiveDictionary{TValue}"/> class.
|
||||
/// </summary>
|
||||
/// <param name="dictionary">The dictionary.</param>
|
||||
public InsensitiveDictionary(IDictionary<string, TValue> dictionary)
|
||||
: base(dictionary, StringComparer.InvariantCultureIgnoreCase)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<Import Project="..\..\..\..\..\..\tools\Common.Netcore.Dependencies.targets" />
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp2.0</TargetFramework>
|
||||
<AssemblyName>Microsoft.Azure.Commands.ResourceManager.Cmdlets</AssemblyName>
|
||||
<RootNamespace>Microsoft.Azure.Commands.ResourceManager.Cmdlets</RootNamespace>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
|
||||
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||
<OutputPath>..\..\..\..\..\Package\Debug\ResourceManager\AzureResourceManager\AzureRM.Resources.Netcore\</OutputPath>
|
||||
<SignAssembly>True</SignAssembly>
|
||||
<DelaySign>True</DelaySign>
|
||||
<AssemblyOriginatorKeyFile>MSSharedLibKey.snk</AssemblyOriginatorKeyFile>
|
||||
<DefineConstants>TRACE;RELEASE;NETSTANDARD;SIGN</DefineConstants>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
<OutputPath>..\..\..\..\..\Package\Debug\ResourceManager\AzureResourceManager\AzureRM.Resources.Netcore\</OutputPath>
|
||||
<DefineConstants>TRACE;DEBUG;NETSTANDARD</DefineConstants>
|
||||
<DelaySign>false</DelaySign>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Azure.Management.ResourceManager" Version="1.6.0-preview" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="1.1.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\..\Common\Commands.Common.Authentication.Abstractions\Common.Authentication.Abstractions.Netcore.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\..\Common\Commands.Common\Common.Netcore.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\Common\Commands.ResourceManager.Common\Common.ResourceManager.Netcore.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\Tags\Commands.Tags\Commands.Tags.Netcore.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>Resources.resx</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Update="Properties\Resources.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="Microsoft.Azure.Commands.ResourceManager.Cmdlets.format.ps1xml">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Microsoft.Azure.Commands.ResourceManager.Cmdlets.Types.ps1xml">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="ResourceManagerStartup.ps1">
|
||||
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="help\**\*" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
|
@ -0,0 +1,264 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="..\..\..\..\..\tools\Common.Dependencies.targets" />
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{8058D403-06E3-4BED-8924-D166CE303961}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>Microsoft.Azure.Commands.ResourceManager.Cmdlets</RootNamespace>
|
||||
<AssemblyName>Microsoft.Azure.Commands.ResourceManager.Cmdlets</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\..\..\</SolutionDir>
|
||||
<RestorePackages>true</RestorePackages>
|
||||
<NuGetPackageImportStamp>a06c46cd</NuGetPackageImportStamp>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>..\..\..\..\Stack\Debug\ResourceManager\AzureResourceManager\AzureRM.Resources\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<SignAssembly>true</SignAssembly>
|
||||
<AssemblyOriginatorKeyFile>MSSharedLibKey.snk</AssemblyOriginatorKeyFile>
|
||||
<DelaySign>true</DelaySign>
|
||||
<OutputPath>..\..\..\..\Stack\Release\ResourceManager\AzureResourceManager\AzureRM.Resources\</OutputPath>
|
||||
<DefineConstants>TRACE;SIGN</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<CodeAnalysisLogFile>bin\Release\Microsoft.Azure.Commands.ResourceManager.Cmdlets.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>
|
||||
<CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
|
||||
<CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
<CodeAnalysisRuleSetDirectories>;$(ProgramFiles)\Microsoft Visual Studio 12.0\Team Tools\Static Analysis Tools\Rule Sets</CodeAnalysisRuleSetDirectories>
|
||||
<CodeAnalysisRuleDirectories>;$(ProgramFiles)\Microsoft Visual Studio 12.0\Team Tools\Static Analysis Tools\FxCop\Rules</CodeAnalysisRuleDirectories>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Microsoft.Azure.Management.ResourceManager, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\..\..\..\packages\Microsoft.Azure.Management.ResourceManager.1.6.0-preview\lib\net452\Microsoft.Azure.Management.ResourceManager.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Runtime.Caching" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Collections\InsensitiveDictionary.cs" />
|
||||
<Compile Include="Components\Constants.cs" />
|
||||
<Compile Include="Components\HttpClientHelper.cs" />
|
||||
<Compile Include="Components\HttpClientHelperFactory.cs" />
|
||||
<Compile Include="Components\HttpMethodExt.cs" />
|
||||
<Compile Include="Components\HttpStatusCodeExt.cs" />
|
||||
<Compile Include="Components\OperationResult.cs" />
|
||||
<Compile Include="Components\QueryFilterBuilder.cs" />
|
||||
<Compile Include="Components\ResourceIdUtility.cs" />
|
||||
<Compile Include="Components\ResourceManagerClientHelper.cs" />
|
||||
<Compile Include="Components\TagsHelper.cs" />
|
||||
<Compile Include="Entities\Applications\ApplicationArtifact.cs" />
|
||||
<Compile Include="Entities\Applications\ApplicationArtifactType.cs" />
|
||||
<Compile Include="Entities\Applications\ApplicationArtifactName.cs" />
|
||||
<Compile Include="Entities\Applications\ApplicationKind.cs" />
|
||||
<Compile Include="Entities\Applications\ApplicationPackageSupportUrls.cs" />
|
||||
<Compile Include="Entities\Applications\ApplicationPackageCustomerSupport.cs" />
|
||||
<Compile Include="Entities\Applications\ApplicationProviderAuthorization.cs" />
|
||||
<Compile Include="Entities\Applications\ApplicationDefinition.cs" />
|
||||
<Compile Include="Entities\Applications\Application.cs" />
|
||||
<Compile Include="Entities\Applications\ApplicationDefinitionProperties.cs" />
|
||||
<Compile Include="Entities\Applications\ApplicationProperties.cs" />
|
||||
<Compile Include="Entities\Applications\ApplicationLockLevel.cs" />
|
||||
<Compile Include="Entities\Authorization\Permission.cs" />
|
||||
<Compile Include="Entities\ErrorResponses\ErrorResponseMessage.cs" />
|
||||
<Compile Include="Entities\ErrorResponses\ErrorResponseMessageException.cs" />
|
||||
<Compile Include="Entities\ErrorResponses\ExtendedErrorInfo.cs" />
|
||||
<Compile Include="Entities\Locks\Lock.cs" />
|
||||
<Compile Include="Entities\Locks\LockLevel.cs" />
|
||||
<Compile Include="Entities\Locks\LockProperties.cs" />
|
||||
<Compile Include="Entities\Operations\AzureAsyncOperationResource.cs" />
|
||||
<Compile Include="Entities\Policy\PolicyAssignment.cs" />
|
||||
<Compile Include="Entities\Policy\PolicyAssignmentProperties.cs" />
|
||||
<Compile Include="Entities\Policy\PolicyDefinitionMode.cs" />
|
||||
<Compile Include="Entities\Policy\PolicySetDefinition.cs" />
|
||||
<Compile Include="Entities\Policy\PolicyDefinition.cs" />
|
||||
<Compile Include="Entities\Policy\PolicySetDefinitionProperties.cs" />
|
||||
<Compile Include="Entities\Policy\PolicyDefinitionProperties.cs" />
|
||||
<Compile Include="Entities\Policy\PolicyRule.cs" />
|
||||
<Compile Include="Entities\Policy\PolicySku.cs" />
|
||||
<Compile Include="Entities\Providers\ResourceProviderDefinition.cs" />
|
||||
<Compile Include="Entities\Providers\ResourceTypeDefinition.cs" />
|
||||
<Compile Include="Entities\ProvisioningState\ProvisioningState.cs" />
|
||||
<Compile Include="Entities\ResourceGroup\ExportTemplateParameters.cs" />
|
||||
<Compile Include="Entities\ResourceGroup\ResourceBatchMoveParameters.cs" />
|
||||
<Compile Include="Entities\Resources\Resource.cs" />
|
||||
<Compile Include="Entities\Resources\ResourcePlan.cs" />
|
||||
<Compile Include="Entities\Resources\ResourceSku.cs" />
|
||||
<Compile Include="Entities\Resources\TerminalProvisioningStates.cs" />
|
||||
<Compile Include="Extensions\AsyncExtensions.cs" />
|
||||
<Compile Include="Extensions\ExceptionExtensions.cs" />
|
||||
<Compile Include="Extensions\HttpHeadersExtensions.cs" />
|
||||
<Compile Include="Extensions\HttpMessageExtensions.cs" />
|
||||
<Compile Include="Extensions\IEnumerableExtensions.cs" />
|
||||
<Compile Include="Extensions\JsonExtensions.cs" />
|
||||
<Compile Include="Extensions\ObjectExtensions.cs" />
|
||||
<Compile Include="Extensions\PsObjectExtensions.cs" />
|
||||
<Compile Include="Handlers\AuthenticationHandler.cs" />
|
||||
<Compile Include="Handlers\RetryHandler.cs" />
|
||||
<Compile Include="Handlers\TracingHandler.cs" />
|
||||
<Compile Include="Handlers\CmdletInfoHandler.cs" />
|
||||
<Compile Include="Handlers\UserAgentHandler.cs" />
|
||||
<Compile Include="Implementation\CmdletBase\ProviderFeatureCmdletBase.cs" />
|
||||
<Compile Include="Implementation\Features\GetAzureProviderFeatureCmdlet.cs" />
|
||||
<Compile Include="Implementation\Features\RegisterAzureProviderFeatureCmdlet.cs" />
|
||||
<Compile Include="Implementation\Locations\GetAzureLocationCmdlet.cs" />
|
||||
<Compile Include="Implementation\ManagedApplications\GetAzureManagedApplication.cs" />
|
||||
<Compile Include="Implementation\ManagedApplications\GetAzureManagedApplicationDefinition.cs" />
|
||||
<Compile Include="Implementation\ManagedApplications\RemoveAzureManagedApplication.cs" />
|
||||
<Compile Include="Implementation\ManagedApplications\RemoveAzureManagedApplicationDefinition.cs" />
|
||||
<Compile Include="Implementation\ManagedApplications\SetAzureManagedApplicationDefinition.cs" />
|
||||
<Compile Include="Implementation\ManagedApplications\SetAzureManagedApplication.cs" />
|
||||
<Compile Include="Implementation\ManagedApplications\NewAzureManagedApplicationDefinition.cs" />
|
||||
<Compile Include="Implementation\ManagedApplications\NewAzureManagedApplication.cs" />
|
||||
<Compile Include="Implementation\ManagedApplications\ManagedApplicationCmdletBase.cs" />
|
||||
<Compile Include="Implementation\Policy\GetAzurePolicySetDefinition.cs" />
|
||||
<Compile Include="Implementation\Policy\NewAzurePolicySetDefinition.cs" />
|
||||
<Compile Include="Implementation\Policy\PolicyCmdletBase.cs" />
|
||||
<Compile Include="Implementation\Policy\RemoveAzurePolicySetDefinition.cs" />
|
||||
<Compile Include="Implementation\Policy\SetAzurePolicySetDefinition.cs" />
|
||||
<Compile Include="Implementation\ResourceGroups\ExportAzureResourceGroupCmdlet.cs" />
|
||||
<Compile Include="Implementation\Providers\GetAzureProviderCmdlet.cs" />
|
||||
<Compile Include="Implementation\Providers\RegisterAzureProviderCmdlet.cs" />
|
||||
<Compile Include="Implementation\Providers\UnregisterAzureProviderCmdlet.cs" />
|
||||
<Compile Include="Implementation\ResourceGroupDeployments\GetAzureResourceGroupDeploymentCmdlet.cs" />
|
||||
<Compile Include="Implementation\ResourceGroupDeployments\NewAzureResourceGroupDeploymentCmdlet.cs" />
|
||||
<Compile Include="Implementation\ResourceGroupDeployments\RemoveAzureResourceGroupDeploymentCmdlet.cs" />
|
||||
<Compile Include="Implementation\ResourceGroupDeployments\StopAzureResourceGroupDeploymentCmdlet.cs" />
|
||||
<Compile Include="Implementation\ResourceGroupDeployments\TestAzureResourceGroupDeploymentCmdlet.cs" />
|
||||
<Compile Include="Implementation\ResourceGroups\RemoveAzureResourceGroupCmdlet.cs" />
|
||||
<Compile Include="Implementation\ResourceGroups\SetAzureResourceGroupCmdlet.cs" />
|
||||
<Compile Include="Implementation\ResourceGroups\NewAzureResourceGroupCmdlet.cs" />
|
||||
<Compile Include="Implementation\ResourceGroups\GetAzureResourceGroupCmdlet.cs" />
|
||||
<Compile Include="Implementation\CmdletBase\ResourceWithParameterCmdletBase.cs" />
|
||||
<Compile Include="Implementation\ResourceGroupDeployments\SaveAzureResourceGroupDeploymentTemplateCmdlet.cs" />
|
||||
<Compile Include="Implementation\ResourceGroupDeployments\GetAzureResourceGroupDeploymentOperationCmdlet.cs" />
|
||||
<Compile Include="Implementation\Lock\GetAzureResourceLockCmdlet.cs" />
|
||||
<Compile Include="Implementation\Resource\InvokeAzureResourceActionCmdlet.cs" />
|
||||
<Compile Include="Implementation\Resource\MoveAzureResourceCmdlet.cs" />
|
||||
<Compile Include="Implementation\Lock\NewAzureResourceLockCmdlet.cs" />
|
||||
<Compile Include="Implementation\Policy\GetAzurePolicyAssignment.cs" />
|
||||
<Compile Include="Implementation\Policy\GetAzurePolicyDefinition.cs" />
|
||||
<Compile Include="Implementation\Policy\NewAzurePolicyAssignment.cs" />
|
||||
<Compile Include="Implementation\Policy\NewAzurePolicyDefinition.cs" />
|
||||
<Compile Include="Implementation\Policy\RemoveAzurePolicyAssignment.cs" />
|
||||
<Compile Include="Implementation\Policy\RemoveAzurePolicyDefinition.cs" />
|
||||
<Compile Include="Implementation\Policy\SetAzurePolicyAssignment.cs" />
|
||||
<Compile Include="Implementation\Policy\SetAzurePolicyDefinition.cs" />
|
||||
<Compile Include="Implementation\Resource\RemoveAzureResourceCmdlet.cs" />
|
||||
<Compile Include="Implementation\Lock\RemoveAzureResourceLockCmdlet.cs" />
|
||||
<Compile Include="Implementation\Lock\ResourceLockManagementCmdletBase.cs" />
|
||||
<Compile Include="Implementation\Resource\SetAzureResourceCmdlet.cs" />
|
||||
<Compile Include="Implementation\Resource\NewAzureResourceCmdlet.cs" />
|
||||
<Compile Include="Implementation\CmdletBase\ResourceManipulationCmdletBase.cs" />
|
||||
<Compile Include="Components\ApiVersionHelper.cs" />
|
||||
<Compile Include="Extensions\ErrorResponseMessageExceptionExtensions.cs" />
|
||||
<Compile Include="Components\LongRunningOperationHelper.cs" />
|
||||
<Compile Include="Extensions\ResourceExtensions.cs" />
|
||||
<Compile Include="Extensions\JTokenExtensions.cs" />
|
||||
<Compile Include="Implementation\CmdletBase\ResourceManagerCmdletBase.cs" />
|
||||
<Compile Include="Implementation\Lock\SetAzureResourceLockCmdlet.cs" />
|
||||
<Compile Include="Json\CamelCasePropertyNamesWithOverridesContractResolver.cs" />
|
||||
<Compile Include="Json\JsonPreserveCaseDictionaryAttribute.cs" />
|
||||
<Compile Include="Json\TimeSpanConverter.cs" />
|
||||
<Compile Include="SdkClient\ProviderFeatureClient.cs" />
|
||||
<Compile Include="SdkClient\SubscriptionSdkClient.cs" />
|
||||
<Compile Include="SdkModels\Deployments\PSCreateResourceGroupDeploymentParameters.cs" />
|
||||
<Compile Include="SdkModels\Deployments\DeploymentVariable.cs" />
|
||||
<Compile Include="SdkModels\Deployments\FilterResourceGroupDeploymentOptions.cs" />
|
||||
<Compile Include="SdkModels\Deployments\PSResourceGroupDeployment.cs" />
|
||||
<Compile Include="SdkModels\Deployments\TemplateFile.cs" />
|
||||
<Compile Include="SdkModels\Deployments\TemplateFileParameterV1.cs" />
|
||||
<Compile Include="SdkModels\Deployments\TemplateFileParameterv2.cs" />
|
||||
<Compile Include="SdkModels\Deployments\TemplateFileResource.cs" />
|
||||
<Compile Include="SdkModels\Deployments\TemplateValidationInfo.cs" />
|
||||
<Compile Include="SdkModels\Deployments\PSValidateResourceGroupDeploymentParameters.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Implementation\Resource\GetAzureResourceCmdlet.cs" />
|
||||
<Compile Include="Properties\Resources.Designer.cs">
|
||||
<DependentUpon>Resources.resx</DependentUpon>
|
||||
<AutoGen>True</AutoGen>
|
||||
<DesignTime>True</DesignTime>
|
||||
</Compile>
|
||||
<Compile Include="RestClients\ResourceManagerRestClientBase.cs" />
|
||||
<Compile Include="RestClients\ResourceManagerRestRestClient.cs" />
|
||||
<Compile Include="SdkClient\ResourceManagerSdkClient.cs" />
|
||||
<Compile Include="SdkExtensions\ResourcesExtensions.cs" />
|
||||
<Compile Include="SdkModels\Errors\PSResourceManagerError.cs" />
|
||||
<Compile Include="SdkModels\Features\PSProviderFeature.cs" />
|
||||
<Compile Include="SdkModels\Locations\PSResourceProviderLocation.cs" />
|
||||
<Compile Include="SdkModels\ResourceGroups\PSCreateResourceGroupParameters.cs" />
|
||||
<Compile Include="SdkModels\ResourceGroups\PSResourceGroup.cs" />
|
||||
<Compile Include="SdkModels\ResourceGroups\PSUpdateResourceGroupParameters.cs" />
|
||||
<Compile Include="SdkModels\ResourceProvider\PSResourceProvider.cs" />
|
||||
<Compile Include="SdkModels\ResourceProvider\PSResourceProviderResourceType.cs" />
|
||||
<Compile Include="Components\ResourceIdentifier.cs" />
|
||||
<Compile Include="SdkModels\Resources\PSResource.cs" />
|
||||
<Compile Include="Utilities\FileUtility.cs" />
|
||||
<Compile Include="Utilities\HttpUtility.cs" />
|
||||
<Compile Include="Utilities\TemplateUtility.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="Microsoft.Azure.Commands.ResourceManager.Cmdlets.dll-Help.xml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="..\..\Commands.Resources\AzureRM.Resources.psd1">
|
||||
<Link>AzureRM.Resources.psd1</Link>
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<Content Include="Microsoft.Azure.Commands.ResourceManager.Cmdlets.format.ps1xml">
|
||||
<SubType>Designer</SubType>
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</Content>
|
||||
<Content Include="Microsoft.Azure.Commands.ResourceManager.Cmdlets.Types.ps1xml">
|
||||
<SubType>Designer</SubType>
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</Content>
|
||||
<None Include="MSSharedLibKey.snk" />
|
||||
<None Include="packages.config">
|
||||
<SubType>Designer</SubType>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
<!-- <ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\Common\Commands.Common.Authentication.Abstractions\Commands.Common.Authentication.Abstractions.csproj">
|
||||
<Project>{70527617-7598-4aef-b5bd-db9186b8184b}</Project>
|
||||
<Name>Commands.Common.Authentication.Abstractions</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\..\..\..\Common\Commands.Common\Commands.Common.csproj">
|
||||
<Project>{5ee72c53-1720-4309-b54b-5fb79703195f}</Project>
|
||||
<Name>Commands.Common</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\..\..\..\Common\Commands.ResourceManager.Common\Commands.ResourceManager.Common.csproj">
|
||||
<Project>{3819d8a7-c62c-4c47-8ddd-0332d9ce1252}</Project>
|
||||
<Name>Commands.ResourceManager.Common</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup> -->
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Properties\Resources.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
||||
<SubType>Designer</SubType>
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
<ItemGroup />
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
</Project>
|
|
@ -0,0 +1,234 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
using Microsoft.Azure.Commands.Common.Authentication.Models;
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components
|
||||
{
|
||||
using Commands.Common.Authentication.Abstractions;
|
||||
using Entities.Providers;
|
||||
using Extensions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Common;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#if !NETSTANDARD
|
||||
using System.Runtime.Caching;
|
||||
#else
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Helper class for determining the API version
|
||||
/// </summary>
|
||||
internal static class ApiVersionHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Determines the API version.
|
||||
/// </summary>
|
||||
/// <param name="context">The azure profile.</param>
|
||||
/// <param name="resourceId">The resource Id.</param>
|
||||
/// <param name="cancellationToken">The cancellation token</param>
|
||||
/// <param name="pre">When specified, indicates if pre-release API versions should be considered.</param>
|
||||
internal static Task<string> DetermineApiVersion(IAzureContext context, string resourceId, CancellationToken cancellationToken, bool? pre = null, Dictionary<string, string> cmdletHeaderValues = null)
|
||||
{
|
||||
var providerNamespace = ResourceIdUtility.GetExtensionProviderNamespace(resourceId)
|
||||
?? ResourceIdUtility.GetProviderNamespace(resourceId);
|
||||
|
||||
var resourceType = ResourceIdUtility.GetExtensionResourceType(resourceId: resourceId, includeProviderNamespace: false)
|
||||
?? ResourceIdUtility.GetResourceType(resourceId: resourceId, includeProviderNamespace: false);
|
||||
|
||||
return ApiVersionHelper.DetermineApiVersion(context: context, providerNamespace: providerNamespace, resourceType: resourceType, cancellationToken: cancellationToken, pre: pre, cmdletHeaderValues: cmdletHeaderValues);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines the API version.
|
||||
/// </summary>
|
||||
/// <param name="context">The azure profile.</param>
|
||||
/// <param name="providerNamespace">The provider namespace.</param>
|
||||
/// <param name="resourceType">The resource type.</param>
|
||||
/// <param name="cancellationToken">The cancellation token</param>
|
||||
/// <param name="pre">When specified, indicates if pre-release API versions should be considered.</param>
|
||||
internal static Task<string> DetermineApiVersion(IAzureContext context, string providerNamespace, string resourceType, CancellationToken cancellationToken, bool? pre = null, Dictionary<string, string> cmdletHeaderValues = null)
|
||||
{
|
||||
var cacheKey = ApiVersionCache.GetCacheKey(context.Environment.Name, providerNamespace: providerNamespace, resourceType: resourceType);
|
||||
var apiVersions = ApiVersionCache.Instance
|
||||
.AddOrGetExisting(cacheKey: cacheKey, getFreshData: () => ApiVersionHelper.GetApiVersionsForResourceType(
|
||||
context,
|
||||
providerNamespace: providerNamespace,
|
||||
resourceType: resourceType,
|
||||
cancellationToken: cancellationToken,
|
||||
cmdletHeaderValues: cmdletHeaderValues));
|
||||
|
||||
apiVersions = apiVersions.CoalesceEnumerable().ToArray();
|
||||
var apiVersionsToSelectFrom = apiVersions;
|
||||
if (pre == null || pre == false)
|
||||
{
|
||||
apiVersionsToSelectFrom = apiVersions
|
||||
.Where(apiVersion => apiVersion.IsDecimal(NumberStyles.AllowDecimalPoint) || apiVersion.IsDateTime("yyyy-mm-dd", DateTimeStyles.None))
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
var selectedApiVersion = apiVersionsToSelectFrom.OrderByDescending(apiVersion => apiVersion).FirstOrDefault();
|
||||
if (string.IsNullOrWhiteSpace(selectedApiVersion) && apiVersions.Any())
|
||||
{
|
||||
// fall back on pre-release APIs if they're the only ones available.
|
||||
selectedApiVersion = apiVersions.OrderByDescending(apiVersion => apiVersion).FirstOrDefault();
|
||||
}
|
||||
|
||||
var result = string.IsNullOrWhiteSpace(selectedApiVersion)
|
||||
? Constants.DefaultApiVersion
|
||||
: selectedApiVersion;
|
||||
|
||||
return Task.FromResult(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines the list of api versions currently supported by the RP.
|
||||
/// </summary>
|
||||
/// <param name="context">The azure profile.</param>
|
||||
/// <param name="providerNamespace">The provider namespace.</param>
|
||||
/// <param name="resourceType">The resource type.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
private static string[] GetApiVersionsForResourceType(IAzureContext context, string providerNamespace, string resourceType, CancellationToken cancellationToken, Dictionary<string, string> cmdletHeaderValues = null)
|
||||
{
|
||||
var resourceManagerClient = ResourceManagerClientHelper.GetResourceManagerClient(context, cmdletHeaderValues);
|
||||
|
||||
var defaultSubscription = context.Subscription;
|
||||
|
||||
var resourceCollectionId = defaultSubscription == null
|
||||
? "/providers"
|
||||
: string.Format("/subscriptions/{0}/providers", defaultSubscription.Id);
|
||||
|
||||
var providers = PaginatedResponseHelper.Enumerate(
|
||||
getFirstPage: () => resourceManagerClient
|
||||
.ListObjectColleciton<ResourceProviderDefinition>(
|
||||
resourceCollectionId: resourceCollectionId,
|
||||
apiVersion: Constants.ProvidersApiVersion,
|
||||
cancellationToken: cancellationToken),
|
||||
getNextPage: nextLink => resourceManagerClient
|
||||
.ListNextBatch<ResourceProviderDefinition>(
|
||||
nextLink: nextLink,
|
||||
cancellationToken: cancellationToken),
|
||||
cancellationToken: cancellationToken);
|
||||
|
||||
return providers
|
||||
.CoalesceEnumerable()
|
||||
.Where(provider => providerNamespace.EqualsInsensitively(provider.Namespace))
|
||||
.SelectMany(provider => provider.ResourceTypes)
|
||||
.Where(type => resourceType.EqualsInsensitively(type.ResourceType))
|
||||
.Select(type => type.ApiVersions)
|
||||
.FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A singleton instance of the <see cref="ApiVersionCache"/>
|
||||
/// </summary>
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Instances of this type are meant to be singletons.")]
|
||||
private class ApiVersionCache
|
||||
{
|
||||
private static MemoryCache _cache;
|
||||
|
||||
static ApiVersionCache()
|
||||
{
|
||||
#if !NETSTANDARD
|
||||
_cache = MemoryCache.Default;
|
||||
#else
|
||||
_cache = new MemoryCache(new MemoryCacheOptions());
|
||||
#endif
|
||||
}
|
||||
/// <summary>
|
||||
/// The API version cache
|
||||
/// </summary>
|
||||
internal static readonly ApiVersionCache Instance = new ApiVersionCache(TimeSpan.FromHours(1));
|
||||
|
||||
/// <summary>
|
||||
/// The cache data expiration time
|
||||
/// </summary>
|
||||
internal TimeSpan CacheDataExpirationTime { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ApiVersionCache" /> class.
|
||||
/// </summary>
|
||||
/// <param name="cacheDataExpirationTime">The polling interval.</param>
|
||||
private ApiVersionCache(TimeSpan cacheDataExpirationTime)
|
||||
{
|
||||
this.CacheDataExpirationTime = cacheDataExpirationTime;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds or gets existing data from cache.
|
||||
/// </summary>
|
||||
/// <param name="cacheKey">The cache key.</param>
|
||||
/// <param name="getFreshData">The delegate used to get data if cache is empty or stale.</param>
|
||||
internal string[] AddOrGetExisting(string cacheKey, Func<string[]> getFreshData)
|
||||
{
|
||||
cacheKey = cacheKey.ToUpperInvariant();
|
||||
|
||||
var cacheItem = this.GetCacheItem(cacheKey: cacheKey);
|
||||
|
||||
if (cacheItem == null)
|
||||
{
|
||||
var expirationTime = DateTime.UtcNow.Add(this.CacheDataExpirationTime);
|
||||
|
||||
cacheItem = getFreshData();
|
||||
|
||||
if (cacheItem != null)
|
||||
{
|
||||
this.SetCacheItem(
|
||||
cacheKey: cacheKey,
|
||||
data: cacheItem,
|
||||
absoluteExpirationTime: expirationTime);
|
||||
}
|
||||
}
|
||||
|
||||
return cacheItem;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the cache entry.
|
||||
/// </summary>
|
||||
/// <param name="cacheKey">The cache key.</param>
|
||||
private string[] GetCacheItem(string cacheKey)
|
||||
{
|
||||
return _cache.Get(cacheKey).Cast<string[]>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the cache entry.
|
||||
/// </summary>
|
||||
/// <param name="cacheKey">The cache key.</param>
|
||||
/// <param name="data">The data to add.</param>
|
||||
/// <param name="absoluteExpirationTime">The absolute expiration time.</param>
|
||||
private void SetCacheItem(string cacheKey, string[] data, DateTimeOffset absoluteExpirationTime)
|
||||
{
|
||||
_cache.Set(key: cacheKey, value: data, absoluteExpiration: absoluteExpirationTime);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the cache key.
|
||||
/// </summary>
|
||||
/// <param name="environmentName">The environment name.</param>
|
||||
/// <param name="providerNamespace">The provider namespace.</param>
|
||||
/// <param name="resourceType">The resource type.</param>
|
||||
internal static string GetCacheKey(string environmentName, string providerNamespace, string resourceType)
|
||||
{
|
||||
return string.Format("{0}/{1}/{2}", environmentName.CoalesceEnumerable(), providerNamespace.CoalesceString(), resourceType.CoalesceString()).ToUpperInvariant();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,157 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components
|
||||
{
|
||||
/// <summary>
|
||||
/// Class for holding constants
|
||||
/// </summary>
|
||||
public static class Constants
|
||||
{
|
||||
/// <summary>
|
||||
/// The <c>Microsoft.Resource</c> namespace.
|
||||
/// </summary>
|
||||
public static readonly string MicrosoftResourceNamesapce = "Microsoft.Resources";
|
||||
|
||||
/// <summary>
|
||||
/// The <c>Microsoft.Authorization</c> namespace.
|
||||
/// </summary>
|
||||
public static readonly string MicrosoftAuthorizationNamespace = "Microsoft.Authorization";
|
||||
|
||||
/// <summary>
|
||||
/// The <c>Microsoft.Solutions</c> namespace.
|
||||
/// </summary>
|
||||
public static readonly string MicrosoftSolutionNamespace = "Microsoft.Solutions";
|
||||
|
||||
/// <summary>
|
||||
/// The string literal <c>ResourceGroups</c>
|
||||
/// </summary>
|
||||
public static readonly string ResourceGroups = "ResourceGroups";
|
||||
|
||||
/// <summary>
|
||||
/// The string literal <c>Providers</c>
|
||||
/// </summary>
|
||||
public static readonly string Providers = "Providers";
|
||||
|
||||
/// <summary>
|
||||
/// The string literal <c>Subscriptions</c>
|
||||
/// </summary>
|
||||
public static readonly string Subscriptions = "Subscriptions";
|
||||
|
||||
/// <summary>
|
||||
/// The string literal <c>Location</c>
|
||||
/// </summary>
|
||||
public static readonly string Location = "Location";
|
||||
|
||||
/// <summary>
|
||||
/// The default API version.
|
||||
/// </summary>
|
||||
public static readonly string DefaultApiVersion = "2015-01-01";
|
||||
|
||||
/// <summary>
|
||||
/// The default appliction API version.
|
||||
/// </summary>
|
||||
public static readonly string ApplicationApiVersion = "2017-09-01";
|
||||
|
||||
/// <summary>
|
||||
/// The default resources API version.
|
||||
/// </summary>
|
||||
public static readonly string ResourcesApiVersion = "2016-09-01";
|
||||
|
||||
/// <summary>
|
||||
/// The default policy definition API version.
|
||||
/// </summary>
|
||||
public static readonly string PolicyDefinitionApiVersion = "2016-12-01";
|
||||
|
||||
/// <summary>
|
||||
/// The default policy set definition API version.
|
||||
/// </summary>
|
||||
public static readonly string PolicySetDefintionApiVersion = "2017-06-01-preview";
|
||||
|
||||
/// <summary>
|
||||
/// The default policy assignment API version.
|
||||
/// </summary>
|
||||
public static readonly string PolicyAssignmentApiVersion = "2017-06-01-preview";
|
||||
|
||||
/// <summary>
|
||||
/// The default providers API version.
|
||||
/// </summary>
|
||||
public static readonly string ProvidersApiVersion = "2016-07-01";
|
||||
|
||||
/// <summary>
|
||||
/// The default Lock API version.
|
||||
/// </summary>
|
||||
public static readonly string LockApiVersion = "2015-01-01";
|
||||
|
||||
/// <summary>
|
||||
/// The default deployment operation API version.
|
||||
/// </summary>
|
||||
public static readonly string DeploymentOperationApiVersion = "2016-02-01";
|
||||
|
||||
/// <summary>
|
||||
/// The move action.
|
||||
/// </summary>
|
||||
public static readonly string MoveResources = "moveResources";
|
||||
|
||||
/// <summary>
|
||||
/// The export action.
|
||||
/// </summary>
|
||||
public static readonly string ExportTemplate = "exportTemplate";
|
||||
|
||||
/// <summary>
|
||||
/// The locks resource type.
|
||||
/// </summary>
|
||||
public static readonly string MicrosoftAuthorizationLocksType = "Microsoft.Authorization/locks";
|
||||
|
||||
/// <summary>
|
||||
/// The deployment operations resource type.
|
||||
/// </summary>
|
||||
public static readonly string MicrosoftResourcesDeploymentOperationsType = Constants.MicrosoftResourceNamesapce + "/deployments/operations";
|
||||
|
||||
/// <summary>
|
||||
/// The deployments resource type.
|
||||
/// </summary>
|
||||
public static readonly string MicrosoftResourcesDeploymentType = Constants.MicrosoftResourceNamesapce + "/deployments";
|
||||
|
||||
/// <summary>
|
||||
/// The policy definition resource type.
|
||||
/// </summary>
|
||||
public static readonly string MicrosoftAuthorizationPolicyDefinitionType = Constants.MicrosoftAuthorizationNamespace + "/policydefinitions";
|
||||
|
||||
/// <summary>
|
||||
/// The policy set definition resource type.
|
||||
/// </summary>
|
||||
public static readonly string MicrosoftAuthorizationPolicySetDefinitionType = Constants.MicrosoftAuthorizationNamespace + "/policysetdefinitions";
|
||||
|
||||
/// <summary>
|
||||
/// The policy definition resource type.
|
||||
/// </summary>
|
||||
public static readonly string MicrosoftAuthorizationPolicyAssignmentType = Constants.MicrosoftAuthorizationNamespace + "/policyassignments";
|
||||
|
||||
/// <summary>
|
||||
/// The application definition resource type.
|
||||
/// </summary>
|
||||
public static readonly string MicrosoftApplicationDefinitionType = Constants.MicrosoftSolutionNamespace + "/applicationdefinitions";
|
||||
|
||||
/// <summary>
|
||||
/// The application resource type.
|
||||
/// </summary>
|
||||
public static readonly string MicrosoftApplicationType = Constants.MicrosoftSolutionNamespace + "/applications";
|
||||
|
||||
/// <summary>
|
||||
/// The type name of the generic resource.
|
||||
/// </summary>
|
||||
public static readonly string MicrosoftAzureResource = "Microsoft.Azure.Resource";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,82 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Handlers;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
|
||||
/// <summary>
|
||||
/// Factory class for creating <see cref="HttpClient"/> objects with custom headers.
|
||||
/// </summary>
|
||||
public abstract class HttpClientHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// The subscription cloud credentials.
|
||||
/// </summary>
|
||||
private readonly SubscriptionCloudCredentials credentials;
|
||||
|
||||
/// <summary>
|
||||
/// The header values.
|
||||
/// </summary>
|
||||
private readonly IEnumerable<ProductInfoHeaderValue> headerValues;
|
||||
|
||||
/// <summary>
|
||||
/// The cmdlet info header values.
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, string> cmdletHeaderValues;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HttpClientHelper"/> class.
|
||||
/// </summary>
|
||||
/// <param name="credentials">The subscription cloud credentials.</param>
|
||||
/// <param name="headerValues">The header values.</param>
|
||||
protected HttpClientHelper(SubscriptionCloudCredentials credentials, IEnumerable<ProductInfoHeaderValue> headerValues, Dictionary<string, string> cmdletHeaderValues)
|
||||
{
|
||||
this.credentials = credentials;
|
||||
this.headerValues = headerValues;
|
||||
this.cmdletHeaderValues = cmdletHeaderValues;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an <see cref="HttpClient"/>
|
||||
/// </summary>
|
||||
/// <param name="primaryHandlers">The handlers that will be added to the top of the chain.</param>
|
||||
public virtual HttpClient CreateHttpClient(params DelegatingHandler[] primaryHandlers)
|
||||
{
|
||||
var delegateHandlers = new DelegatingHandler[]
|
||||
{
|
||||
new AuthenticationHandler(cloudCredentials: credentials),
|
||||
new UserAgentHandler(headerValues: headerValues),
|
||||
new CmdletInfoHandler(cmdletHeaderValues: cmdletHeaderValues),
|
||||
new TracingHandler(),
|
||||
new RetryHandler(),
|
||||
};
|
||||
|
||||
var pipeline = (HttpMessageHandler)(new HttpClientHandler());
|
||||
var reversedHandlers = primaryHandlers.CoalesceEnumerable().Concat(delegateHandlers).ToArray().Reverse();
|
||||
foreach (var handler in reversedHandlers)
|
||||
{
|
||||
handler.InnerHandler = pipeline;
|
||||
pipeline = handler;
|
||||
}
|
||||
|
||||
return new HttpClient(pipeline);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http.Headers;
|
||||
|
||||
/// <summary>
|
||||
/// Factory class for creating http client helpers.
|
||||
/// </summary>
|
||||
public class HttpClientHelperFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets an instance of the facotry.
|
||||
/// </summary>
|
||||
public static HttpClientHelperFactory Instance { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes static members of the <see cref="HttpClientHelperFactory"/> class.
|
||||
/// </summary>
|
||||
static HttpClientHelperFactory()
|
||||
{
|
||||
HttpClientHelperFactory.Instance = new HttpClientHelperFactory();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HttpClientHelperFactory"/> class.
|
||||
/// </summary>
|
||||
protected HttpClientHelperFactory()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates new instances of the <see cref="HttpClientHelper"/> class.
|
||||
/// </summary>
|
||||
/// <param name="credentials">The credentials.</param>
|
||||
/// <param name="headerValues">The headers.</param>
|
||||
public virtual HttpClientHelper CreateHttpClientHelper(SubscriptionCloudCredentials credentials, IEnumerable<ProductInfoHeaderValue> headerValues, Dictionary<string, string> cmdletHeaderValues)
|
||||
{
|
||||
return new HttpClientHelperImpl(credentials: credentials, headerValues: headerValues, cmdletHeaderValues: cmdletHeaderValues);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An implementation of the <see cref="HttpClientHelper"/> abstract class.
|
||||
/// </summary>
|
||||
private class HttpClientHelperImpl : HttpClientHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes new instances of the <see cref="HttpClientHelperImpl"/> class.
|
||||
/// </summary>
|
||||
/// <param name="credentials">The credentials.</param>
|
||||
/// <param name="headerValues">The headers.</param>
|
||||
public HttpClientHelperImpl(SubscriptionCloudCredentials credentials, IEnumerable<ProductInfoHeaderValue> headerValues, Dictionary<string, string> cmdletHeaderValues)
|
||||
: base(credentials: credentials, headerValues: headerValues, cmdletHeaderValues: cmdletHeaderValues)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components
|
||||
{
|
||||
using System.Net.Http;
|
||||
|
||||
/// <summary>
|
||||
/// Extra http methods.
|
||||
/// </summary>
|
||||
public class HttpMethodExt
|
||||
{
|
||||
/// <summary>
|
||||
/// The PATCH method.
|
||||
/// </summary>
|
||||
public static readonly HttpMethod Patch = new HttpMethod("PATCH");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components
|
||||
{
|
||||
using System.Net;
|
||||
|
||||
/// <summary>
|
||||
/// Extended status codes.
|
||||
/// </summary>
|
||||
public static class HttpStatusCodeExt
|
||||
{
|
||||
/// <summary>
|
||||
/// Http Status code for too many requests
|
||||
/// </summary>
|
||||
public static readonly HttpStatusCode TooManyRequests = (HttpStatusCode)429;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,517 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components
|
||||
{
|
||||
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Collections;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.RestClients;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Utilities;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Management.Automation;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// A helper class for tracking long running operations.
|
||||
/// </summary>
|
||||
internal class LongRunningOperationHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// The default retry after interval.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan DefaultRetryAfter = TimeSpan.FromSeconds(60);
|
||||
|
||||
/// <summary>
|
||||
/// A delegate for fetching the resources client.
|
||||
/// </summary>
|
||||
private Func<ResourceManagerRestRestClient> ResourcesClientFactory { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The cancellation token.
|
||||
/// </summary>
|
||||
private CancellationToken CancellationToken { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The progress tracker.
|
||||
/// </summary>
|
||||
private ProgressTracker ProgressTrackerObject { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// A value indicating if this is a resource create.
|
||||
/// </summary>
|
||||
private bool IsResourceCreateOrUpdate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LongRunningOperationHelper"/> class.
|
||||
/// </summary>
|
||||
/// <param name="activityName">The name of the activity to report in progress.</param>
|
||||
/// <param name="resourcesClientFactory">A delegate for fetching the resources client/</param>
|
||||
/// <param name="writeProgressAction">A delegate for writing progress.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <param name="isResourceCreateOrUpdate">Set to true if this tracker will be used to track a resource creation.</param>
|
||||
internal LongRunningOperationHelper(string activityName, Func<ResourceManagerRestRestClient> resourcesClientFactory, Action<ProgressRecord> writeProgressAction, CancellationToken cancellationToken, bool isResourceCreateOrUpdate)
|
||||
{
|
||||
this.ResourcesClientFactory = resourcesClientFactory;
|
||||
this.CancellationToken = cancellationToken;
|
||||
this.ProgressTrackerObject = new ProgressTracker(activityName, resourcesClientFactory, writeProgressAction, cancellationToken);
|
||||
this.IsResourceCreateOrUpdate = isResourceCreateOrUpdate;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for the operation to complete.
|
||||
/// </summary>
|
||||
/// <param name="operationResult">The operation result.</param>
|
||||
internal string WaitOnOperation(OperationResult operationResult)
|
||||
{
|
||||
// TODO: Re-factor this mess.
|
||||
this.ProgressTrackerObject.UpdateProgress("Starting", 0);
|
||||
|
||||
var trackingResult = this.HandleOperationResponse(operationResult, this.IsResourceCreateOrUpdate ? operationResult.OperationUri : operationResult.LocationUri);
|
||||
|
||||
while (trackingResult != null && trackingResult.ShouldWait)
|
||||
{
|
||||
operationResult =
|
||||
this.GetResourcesClient()
|
||||
.GetOperationResult<JToken>(trackingResult.TrackingUri, this.CancellationToken)
|
||||
.Result;
|
||||
|
||||
trackingResult = this.HandleOperationResponse(operationResult, trackingResult.TrackingUri);
|
||||
|
||||
if (trackingResult.ShouldWait && trackingResult.RetryAfter != null)
|
||||
{
|
||||
Task.Delay(delay: trackingResult.RetryAfter.Value, cancellationToken: this.CancellationToken).Wait(cancellationToken: this.CancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
this.ProgressTrackerObject.UpdateProgress("Complete", 100);
|
||||
|
||||
return operationResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the operation response/
|
||||
/// </summary>
|
||||
/// <param name="operationResult">The result of the operation.</param>
|
||||
/// <param name="lastRequestUri">The last <see cref="Uri"/> that was used to request operation state.</param>
|
||||
private TrackingOperationResult HandleOperationResponse(OperationResult operationResult, Uri lastRequestUri)
|
||||
{
|
||||
if (!operationResult.HttpStatusCode.IsSuccessfulRequest())
|
||||
{
|
||||
if (operationResult.HttpStatusCode.IsServerFailureRequest() ||
|
||||
operationResult.HttpStatusCode == HttpStatusCodeExt.TooManyRequests)
|
||||
{
|
||||
var result = new TrackingOperationResult
|
||||
{
|
||||
ShouldWait = true,
|
||||
Failed = false,
|
||||
RetryAfter = operationResult.RetryAfter ?? LongRunningOperationHelper.DefaultRetryAfter,
|
||||
TrackingUri = lastRequestUri,
|
||||
OperationResult = operationResult,
|
||||
};
|
||||
|
||||
this.UpdateProgress(result);
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.FailedResult(
|
||||
operationResult,
|
||||
string.Format("The operation failed because the resource provider returned an unexpected HTTP status code of: '{0}'.", (int)operationResult.HttpStatusCode));
|
||||
}
|
||||
}
|
||||
|
||||
if (operationResult.HttpStatusCode == HttpStatusCode.Accepted)
|
||||
{
|
||||
return this.WaitResult(operationResult);
|
||||
}
|
||||
|
||||
if (operationResult.HttpStatusCode != HttpStatusCode.OK &&
|
||||
operationResult.HttpStatusCode != HttpStatusCode.Created &&
|
||||
(!this.IsResourceCreateOrUpdate && operationResult.HttpStatusCode != HttpStatusCode.NoContent))
|
||||
{
|
||||
this.FailedResult(
|
||||
operationResult,
|
||||
string.Format("The operation failed because the resource provider returned an unexpected HTTP status code of: '{0}'.", (int)operationResult.HttpStatusCode));
|
||||
}
|
||||
|
||||
return this.IsResourceCreateOrUpdate
|
||||
? this.HandleCreateOrUpdateResponse(operationResult)
|
||||
: this.SuccessfulResult(operationResult);
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extra code for handling resource create/update calls.
|
||||
/// </summary>
|
||||
/// <param name="operationResult">The result of the operation.</param>
|
||||
private TrackingOperationResult HandleCreateOrUpdateResponse(OperationResult operationResult)
|
||||
{
|
||||
Resource<InsensitiveDictionary<JToken>> resource;
|
||||
if (!operationResult.Value.TryConvertTo<Resource<InsensitiveDictionary<JToken>>>(out resource))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (resource == null && operationResult.HttpStatusCode == HttpStatusCode.Created)
|
||||
{
|
||||
return this.SuccessfulResult(operationResult);
|
||||
}
|
||||
|
||||
if (resource == null)
|
||||
{
|
||||
this.FailedResult(
|
||||
operationResult,
|
||||
"The operation failed because resource could not be de-serialized.");
|
||||
}
|
||||
|
||||
resource.Properties = resource.Properties ?? new InsensitiveDictionary<JToken>();
|
||||
|
||||
JToken provisioningStateJToken;
|
||||
if (resource.Properties.TryGetValue("provisioningState", out provisioningStateJToken))
|
||||
{
|
||||
TerminalProvisioningStates resourceProvisioningState;
|
||||
if (Enum.TryParse(value: provisioningStateJToken.ToString(), ignoreCase: true, result: out resourceProvisioningState))
|
||||
{
|
||||
if (resourceProvisioningState == TerminalProvisioningStates.Succeeded ||
|
||||
resourceProvisioningState == TerminalProvisioningStates.Ready)
|
||||
{
|
||||
return this.SuccessfulResult(operationResult);
|
||||
}
|
||||
|
||||
if (resourceProvisioningState == TerminalProvisioningStates.Failed ||
|
||||
resourceProvisioningState == TerminalProvisioningStates.Canceled)
|
||||
{
|
||||
this.FailedResult(
|
||||
operationResult,
|
||||
string.Format("The operation failed because resource is in the: '{0}' state. Please check the logs for more details.", provisioningStateJToken));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return this.WaitResult(operationResult);
|
||||
}
|
||||
}
|
||||
|
||||
return this.SuccessfulResult(operationResult);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates a successful terminal state.
|
||||
/// </summary>
|
||||
/// <param name="operationResult">The result of the operation.</param>
|
||||
private TrackingOperationResult SuccessfulResult(OperationResult operationResult)
|
||||
{
|
||||
var result = new TrackingOperationResult
|
||||
{
|
||||
ShouldWait = false,
|
||||
Failed = false,
|
||||
RetryAfter = operationResult.RetryAfter ?? LongRunningOperationHelper.DefaultRetryAfter,
|
||||
TrackingUri = operationResult.LocationUri ?? operationResult.OperationUri,
|
||||
OperationResult = operationResult,
|
||||
};
|
||||
|
||||
this.UpdateProgress(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates an in-progress state.
|
||||
/// </summary>
|
||||
/// <param name="operationResult">The result of the operation.</param>
|
||||
private TrackingOperationResult WaitResult(OperationResult operationResult)
|
||||
{
|
||||
var result = new TrackingOperationResult
|
||||
{
|
||||
ShouldWait = true,
|
||||
Failed = false,
|
||||
RetryAfter = operationResult.RetryAfter ?? LongRunningOperationHelper.DefaultRetryAfter,
|
||||
TrackingUri = operationResult.LocationUri ?? operationResult.OperationUri,
|
||||
OperationResult = operationResult,
|
||||
};
|
||||
|
||||
this.UpdateProgress(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates a failed terminal state.
|
||||
/// </summary>
|
||||
/// <param name="operationResult">The result of the operation.</param>
|
||||
/// <param name="message">The exception message.</param>
|
||||
private void FailedResult(OperationResult operationResult, string message)
|
||||
{
|
||||
var result = new TrackingOperationResult
|
||||
{
|
||||
ShouldWait = false,
|
||||
Failed = true,
|
||||
RetryAfter = operationResult.RetryAfter ?? LongRunningOperationHelper.DefaultRetryAfter,
|
||||
TrackingUri = operationResult.LocationUri ?? operationResult.OperationUri,
|
||||
OperationResult = operationResult,
|
||||
};
|
||||
|
||||
this.UpdateProgress(result);
|
||||
|
||||
throw new InvalidOperationException(message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resources client.
|
||||
/// </summary>
|
||||
private ResourceManagerRestRestClient GetResourcesClient()
|
||||
{
|
||||
return this.ResourcesClientFactory();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs the fact that the operation has progressed.
|
||||
/// </summary>
|
||||
/// <param name="result">The operation result</param>
|
||||
private void UpdateProgress(TrackingOperationResult result)
|
||||
{
|
||||
this.ProgressTrackerObject.UpdateProgress(result, this.IsResourceCreateOrUpdate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The progress tracker.
|
||||
/// </summary>
|
||||
private class ProgressTracker
|
||||
{
|
||||
/// <summary>
|
||||
/// A delegate for fetching the resources client.
|
||||
/// </summary>
|
||||
private Func<ResourceManagerRestRestClient> ResourcesClientFactory { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// A delegate for writing progress to PowerShell.
|
||||
/// </summary>
|
||||
private Action<ProgressRecord> WriteProgressAction { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The cancellation token.
|
||||
/// </summary>
|
||||
private CancellationToken CancellationToken { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The progress record.
|
||||
/// </summary>
|
||||
private ProgressRecord ProgressRecord { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The last state that was observed.
|
||||
/// </summary>
|
||||
private string LastState { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ProgressTracker"/> class.
|
||||
/// </summary>
|
||||
/// <param name="activityName">The name of the activity to report in progress.</param>
|
||||
/// <param name="resourcesClientFactory">A delegate for fetching the resources client/</param>
|
||||
/// <param name="writeProgressAction">A delegate for writing progress.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
internal ProgressTracker(string activityName, Func<ResourceManagerRestRestClient> resourcesClientFactory, Action<ProgressRecord> writeProgressAction, CancellationToken cancellationToken)
|
||||
{
|
||||
this.ResourcesClientFactory = resourcesClientFactory;
|
||||
this.WriteProgressAction = writeProgressAction;
|
||||
this.CancellationToken = cancellationToken;
|
||||
this.LastState = "Starting";
|
||||
this.ProgressRecord = new ProgressRecord(activityId: 0, activity: activityName, statusDescription: "Starting - 0.00% completed.");
|
||||
}
|
||||
|
||||
internal void SetProgressPercentageAndWriteProgress(double percentage)
|
||||
{
|
||||
this.SetProgressRecordPercentComplete(percentage);
|
||||
this.WriteProgressAction(this.ProgressRecord);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs the fact that the operation has progressed.
|
||||
/// </summary>
|
||||
/// <param name="result">The operation result</param>
|
||||
/// <param name="isResourceCreateOrUpdate">Is Create or Update operation, other option include Move etc.</param>
|
||||
internal void UpdateProgress(TrackingOperationResult result, bool isResourceCreateOrUpdate)
|
||||
{
|
||||
if (isResourceCreateOrUpdate)
|
||||
{
|
||||
var currentState = this.GetOperationState(result.OperationResult);
|
||||
|
||||
if (result.Failed || currentState == null || !this.LastState.EqualsInsensitively(currentState))
|
||||
{
|
||||
this.SetProgressPercentageAndWriteProgress(100.0);
|
||||
}
|
||||
|
||||
if (currentState == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.LastState = currentState;
|
||||
}
|
||||
else
|
||||
{
|
||||
if(result.Failed)
|
||||
{
|
||||
this.SetProgressPercentageAndWriteProgress(100.0);
|
||||
}
|
||||
}
|
||||
|
||||
this.SetProgressRecordPercentComplete(result.OperationResult.PercentComplete);
|
||||
this.WriteProgressAction(this.ProgressRecord);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the progress of the operation.
|
||||
/// </summary>
|
||||
/// <param name="currentState">The current state.</param>
|
||||
/// <param name="percentCompleted">The percent completed.</param>
|
||||
internal void UpdateProgress(string currentState, double percentCompleted)
|
||||
{
|
||||
if (currentState == null || !this.LastState.EqualsInsensitively(currentState))
|
||||
{
|
||||
this.SetProgressRecordPercentComplete(100.0);
|
||||
this.WriteProgressAction(this.ProgressRecord);
|
||||
}
|
||||
|
||||
if (currentState == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.LastState = currentState;
|
||||
this.SetProgressRecordPercentComplete(percentCompleted);
|
||||
this.WriteProgressAction(this.ProgressRecord);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the progress completed and updates the status description.
|
||||
/// </summary>
|
||||
/// <param name="percentComplete">The percent completed.</param>
|
||||
private void SetProgressRecordPercentComplete(double? percentComplete)
|
||||
{
|
||||
if (percentComplete == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var value = Math.Max(Math.Min(100.0, percentComplete.Value), 0.0);
|
||||
|
||||
this.ProgressRecord.PercentComplete = (int)value;
|
||||
|
||||
this.ProgressRecord.StatusDescription = string.Format("{0} - {1:P2} completed.", this.LastState, value / 100.0);
|
||||
|
||||
this.ProgressRecord.RecordType = (100.0 - value) <= double.Epsilon
|
||||
? ProgressRecordType.Completed
|
||||
: ProgressRecordType.Processing;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extra code for handling resource create/update calls.
|
||||
/// </summary>
|
||||
/// <param name="operationResult">The result of the operation.</param>
|
||||
private string GetOperationState(OperationResult operationResult)
|
||||
{
|
||||
return operationResult.AzureAsyncOperationUri != null
|
||||
? this.GetAzureAsyncOperationState(operationResult)
|
||||
: ProgressTracker.GetResourceState(operationResult);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the azure async operation state.
|
||||
/// </summary>
|
||||
/// <param name="operationResult">The operation result.</param>
|
||||
private string GetAzureAsyncOperationState(OperationResult operationResult)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = this.ResourcesClientFactory()
|
||||
.GetAzureAsyncOperationResource(operationResult.AzureAsyncOperationUri, this.CancellationToken)
|
||||
.Result;
|
||||
|
||||
return result == null
|
||||
? null
|
||||
: result.Status;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (e.IsFatal())
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the state from the resource.
|
||||
/// </summary>
|
||||
/// <param name="operationResult">The operation result.</param>
|
||||
private static string GetResourceState(OperationResult operationResult)
|
||||
{
|
||||
Resource<InsensitiveDictionary<JToken>> resource;
|
||||
if (!operationResult.Value.TryConvertTo<Resource<InsensitiveDictionary<JToken>>>(out resource))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (resource == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
resource.Properties = resource.Properties ?? new InsensitiveDictionary<JToken>();
|
||||
JToken provisioningStateJToken;
|
||||
|
||||
return resource.Properties.TryGetValue("provisioningState", out provisioningStateJToken)
|
||||
? provisioningStateJToken.ToString()
|
||||
: null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A simple class that is used to track progress.
|
||||
/// </summary>
|
||||
private class TrackingOperationResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the retry interval.
|
||||
/// </summary>
|
||||
internal TimeSpan? RetryAfter { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tracking <see cref="Uri"/>.
|
||||
/// </summary>
|
||||
internal Uri TrackingUri { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the operation result.
|
||||
/// </summary>
|
||||
internal OperationResult OperationResult { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value that indicates if the polling method should continue to wait.
|
||||
/// </summary>
|
||||
internal bool ShouldWait { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a method that indicates that the operation has terminally failed.
|
||||
/// </summary>
|
||||
internal bool Failed { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components
|
||||
{
|
||||
using System;
|
||||
using System.Net;
|
||||
|
||||
/// <summary>
|
||||
/// A simple class that represents the result of an operation.
|
||||
/// </summary>
|
||||
public class OperationResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the status code that was returned.
|
||||
/// </summary>
|
||||
public HttpStatusCode HttpStatusCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the retry after interval that was returned.
|
||||
/// </summary>
|
||||
public TimeSpan? RetryAfter { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the long operation location Uri where clients can poll for progress of the operation.
|
||||
/// </summary>
|
||||
public Uri LocationUri { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="Uri"/> of the <see cref="System.Net.Http.HttpRequestMessage"/> that created this result.
|
||||
/// </summary>
|
||||
public Uri OperationUri { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the azure async operation location Uri where clients can poll for progress of the operation.
|
||||
/// </summary>
|
||||
public Uri AzureAsyncOperationUri { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the percentage of completion.
|
||||
/// </summary>
|
||||
public double? PercentComplete { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the value.
|
||||
/// </summary>
|
||||
public string Value { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,157 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components
|
||||
{
|
||||
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
/// <summary>
|
||||
/// A class that builds query filters.
|
||||
/// </summary>
|
||||
public static class QueryFilterBuilder
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a filter from the given properties.
|
||||
/// </summary>
|
||||
/// <param name="subscriptionId">The subscription to query.</param>
|
||||
/// <param name="resourceGroup">The name of the resource group/</param>
|
||||
/// <param name="resourceType">The resource type.</param>
|
||||
/// <param name="resourceName">The resource name.</param>
|
||||
/// <param name="tagName">The tag name.</param>
|
||||
/// <param name="tagValue">The tag value.</param>
|
||||
/// <param name="filter">The filter.</param>
|
||||
public static string CreateFilter(
|
||||
string subscriptionId,
|
||||
string resourceGroup,
|
||||
string resourceType,
|
||||
string resourceName,
|
||||
string tagName,
|
||||
string tagValue,
|
||||
string filter,
|
||||
string nameContains = null,
|
||||
string resourceGroupNameContains = null)
|
||||
{
|
||||
var filterStringBuilder = new StringBuilder();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(subscriptionId))
|
||||
{
|
||||
filterStringBuilder.AppendFormat("subscriptionId EQ '{0}'", subscriptionId);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(resourceGroup))
|
||||
{
|
||||
if (filterStringBuilder.Length > 0)
|
||||
{
|
||||
filterStringBuilder.Append(" AND ");
|
||||
}
|
||||
|
||||
filterStringBuilder.AppendFormat("resourceGroup EQ '{0}'", resourceGroup);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(resourceType))
|
||||
{
|
||||
if (filterStringBuilder.Length > 0)
|
||||
{
|
||||
filterStringBuilder.Append(" AND ");
|
||||
}
|
||||
|
||||
filterStringBuilder.AppendFormat("resourceType EQ '{0}'", resourceType);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(resourceName))
|
||||
{
|
||||
if (filterStringBuilder.Length > 0)
|
||||
{
|
||||
filterStringBuilder.Append(" AND ");
|
||||
}
|
||||
|
||||
filterStringBuilder.AppendFormat("name EQ '{0}'", resourceName);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(tagName))
|
||||
{
|
||||
if (filterStringBuilder.Length > 0)
|
||||
{
|
||||
filterStringBuilder.Append(" AND ");
|
||||
}
|
||||
|
||||
filterStringBuilder.AppendFormat("tagName EQ '{0}'", tagName);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(tagValue))
|
||||
{
|
||||
if (filterStringBuilder.Length > 0)
|
||||
{
|
||||
filterStringBuilder.Append(" AND ");
|
||||
}
|
||||
|
||||
filterStringBuilder.AppendFormat("tagValue EQ '{0}'", tagValue);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(resourceGroupNameContains))
|
||||
{
|
||||
if (filterStringBuilder.Length > 0)
|
||||
{
|
||||
filterStringBuilder.Append(" AND ");
|
||||
}
|
||||
|
||||
filterStringBuilder.AppendFormat("substringof('{0}', resourceGroup)", resourceGroupNameContains);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(nameContains))
|
||||
{
|
||||
if (filterStringBuilder.Length > 0)
|
||||
{
|
||||
filterStringBuilder.Append(" AND ");
|
||||
}
|
||||
|
||||
filterStringBuilder.AppendFormat("substringof('{0}', name)", nameContains);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(filter))
|
||||
{
|
||||
filter = filter.Trim().TrimStart('?').TrimStart('&');
|
||||
|
||||
if (filter.StartsWith("$filter", StringComparison.InvariantCultureIgnoreCase))
|
||||
{
|
||||
var indexOfEqual = filter.IndexOf("=", StringComparison.Ordinal);
|
||||
|
||||
if (indexOfEqual > 0 && indexOfEqual < filter.Length - 2)
|
||||
{
|
||||
|
||||
filter = filter.Substring(filter.IndexOf("=", StringComparison.Ordinal) + 1).Trim();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException(
|
||||
"If $filter is specified, it cannot be empty and must be of the format '$filter = <filter_value>'. The filter: " + filter,
|
||||
"filter");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (filterStringBuilder.Length > 0 && !string.IsNullOrWhiteSpace(filter))
|
||||
{
|
||||
return "(" + filterStringBuilder.ToString() + ") AND (" + filter.CoalesceString() + ")";
|
||||
}
|
||||
|
||||
return filterStringBuilder.Length > 0
|
||||
? filterStringBuilder.ToString()
|
||||
: filter.CoalesceString();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,449 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components
|
||||
{
|
||||
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
/// <summary>
|
||||
/// Class for building and parsing resource Ids.
|
||||
/// </summary>
|
||||
public static class ResourceIdUtility
|
||||
{
|
||||
/// <summary>
|
||||
/// Processes the parameters to return a valid resource Id.
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource Id.</param>
|
||||
/// <param name="resourceGroupName">The resource group</param>
|
||||
/// <param name="extensionResourceType">The extension resource type string in the format: '{providerName}/{typeName}/{nestedTypeName}'</param>
|
||||
/// <param name="extensionResourceName">The extension resource name in the format: '{resourceName}[/{nestedResourceName}]'</param>
|
||||
public static string GetResourceId(string resourceId, string extensionResourceType, string extensionResourceName = null)
|
||||
{
|
||||
var resourceIdBuilder = new StringBuilder(resourceId.TrimEnd('/'));
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(extensionResourceType))
|
||||
{
|
||||
resourceIdBuilder.Append(ResourceIdUtility.ProcessResourceTypeAndName(resourceType: extensionResourceType, resourceName: extensionResourceName));
|
||||
}
|
||||
|
||||
return resourceIdBuilder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes the parameters to return a valid resource Id.
|
||||
/// </summary>
|
||||
/// <param name="subscriptionId">The subscription.</param>
|
||||
/// <param name="resourceGroupName">The resource group</param>
|
||||
/// <param name="resourceType">The resource type string in the format: '{providerName}/{typeName}/{nestedTypeName}'</param>
|
||||
/// <param name="resourceName">The resource name in the format: '{resourceName}[/{nestedResourceName}]'</param>
|
||||
/// <param name="extensionResourceType">The extension resource type string in the format: '{providerName}/{typeName}/{nestedTypeName}'</param>
|
||||
/// <param name="extensionResourceName">The extension resource name in the format: '{resourceName}[/{nestedResourceName}]'</param>
|
||||
public static string GetResourceId(Guid? subscriptionId, string resourceGroupName, string resourceType, string resourceName, string extensionResourceType = null, string extensionResourceName = null)
|
||||
{
|
||||
if (subscriptionId == null && !string.IsNullOrWhiteSpace(resourceGroupName))
|
||||
{
|
||||
throw new InvalidOperationException("A resource group cannot be specified without a subscription.");
|
||||
}
|
||||
|
||||
var resourceId = new StringBuilder();
|
||||
|
||||
if (subscriptionId != null)
|
||||
{
|
||||
resourceId.AppendFormat("/subscriptions/{0}", Uri.EscapeDataString(subscriptionId.Value.ToString()));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(resourceGroupName))
|
||||
{
|
||||
resourceId.AppendFormat("/resourceGroups/{0}", Uri.EscapeDataString(resourceGroupName));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(resourceType))
|
||||
{
|
||||
resourceId.Append(ResourceIdUtility.ProcessResourceTypeAndName(resourceType: resourceType, resourceName: resourceName));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(extensionResourceType))
|
||||
{
|
||||
resourceId.Append(ResourceIdUtility.ProcessResourceTypeAndName(resourceType: extensionResourceType, resourceName: extensionResourceName));
|
||||
}
|
||||
|
||||
return resourceId.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes the parameters to return a valid resource Id.
|
||||
/// </summary>
|
||||
/// <param name="subscriptionId">The subscription.</param>
|
||||
public static string GetResourceGroupsId(Guid? subscriptionId)
|
||||
{
|
||||
if (subscriptionId == null)
|
||||
{
|
||||
throw new InvalidOperationException("A resource group cannot be specified without a subscription.");
|
||||
}
|
||||
|
||||
return string.Format("/subscriptions/{0}/resourceGroups", Uri.EscapeDataString(subscriptionId.Value.ToString()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes the parameters to return a valid resource Id.
|
||||
/// </summary>
|
||||
/// <param name="subscriptionId">The subscription.</param>
|
||||
/// <param name="resourceGroupName">The resource group</param>
|
||||
/// <param name="parentResource">The parent resource in the format: '{resourceType}/{typeName}'</param>
|
||||
/// <param name="resourceType">The resource type string in the format: '{providerName}/{typeName}'</param>
|
||||
/// <param name="resourceName">The resource name in the format: '{resourceName}'</param>
|
||||
/// <returns></returns>
|
||||
public static string GetResourceId(Guid subscriptionId, string resourceGroupName, string parentResource, string resourceType, string resourceName)
|
||||
{
|
||||
var provider = ResourceIdUtility.GetProviderFromLegacyResourceTypeString(resourceType);
|
||||
resourceType = ResourceIdUtility.GetTypeFromLegacyResourceTypeString(resourceType);
|
||||
|
||||
var parameters = new[]
|
||||
{
|
||||
subscriptionId.ToString(),
|
||||
resourceGroupName,
|
||||
provider,
|
||||
parentResource.Trim('/'),
|
||||
resourceType.Trim('/'),
|
||||
resourceName.Trim('/'),
|
||||
};
|
||||
|
||||
var parameteValues = parameters
|
||||
.Select(parameter => Uri.EscapeDataString(parameter))
|
||||
.Cast<object>()
|
||||
.ToArray();
|
||||
|
||||
return string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/{2}/{3}/{4}/{5}", parameteValues);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes the parameters to return a valid resource collection Id.
|
||||
/// </summary>
|
||||
/// <param name="subscriptionId">The subscription.</param>
|
||||
/// <param name="resourceGroupName">The resource group</param>
|
||||
/// <param name="resourceType">The resource type string in the format: '{providerName}/{typeName}/{nestedTypeName}'</param>
|
||||
/// <param name="extensionResourceType">The extension resource type string in the format: '{providerName}/{typeName}/{nestedTypeName}'</param>
|
||||
public static string GetResourceCollectionId(Guid? subscriptionId, string resourceGroupName, string resourceType, string extensionResourceType = null)
|
||||
{
|
||||
if (subscriptionId == null && !string.IsNullOrWhiteSpace(resourceGroupName))
|
||||
{
|
||||
throw new InvalidOperationException("A resource group cannot be specified without a subscription.");
|
||||
}
|
||||
|
||||
var resourceId = new StringBuilder();
|
||||
|
||||
if (subscriptionId != null)
|
||||
{
|
||||
resourceId.AppendFormat("/subscriptions/{0}", Uri.EscapeDataString(subscriptionId.Value.ToString()));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(resourceGroupName))
|
||||
{
|
||||
resourceId.AppendFormat("/resourceGroups/{0}", Uri.EscapeDataString(resourceGroupName));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(resourceType))
|
||||
{
|
||||
resourceId.Append(ResourceIdUtility.ProcessResourceTypeAndName(resourceType: resourceType, resourceName: null));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(extensionResourceType))
|
||||
{
|
||||
resourceId.Append(ResourceIdUtility.ProcessResourceTypeAndName(resourceType: extensionResourceType, resourceName: null));
|
||||
}
|
||||
|
||||
return resourceId.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the provider namespace from the resource id.
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource id.</param>
|
||||
public static string GetProviderNamespace(string resourceId)
|
||||
{
|
||||
return ResourceIdUtility.GetNextSegmentAfter(resourceId: resourceId, segmentName: Constants.Providers);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the subscription id from the resource id.
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource id.</param>
|
||||
public static string GetSubscriptionId(string resourceId)
|
||||
{
|
||||
return ResourceIdUtility.GetNextSegmentAfter(resourceId: resourceId, segmentName: Constants.Subscriptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the resource group from the resource id.
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource id.</param>
|
||||
public static string GetResourceGroupName(string resourceId)
|
||||
{
|
||||
return ResourceIdUtility.GetNextSegmentAfter(resourceId: resourceId, segmentName: Constants.ResourceGroups);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the id of the resource group from the resource id.
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource id.</param>
|
||||
public static string GetResourceGroupId(string resourceId)
|
||||
{
|
||||
var subscriptionId = ResourceIdUtility.GetSubscriptionId(resourceId);
|
||||
if (string.IsNullOrWhiteSpace(subscriptionId))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
Guid subscriptionGuid;
|
||||
if (!Guid.TryParse(subscriptionId, out subscriptionGuid))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var resourceGroupName = ResourceIdUtility.GetResourceGroupName(resourceId);
|
||||
if (string.IsNullOrWhiteSpace(resourceGroupName))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return ResourceIdUtility.GetResourceId(
|
||||
subscriptionId: subscriptionGuid,
|
||||
resourceGroupName: resourceGroupName,
|
||||
resourceType: null,
|
||||
resourceName: null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a resource type
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource Id.</param>
|
||||
/// <param name="includeProviderNamespace">Indicates if the provider namespace should be included in the resource name.</param>
|
||||
public static string GetResourceType(string resourceId, bool includeProviderNamespace = true)
|
||||
{
|
||||
return ResourceIdUtility.GetResourceTypeOrName(resourceId: resourceId, includeProviderNamespace: includeProviderNamespace, getResourceName: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a resource name
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource Id.</param>
|
||||
public static string GetResourceName(string resourceId)
|
||||
{
|
||||
return ResourceIdUtility.GetResourceTypeOrName(resourceId: resourceId, getResourceName: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the extension provider namespace from the resource id.
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource id.</param>
|
||||
public static string GetExtensionProviderNamespace(string resourceId)
|
||||
{
|
||||
return ResourceIdUtility.IsExtensionResourceId(resourceId)
|
||||
? ResourceIdUtility.GetNextSegmentAfter(resourceId: resourceId, segmentName: Constants.Providers, selectLastSegment: true)
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a resource type
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource Id.</param>
|
||||
/// <param name="includeProviderNamespace">Indicates if the provider namespace should be included in the resource name.</param>
|
||||
public static string GetExtensionResourceType(string resourceId, bool includeProviderNamespace = true)
|
||||
{
|
||||
return ResourceIdUtility.GetExtensionResourceTypeOrName(resourceId: resourceId, includeProviderNamespace: includeProviderNamespace, getResourceName: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a resource name
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource Id.</param>
|
||||
public static string GetExtensionResourceName(string resourceId)
|
||||
{
|
||||
return ResourceIdUtility.GetExtensionResourceTypeOrName(resourceId: resourceId, getResourceName: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets either a resource type or resource Id based on the value of the <see cref="getResourceName"/> parameter.
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource Id.</param>
|
||||
/// <param name="getResourceName">When set to true returns a resource name, otherwise a resource type.</param>
|
||||
/// <param name="includeProviderNamespace">Indicates if the provider namespace should be included in the resource name.</param>
|
||||
private static string GetExtensionResourceTypeOrName(string resourceId, bool getResourceName, bool includeProviderNamespace = true)
|
||||
{
|
||||
return ResourceIdUtility.IsExtensionResourceId(resourceId)
|
||||
? ResourceIdUtility.GetResourceTypeOrName(resourceId: resourceId, getResourceName: getResourceName, includeProviderNamespace: includeProviderNamespace, useLastSegment: true)
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a resource id contains an extension resource.
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource Id.</param>
|
||||
private static bool IsExtensionResourceId(string resourceId)
|
||||
{
|
||||
return resourceId
|
||||
.SplitRemoveEmpty('/')
|
||||
.Count(segment => segment.EqualsInsensitively(Constants.Providers)) == 2;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets either a resource type or resource Id based on the value of the <see cref="getResourceName"/> parameter.
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource Id.</param>
|
||||
/// <param name="getResourceName">When set to true returns a resource name, otherwise a resource type.</param>
|
||||
/// <param name="includeProviderNamespace">Indicates if the provider namespace should be included in the resource name.</param>
|
||||
/// <param name="useLastSegment">Seek the last segment instead of the first match.</param>
|
||||
private static string GetResourceTypeOrName(string resourceId, bool getResourceName, bool includeProviderNamespace = true, bool useLastSegment = false)
|
||||
{
|
||||
var substring = ResourceIdUtility.GetSubstringAfterSegment(
|
||||
resourceId: resourceId,
|
||||
segmentName: Constants.Providers,
|
||||
selectLastSegment: useLastSegment);
|
||||
|
||||
var segments = substring.CoalesceString().SplitRemoveEmpty('/');
|
||||
|
||||
if (!segments.Any())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var providerNamespace = segments.First();
|
||||
|
||||
var segmentString = segments.Skip(1)
|
||||
.TakeWhile(segment => !segment.EqualsInsensitively(Constants.Providers))
|
||||
.Where((segment, index) => getResourceName ? index % 2 != 0 : index % 2 == 0)
|
||||
.ConcatStrings("/");
|
||||
|
||||
return getResourceName
|
||||
? segmentString
|
||||
: includeProviderNamespace
|
||||
? string.Format("{0}/{1}", providerNamespace, segmentString)
|
||||
: segmentString;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the next segment after the one specified in <paramref name="segmentName"/>.
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource Id.</param>
|
||||
/// <param name="segmentName">The segment name.</param>
|
||||
/// <param name="selectLastSegment">When set to true, gets the last segment (default) otherwise gets the first one.</param>
|
||||
private static string GetNextSegmentAfter(string resourceId, string segmentName, bool selectLastSegment = false)
|
||||
{
|
||||
var segment = ResourceIdUtility
|
||||
.GetSubstringAfterSegment(
|
||||
resourceId: resourceId,
|
||||
segmentName: segmentName,
|
||||
selectLastSegment: selectLastSegment)
|
||||
.SplitRemoveEmpty('/')
|
||||
.FirstOrDefault();
|
||||
|
||||
return string.IsNullOrWhiteSpace(segment)
|
||||
? null
|
||||
: segment;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a the substring after a segment.
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource Id.</param>
|
||||
/// <param name="segmentName">The segment name.</param>
|
||||
/// <param name="selectLastSegment">When set to true, gets the last segment (default) otherwise gets the first one.</param>
|
||||
private static string GetSubstringAfterSegment(string resourceId, string segmentName, bool selectLastSegment = true)
|
||||
{
|
||||
var segment = string.Format("/{0}/", segmentName.Trim('/').ToUpperInvariant());
|
||||
|
||||
var index = selectLastSegment
|
||||
? resourceId.LastIndexOf(segment, StringComparison.InvariantCultureIgnoreCase)
|
||||
: resourceId.IndexOf(segment, StringComparison.InvariantCultureIgnoreCase);
|
||||
|
||||
return index < 0
|
||||
? null
|
||||
: resourceId.Substring(index + segment.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes a resource type string and a resource name string and
|
||||
/// </summary>
|
||||
/// <param name="resourceType">The resource type string in the format: '{providerName}/{typeName}/{nestedTypeName}'</param>
|
||||
/// <param name="resourceName">The resource name in the format: '{resourceName}[/{nestedResourceName}]'</param>
|
||||
private static string ProcessResourceTypeAndName(string resourceType, string resourceName)
|
||||
{
|
||||
var resourceId = new StringBuilder();
|
||||
var resourceTypeTokens = resourceType.SplitRemoveEmpty('/');
|
||||
var resourceNameTokens = resourceName.CoalesceString().SplitRemoveEmpty('/');
|
||||
|
||||
resourceId.AppendFormat("/providers/{0}", Uri.EscapeDataString(resourceTypeTokens.First()));
|
||||
|
||||
for (int i = 1; i < resourceTypeTokens.Length; ++i)
|
||||
{
|
||||
resourceId.AppendFormat("/{0}", Uri.EscapeDataString(resourceTypeTokens[i]));
|
||||
|
||||
if (resourceNameTokens.Length > i - 1)
|
||||
{
|
||||
resourceId.AppendFormat("/{0}", Uri.EscapeDataString(resourceNameTokens[i - 1]));
|
||||
}
|
||||
}
|
||||
|
||||
return resourceId.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the provider from the resource type for the legacy resource id format.
|
||||
/// </summary>
|
||||
/// <param name="legacyResourceType">The resource type.</param>
|
||||
private static string GetProviderFromLegacyResourceTypeString(string legacyResourceType)
|
||||
{
|
||||
if (legacyResourceType == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
int indexOfSlash = legacyResourceType.IndexOf('/');
|
||||
if (indexOfSlash < 0)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
else
|
||||
{
|
||||
return legacyResourceType.Substring(0, indexOfSlash);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource type from the resource type for the legacy resource id format.
|
||||
/// </summary>
|
||||
/// <param name="legacyResourceType">The resource type.</param>
|
||||
private static string GetTypeFromLegacyResourceTypeString(string legacyResourceType)
|
||||
{
|
||||
if (legacyResourceType == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
int lastIndexOfSlash = legacyResourceType.LastIndexOf('/');
|
||||
if (lastIndexOfSlash < 0)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
else
|
||||
{
|
||||
return legacyResourceType.Substring(lastIndexOfSlash + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,154 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using ProjectResources = Microsoft.Azure.Commands.ResourceManager.Cmdlets.Properties.Resources;
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components
|
||||
{
|
||||
public class ResourceIdentifier
|
||||
{
|
||||
public string ResourceType { get; set; }
|
||||
|
||||
public string ResourceGroupName { get; set; }
|
||||
|
||||
public string ResourceName { get; set; }
|
||||
|
||||
public string ParentResource { get; set; }
|
||||
|
||||
public string Subscription { get; set; }
|
||||
|
||||
public ResourceIdentifier() { }
|
||||
|
||||
public ResourceIdentifier(string idFromServer)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(idFromServer))
|
||||
{
|
||||
string[] tokens = idFromServer.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (tokens.Length < 8)
|
||||
{
|
||||
throw new ArgumentException(ProjectResources.InvalidFormatOfResourceId, "idFromServer");
|
||||
}
|
||||
Subscription = tokens[1];
|
||||
ResourceGroupName = tokens[3];
|
||||
ResourceName = tokens[tokens.Length - 1];
|
||||
|
||||
List<string> resourceTypeBuilder = new List<string>();
|
||||
resourceTypeBuilder.Add(tokens[5]);
|
||||
|
||||
List<string> parentResourceBuilder = new List<string>();
|
||||
for (int i = 6; i <= tokens.Length - 3; i++)
|
||||
{
|
||||
parentResourceBuilder.Add(tokens[i]);
|
||||
// Add every other token to type
|
||||
if (i%2 == 0)
|
||||
{
|
||||
resourceTypeBuilder.Add(tokens[i]);
|
||||
}
|
||||
}
|
||||
resourceTypeBuilder.Add(tokens[tokens.Length - 2]);
|
||||
|
||||
if (parentResourceBuilder.Count > 0)
|
||||
{
|
||||
ParentResource = string.Join("/", parentResourceBuilder);
|
||||
}
|
||||
if (resourceTypeBuilder.Count > 0)
|
||||
{
|
||||
ResourceType = string.Join("/", resourceTypeBuilder);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static ResourceIdentifier FromResourceGroupIdentifier(string resourceGroupId)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(resourceGroupId))
|
||||
{
|
||||
string[] tokens = resourceGroupId.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (tokens.Length < 4)
|
||||
{
|
||||
throw new ArgumentException(ProjectResources.InvalidFormatOfResourceGroupId, "resourceGroupId");
|
||||
}
|
||||
return new ResourceIdentifier
|
||||
{
|
||||
Subscription = tokens[1],
|
||||
ResourceGroupName = tokens[3],
|
||||
};
|
||||
}
|
||||
|
||||
return new ResourceIdentifier();
|
||||
}
|
||||
|
||||
public static string GetProviderFromResourceType(string resourceType)
|
||||
{
|
||||
if (resourceType == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
int indexOfSlash = resourceType.IndexOf('/');
|
||||
if (indexOfSlash < 0)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
else
|
||||
{
|
||||
return resourceType.Substring(0, indexOfSlash);
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetTypeFromResourceType(string resourceType)
|
||||
{
|
||||
if (resourceType == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
int lastIndexOfSlash = resourceType.LastIndexOf('/');
|
||||
if (lastIndexOfSlash < 0)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
else
|
||||
{
|
||||
return resourceType.Substring(lastIndexOfSlash + 1);
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string provider = GetProviderFromResourceType(ResourceType);
|
||||
string type = GetTypeFromResourceType(ResourceType);
|
||||
string parentAndType = string.IsNullOrEmpty(ParentResource) ? type : ParentResource + "/" + type;
|
||||
StringBuilder resourceId = new StringBuilder();
|
||||
|
||||
AppendIfNotNull(resourceId, "/subscriptions/{0}", Subscription);
|
||||
AppendIfNotNull(resourceId, "/resourceGroups/{0}", ResourceGroupName);
|
||||
AppendIfNotNull(resourceId, "/providers/{0}", provider);
|
||||
AppendIfNotNull(resourceId, "/{0}", parentAndType);
|
||||
AppendIfNotNull(resourceId, "/{0}", ResourceName);
|
||||
|
||||
return resourceId.ToString();
|
||||
}
|
||||
|
||||
private void AppendIfNotNull(StringBuilder resourceId, string format, string value)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(value))
|
||||
{
|
||||
resourceId.AppendFormat(format, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
using Microsoft.Azure.Commands.Common.Authentication;
|
||||
using Microsoft.Azure.Commands.Common.Authentication.Models;
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components
|
||||
{
|
||||
using Commands.Common.Authentication.Abstractions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.RestClients;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
/// <summary>
|
||||
/// Helper class for constructing <see cref="ResourceManagerRestRestClient"/>.
|
||||
/// </summary>
|
||||
internal static class ResourceManagerClientHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a new instance of the <see cref="ResourceManagerRestRestClient"/>.
|
||||
/// </summary>
|
||||
/// <param name="context">The azure profile.</param>
|
||||
internal static ResourceManagerRestRestClient GetResourceManagerClient(IAzureContext context, Dictionary<string, string> cmdletHeaderValues = null)
|
||||
{
|
||||
var endpoint = context.Environment.GetEndpoint(AzureEnvironment.Endpoint.ResourceManager);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(endpoint))
|
||||
{
|
||||
throw new ApplicationException(
|
||||
"The endpoint for the Azure Resource Manager service is not set. Please report this issue via GitHub or contact Microsoft customer support.");
|
||||
}
|
||||
|
||||
var endpointUri = new Uri(endpoint, UriKind.Absolute);
|
||||
|
||||
return new ResourceManagerRestRestClient(
|
||||
endpointUri: endpointUri,
|
||||
httpClientHelper: HttpClientHelperFactory.Instance
|
||||
.CreateHttpClientHelper(
|
||||
credentials: AzureSession.Instance.AuthenticationFactory
|
||||
.GetSubscriptionCloudCredentials(
|
||||
context,
|
||||
AzureEnvironment.Endpoint.ResourceManager),
|
||||
headerValues: AzureSession.Instance.ClientFactory.UserAgents,
|
||||
cmdletHeaderValues: cmdletHeaderValues));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,109 @@
|
|||
// ---------r-------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components
|
||||
{
|
||||
using Common.Tags;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Collections;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using ProjectResources = Microsoft.Azure.Commands.ResourceManager.Cmdlets.Properties.Resources;
|
||||
|
||||
/// <summary>
|
||||
/// Helper class for tags.
|
||||
/// </summary>
|
||||
internal static class TagsHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a tags dictionary from an enumerable of tags.
|
||||
/// </summary>
|
||||
/// <param name="tags">The enumerable of tags</param>
|
||||
internal static InsensitiveDictionary<string> GetTagsDictionary(Hashtable tags)
|
||||
{
|
||||
if(tags == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var tagsDictionary = TagsConversionHelper.CreateTagDictionary(tags, true);
|
||||
return tagsDictionary.Distinct(kvp => kvp.Key).ToInsensitiveDictionary(kvp => kvp.Key, kvp => kvp.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a tags hash table from a tags dictionary.
|
||||
/// </summary>
|
||||
/// <param name="tags">The tags dictionary.</param>
|
||||
internal static Hashtable GetTagsHashtable(InsensitiveDictionary<string> tags)
|
||||
{
|
||||
return tags == null
|
||||
? null
|
||||
: TagsConversionHelper.CreateTagHashtable(tags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the tag name given the tagObj and tagName parameters. If both are specified then tagObj takes precedence.
|
||||
/// </summary>
|
||||
/// <param name="tagObjParameter">Parameter containing the tag name-value specified as a hashset.</param>
|
||||
/// <param name="tagNameParameter">Parameter containing the tag name specified individually.</param>
|
||||
/// <returns>The resolved tag name.</returns>
|
||||
internal static string GetTagNameFromParameters(Hashtable tagObjParameter, string tagNameParameter)
|
||||
{
|
||||
PSTagValuePair tagValuePair = null;
|
||||
if (tagObjParameter != null)
|
||||
{
|
||||
tagValuePair = TagsConversionHelper.Create(tagObjParameter);
|
||||
|
||||
if (tagValuePair == null)
|
||||
{
|
||||
throw new ArgumentException(ProjectResources.InvalidTagFormat);
|
||||
}
|
||||
}
|
||||
|
||||
if (tagValuePair != null)
|
||||
{
|
||||
return tagValuePair.Name;
|
||||
}
|
||||
return tagNameParameter;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the tag value given the tagObj and tagValue parameters. If both are specified then tagObj takes precedence.
|
||||
/// </summary>
|
||||
/// <param name="tagObjParameter">Parameter containing the tag name-value specified as a hashset.</param>
|
||||
/// <param name="tagValueParameter">Parameter containing the tag value specified individually.</param>
|
||||
/// <returns>The resolved tag value.</returns>
|
||||
internal static string GetTagValueFromParameters(Hashtable tagObjParameter, string tagValueParameter)
|
||||
{
|
||||
PSTagValuePair tagValuePair = null;
|
||||
if (tagObjParameter != null)
|
||||
{
|
||||
tagValuePair = TagsConversionHelper.Create(tagObjParameter);
|
||||
|
||||
if (tagValuePair == null)
|
||||
{
|
||||
throw new ArgumentException(ProjectResources.InvalidTagFormat);
|
||||
}
|
||||
}
|
||||
|
||||
if (tagValuePair != null)
|
||||
{
|
||||
return tagValuePair.Value;
|
||||
}
|
||||
return tagValueParameter;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Collections;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The application object.
|
||||
/// </summary>
|
||||
public class Application
|
||||
{
|
||||
/// <summary>
|
||||
/// The application name.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the application location.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Location { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The application properties.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public ApplicationProperties Properties { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The marketplace plan information.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public ResourcePlan Plan { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The application kind.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public ApplicationKind Kind { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tags.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public InsensitiveDictionary<string> Tags { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The application artifact.
|
||||
/// </summary>
|
||||
public class ApplicationArtifact
|
||||
{
|
||||
/// <summary>
|
||||
/// The application artifact name.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public ApplicationArtifactName Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The application artifact type.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public ApplicationArtifactType Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The application artifact blob uri.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Uri { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application
|
||||
{
|
||||
/// <summary>
|
||||
/// The artifact name.
|
||||
/// </summary>
|
||||
public enum ApplicationArtifactName
|
||||
{
|
||||
/// <summary>
|
||||
/// Appliance Resource Template.
|
||||
/// </summary>
|
||||
ApplianceResourceTemplate,
|
||||
|
||||
/// <summary>
|
||||
/// Create UI Definition.
|
||||
/// </summary>
|
||||
CreateUiDefinition
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application
|
||||
{
|
||||
/// <summary>
|
||||
/// The artifact type.
|
||||
/// </summary>
|
||||
public enum ApplicationArtifactType
|
||||
{
|
||||
/// <summary>
|
||||
/// Template artifact type.
|
||||
/// </summary>
|
||||
Template,
|
||||
|
||||
/// <summary>
|
||||
/// Custom artifact type.
|
||||
/// </summary>
|
||||
Custom
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Collections;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The application definition object.
|
||||
/// </summary>
|
||||
public class ApplicationDefinition
|
||||
{
|
||||
/// <summary>
|
||||
/// The application defintion name.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the application definition location.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Location { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The application definition properties.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public ApplicationDefinitionProperties Properties { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tags.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public InsensitiveDictionary<string> Tags { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,81 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
/// <summary>
|
||||
/// The application definition properties.
|
||||
/// </summary>
|
||||
public class ApplicationDefinitionProperties
|
||||
{
|
||||
/// <summary>
|
||||
/// The value indicating whether the package is enabled or not.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public bool? IsEnabled { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The lock level that determines customer's access to the managed resource group.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public ApplicationLockLevel LockLevel { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The application definition display name.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string DisplayName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The application definition description.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The collection of provider authorizations.
|
||||
/// ARM will use information in this collection to onboard the appliance provider so that they can perform operations on behalf of the customer.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public ApplicationProviderAuthorization[] Authorizations { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The collection of appliance artifacts.
|
||||
/// The portal will use the files specified as artifacts to construct the user experience of creating an appliance from an application definition.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public ApplicationArtifact[] Artifacts { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The package zip blob uri.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string PackageFileUri { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The create ui definition json.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public JObject CreateUiDefinition { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The main template json.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public JObject MainTemplate { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application
|
||||
{
|
||||
/// <summary>
|
||||
/// The application kind.
|
||||
/// </summary>
|
||||
public enum ApplicationKind
|
||||
{
|
||||
/// <summary>
|
||||
/// The application kind is service catalog.
|
||||
/// </summary>
|
||||
ServiceCatalog,
|
||||
|
||||
/// <summary>
|
||||
/// The application kind is marketplace.
|
||||
/// </summary>
|
||||
MarketPlace
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application
|
||||
{
|
||||
/// <summary>
|
||||
/// The lock level allowed.
|
||||
/// </summary>
|
||||
public enum ApplicationLockLevel
|
||||
{
|
||||
/// <summary>
|
||||
/// No lock.
|
||||
/// </summary>
|
||||
None,
|
||||
|
||||
/// <summary>
|
||||
/// The lock blocks delete.
|
||||
/// </summary>
|
||||
CanNotDelete,
|
||||
|
||||
/// <summary>
|
||||
/// The lock blocks all updates and delete.
|
||||
/// </summary>
|
||||
ReadOnly
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The application package customer support object.
|
||||
/// </summary>
|
||||
public class ApplicationPackageCustomerSupport
|
||||
{
|
||||
/// <summary>
|
||||
/// The contact name.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string ContactName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The email.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Email { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The phone.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Phone { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The application package support urls.
|
||||
/// </summary>
|
||||
public class ApplicationPackageSupportUrls
|
||||
{
|
||||
/// <summary>
|
||||
/// The public azure support URL.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string PublicAzure { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The government cloud support URL.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string GovernmentCloud { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,79 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
/// <summary>
|
||||
/// The policy definition properties.
|
||||
/// </summary>
|
||||
public class ApplicationProperties
|
||||
{
|
||||
/// <summary>
|
||||
/// The managed resource group id.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string ManagedResourceGroupId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The application definition id.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string ApplicationDefinitionId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The publisher package id.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string PublisherPackageId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The outputs.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public JObject Outputs { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The parameters declaration.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public JObject Parameters { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The ui definition uri.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string UiDefinitionUri { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The read-only authorizations property that is retrieved from the appliance package.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public ApplicationProviderAuthorization[] Authorizations { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The read-only customer support property that is retrieved from the application package.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public ApplicationPackageCustomerSupport CustomerSupport { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The read-only support URLs property that is retrieved from the application package.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public ApplicationPackageSupportUrls SupportUrls { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The application object.
|
||||
/// </summary>
|
||||
public class ApplicationProviderAuthorization
|
||||
{
|
||||
/// <summary>
|
||||
/// The provider's principal identifier. This is the identity that the provider will use to call ARM to manage the application resources.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string PrincipalId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The provider's role definition identifier. This role will define all the permissions that the provider must have on the application's
|
||||
/// container resource group. This role definition cannot have permission to delete the resource group.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string RoleDefinitionId { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Authorization
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The permission.
|
||||
/// </summary>
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "By design.")]
|
||||
public class Permission
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the actions.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string[] Actions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the not actions.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string[] NotActions { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.ErrorResponses
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The error response message.
|
||||
/// </summary>
|
||||
public class ErrorResponseMessage
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the extended error info.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public ExtendedErrorInfo Error { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.ErrorResponses
|
||||
{
|
||||
using Cmdlets.Utilities;
|
||||
using System;
|
||||
using System.Net;
|
||||
|
||||
/// <summary>
|
||||
/// The error response message exception.
|
||||
/// </summary>
|
||||
public class ErrorResponseMessageException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the http status code.
|
||||
/// </summary>
|
||||
public HttpStatusCode HttpStatus { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the error response code.
|
||||
/// </summary>
|
||||
public ErrorResponseMessage ErrorResponseMessage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ErrorResponseMessageException" /> class.
|
||||
/// </summary>
|
||||
/// <param name="httpStatus">The http status code.</param>
|
||||
/// <param name="errorResponseMessage">The error response code.</param>
|
||||
/// <param name="errorMessage">The error response message.</param>
|
||||
/// <param name="innerException">Optional. The inner exception.</param>
|
||||
public ErrorResponseMessageException(HttpStatusCode httpStatus, ErrorResponseMessage errorResponseMessage, string errorMessage, Exception innerException = null)
|
||||
: base(errorMessage, innerException)
|
||||
{
|
||||
if (HttpUtility.IsSuccessfulRequest(httpStatus))
|
||||
{
|
||||
throw new ArgumentException(
|
||||
message: "The error response message exception should not be used for successful http response messages.",
|
||||
paramName: "httpStatus");
|
||||
}
|
||||
|
||||
this.HttpStatus = httpStatus;
|
||||
this.ErrorResponseMessage = errorResponseMessage;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.ErrorResponses
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The extended error information.
|
||||
/// </summary>
|
||||
public class ExtendedErrorInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the error code.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Code { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the error message.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Message { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the target.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Target { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the detailed error message details.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public ExtendedErrorInfo[] Details { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Locks
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The lock object.
|
||||
/// </summary>
|
||||
public class Lock
|
||||
{
|
||||
/// <summary>
|
||||
/// The lock properties.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public LockProperties Properties { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Locks
|
||||
{
|
||||
/// <summary>
|
||||
/// The lock level allowed.
|
||||
/// </summary>
|
||||
public enum LockLevel
|
||||
{
|
||||
/// <summary>
|
||||
/// The lock blocks delete.
|
||||
/// </summary>
|
||||
CanNotDelete,
|
||||
|
||||
/// <summary>
|
||||
/// The lock blocks all updates and delete.
|
||||
/// </summary>
|
||||
ReadOnly
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Locks
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The lock properties.
|
||||
/// </summary>
|
||||
public class LockProperties
|
||||
{
|
||||
/// <summary>
|
||||
/// The lock level.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public LockLevel Level { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The lock notes.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Notes { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Operations
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.ErrorResponses;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The async operation result.
|
||||
/// </summary>
|
||||
public class AzureAsyncOperationResource
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the status of the async operation.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Status { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the extended error info.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public ExtendedErrorInfo Error { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The policy assignment object.
|
||||
/// </summary>
|
||||
public class PolicyAssignment
|
||||
{
|
||||
/// <summary>
|
||||
/// The policy assignment properties.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public PolicyAssignmentProperties Properties { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The policy assignment name.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The policy sku.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public PolicySku Sku { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
/// <summary>
|
||||
/// The policy assignment properties.
|
||||
/// </summary>
|
||||
public class PolicyAssignmentProperties
|
||||
{
|
||||
/// <summary>
|
||||
/// The scope.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Scope { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The not scopes array.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string[] NotScopes { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The display name.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string DisplayName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The description.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The policy assignment metadata.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public JObject Metadata { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The policy definition id.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string PolicyDefinitionId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The parameter values.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public JObject Parameters { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The policy definition object.
|
||||
/// </summary>
|
||||
public class PolicyDefinition
|
||||
{
|
||||
/// <summary>
|
||||
/// The policy definition name.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The policy definition properties.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public PolicyDefinitionProperties Properties { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy
|
||||
{
|
||||
/// <summary>
|
||||
/// The policy definition mode.
|
||||
/// </summary>
|
||||
public enum PolicyDefinitionMode
|
||||
{
|
||||
/// <summary>
|
||||
/// The policy definition mode is indexed.
|
||||
/// </summary>
|
||||
Indexed,
|
||||
|
||||
/// <summary>
|
||||
/// The policy definition mode is all.
|
||||
/// </summary>
|
||||
All
|
||||
}
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
/// <summary>
|
||||
/// The policy definition properties.
|
||||
/// </summary>
|
||||
public class PolicyDefinitionProperties
|
||||
{
|
||||
/// <summary>
|
||||
/// The description.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The display name.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string DisplayName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The policy rule.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public JObject PolicyRule { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The policy definition metadata.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public JObject Metadata { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The parameters declaration.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public JObject Parameters { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The mode.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public PolicyDefinitionMode? Mode { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The policy rule object.
|
||||
/// </summary>
|
||||
public class PolicyRule
|
||||
{
|
||||
/// <summary>
|
||||
/// The policy rule
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Rule { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The policy set definition object.
|
||||
/// </summary>
|
||||
public class PolicySetDefinition
|
||||
{
|
||||
/// <summary>
|
||||
/// The policy set definition name.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The policy set definition properties.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public PolicySetDefinitionProperties Properties { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
/// <summary>
|
||||
/// The policy definition properties.
|
||||
/// </summary>
|
||||
public class PolicySetDefinitionProperties
|
||||
{
|
||||
/// <summary>
|
||||
/// The description.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The display name.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string DisplayName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The policy set definition metadata.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public JObject Metadata { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The policy reference.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public JArray PolicyDefinitions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The parameters declaration.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public JObject Parameters { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy
|
||||
{
|
||||
/// <summary>
|
||||
/// The policy sku object.
|
||||
/// </summary>
|
||||
public class PolicySku
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the <c>sku</c> name.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <c>sku</c> tier.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Tier { get; set; }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Providers
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The resource provider type.
|
||||
/// </summary>
|
||||
public class ResourceProviderDefinition
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the registration state.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string RegistrationState { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the namespace.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Namespace { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the resource types.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public ResourceTypeDefinition[] ResourceTypes { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Providers
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The resource type.
|
||||
/// </summary>
|
||||
public class ResourceTypeDefinition
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the locations
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string[] Locations { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the API versions.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string[] ApiVersions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the resource type.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string ResourceType { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities
|
||||
{
|
||||
public enum ProvisioningState
|
||||
{
|
||||
/// <summary>
|
||||
/// The provisioning state is not specified.
|
||||
/// </summary>
|
||||
NotSpecified,
|
||||
|
||||
/// <summary>
|
||||
/// The provisioning state is accepted.
|
||||
/// </summary>
|
||||
Accepted,
|
||||
|
||||
/// <summary>
|
||||
/// The provisioning state is running.
|
||||
/// </summary>
|
||||
Running,
|
||||
|
||||
/// <summary>
|
||||
/// The provisioning state is creating.
|
||||
/// </summary>
|
||||
Creating,
|
||||
|
||||
/// <summary>
|
||||
/// The provisioning state is created.
|
||||
/// </summary>
|
||||
Created,
|
||||
|
||||
/// <summary>
|
||||
/// The provisioning state is deleting.
|
||||
/// </summary>
|
||||
Deleting,
|
||||
|
||||
/// <summary>
|
||||
/// The provisioning state is deleted.
|
||||
/// </summary>
|
||||
Deleted,
|
||||
|
||||
/// <summary>
|
||||
/// The provisioning state is canceled.
|
||||
/// </summary>
|
||||
Canceled,
|
||||
|
||||
/// <summary>
|
||||
/// The provisioning state is failed.
|
||||
/// </summary>
|
||||
Failed,
|
||||
|
||||
/// <summary>
|
||||
/// The provisioning state is succeeded.
|
||||
/// </summary>
|
||||
Succeeded,
|
||||
|
||||
/// <summary>
|
||||
/// The provisioning state is moving resources.
|
||||
/// </summary>
|
||||
MovingResources,
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.ResourceGroups
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The export template request definition object.
|
||||
/// </summary>
|
||||
public class ExportTemplateParameters
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the target resource group.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Options { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the list of resources in the resource group.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string[] Resources { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.ResourceGroups
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The resource batch move definition object.
|
||||
/// </summary>
|
||||
public class ResourceBatchMoveParameters
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the target resource group.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string TargetResourceGroup { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the list of resources to move.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string[] Resources { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,99 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Collections;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
|
||||
/// <summary>
|
||||
/// The resource definition object.
|
||||
/// </summary>
|
||||
public class Resource<TProperties>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the properties.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public TProperties Properties { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the id for the resource.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the resource.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the type of the resource definition.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the resource <c>sku</c>.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public ResourceSku Sku { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the kind of the resource definition.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Kind { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the resource location.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Location { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <c>etag</c>.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default, PropertyName = "etag")]
|
||||
public string ETag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the resource plan.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public ResourcePlan Plan { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the created time.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public DateTime? CreatedTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the changed time.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public DateTime? ChangedTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tags.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public InsensitiveDictionary<string> Tags { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
|
||||
/// <summary>
|
||||
/// The resource plan object.
|
||||
/// </summary>
|
||||
public class ResourcePlan
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the plan name.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the plan's promotion code.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string PromotionCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the plan's product code.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Product { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the plan's publisher.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Publisher { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources
|
||||
{
|
||||
/// <summary>
|
||||
/// The resource sku object.
|
||||
/// </summary>
|
||||
public class ResourceSku
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the <c>sku</c> name.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Always)]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <c>sku</c> tier.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Tier { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <c>sku</c> size.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Size { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <c>sku</c> family.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public string Family { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <c>sku</c> capacity.
|
||||
/// </summary>
|
||||
[JsonProperty(Required = Required.Default)]
|
||||
public int? Capacity { get; set; }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources
|
||||
{
|
||||
/// <summary>
|
||||
/// Terminal values for the <c>ProvisioningState</c> property.
|
||||
/// </summary>
|
||||
public enum TerminalProvisioningStates
|
||||
{
|
||||
/// <summary>
|
||||
/// The ready state.
|
||||
/// </summary>
|
||||
Ready,
|
||||
|
||||
/// <summary>
|
||||
/// The succeeded state.
|
||||
/// </summary>
|
||||
Succeeded,
|
||||
|
||||
/// <summary>
|
||||
/// The failed state.
|
||||
/// </summary>
|
||||
Failed,
|
||||
|
||||
/// <summary>
|
||||
/// The cancelled state.
|
||||
/// </summary>
|
||||
Canceled,
|
||||
}
|
||||
}
|
|
@ -0,0 +1,103 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// The asynchronous extensions.
|
||||
/// </summary>
|
||||
public static class AsyncExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a task that will complete when all of the supplied tasks have completed. Multiple exceptions will be wrapped
|
||||
/// as single aggregate exception. This extension method is intend to be used with await operator exclusively.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the result produced by task.</typeparam>
|
||||
/// <param name="tasks">The asynchronous tasks.</param>
|
||||
public static Task<T[]> WhenAllForAwait<T>(this IEnumerable<Task<T>> tasks)
|
||||
{
|
||||
return Task.WhenAll(tasks).WrapMultipleExceptionsForAwait();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a task that will complete when all of the supplied tasks have completed. Multiple exceptions will be wrapped
|
||||
/// as single aggregate exception. This extension method is intend to be used with await operator exclusively.
|
||||
/// </summary>
|
||||
/// <param name="tasks">The asynchronous tasks.</param>
|
||||
public static Task WhenAllForAwait(this IEnumerable<Task> tasks)
|
||||
{
|
||||
return Task.WhenAll(tasks).WrapMultipleExceptionsForAwait();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wraps the multiple exceptions as single aggregate exception for await operator.
|
||||
/// </summary>
|
||||
/// <param name="task">The asynchronous task.</param>
|
||||
public static Task WrapMultipleExceptionsForAwait(this Task task)
|
||||
{
|
||||
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
|
||||
task.ContinueWith(
|
||||
continuationAction: ignored => AsyncExtensions.CompleteTaskAndWrapMultipleExceptions(task, tcs),
|
||||
continuationOptions: TaskContinuationOptions.ExecuteSynchronously,
|
||||
cancellationToken: CancellationToken.None,
|
||||
scheduler: TaskScheduler.Default);
|
||||
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wraps the multiple exceptions as single aggregate exception for await operator.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the result produced by task.</typeparam>
|
||||
/// <param name="task">The asynchronous task.</param>
|
||||
public static Task<T> WrapMultipleExceptionsForAwait<T>(this Task<T> task)
|
||||
{
|
||||
TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
|
||||
task.ContinueWith(
|
||||
continuationAction: ignored => AsyncExtensions.CompleteTaskAndWrapMultipleExceptions(task, tcs),
|
||||
continuationOptions: TaskContinuationOptions.ExecuteSynchronously,
|
||||
cancellationToken: CancellationToken.None,
|
||||
scheduler: TaskScheduler.Default);
|
||||
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Completes the task completion source and wraps multiple exceptions as single aggregate exception.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the result produced by task.</typeparam>
|
||||
/// <param name="task">The asynchronous task.</param>
|
||||
/// <param name="completionSource">The task completion source.</param>
|
||||
private static void CompleteTaskAndWrapMultipleExceptions<T>(Task task, TaskCompletionSource<T> completionSource)
|
||||
{
|
||||
switch (task.Status)
|
||||
{
|
||||
case TaskStatus.Canceled:
|
||||
completionSource.SetCanceled();
|
||||
break;
|
||||
case TaskStatus.RanToCompletion:
|
||||
var genericTask = task as Task<T>;
|
||||
completionSource.SetResult(genericTask != null ? genericTask.Result : default(T));
|
||||
break;
|
||||
case TaskStatus.Faulted:
|
||||
completionSource.SetException(task.Exception.InnerExceptions.Count > 1 ? task.Exception : task.Exception.InnerException);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,56 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.ErrorResponses;
|
||||
using System;
|
||||
using System.Management.Automation;
|
||||
|
||||
/// <summary>
|
||||
/// Helper class that converts <see cref="ErrorResponseMessageException"/> objects into <see cref="ErrorRecord"/>
|
||||
/// </summary>
|
||||
internal static class ErrorResponseMessageExceptionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <see cref="ErrorResponseMessageException"/> objects into <see cref="ErrorRecord"/>
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception</param>
|
||||
internal static ErrorRecord ToErrorRecord(this ErrorResponseMessageException exception)
|
||||
{
|
||||
// TODO: Improve this.
|
||||
return new ErrorRecord(exception, exception.ErrorResponseMessage == null ? exception.HttpStatus.ToString() : exception.ErrorResponseMessage.Error.Code, ErrorCategory.CloseError, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <see cref="Exception"/> objects into <see cref="ErrorRecord"/>
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception</param>
|
||||
internal static ErrorRecord ToErrorRecord(this Exception exception)
|
||||
{
|
||||
// TODO: Improve this.
|
||||
return new ErrorRecord(exception, exception.Message, ErrorCategory.CloseError, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <see cref="AggregateException"/> objects into <see cref="ErrorRecord"/>
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception</param>
|
||||
internal static ErrorRecord ToErrorRecord(this AggregateException aggregateException)
|
||||
{
|
||||
// TODO: Improve this.
|
||||
return new ErrorRecord(aggregateException, aggregateException.ToString(), ErrorCategory.CloseError, null);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions
|
||||
{
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security;
|
||||
using System.Threading;
|
||||
|
||||
/// <summary>
|
||||
/// Exception extension methods
|
||||
/// </summary>
|
||||
public static class ExceptionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Test if an exception is a fatal exception.
|
||||
/// </summary>
|
||||
/// <param name="ex">Exception object.</param>
|
||||
public static bool IsFatal(this Exception ex)
|
||||
{
|
||||
if (ex is AggregateException)
|
||||
{
|
||||
return ex.Cast<AggregateException>().Flatten().InnerExceptions.Any(exception => exception.IsFatal());
|
||||
}
|
||||
|
||||
if (ex.InnerException != null && ex.InnerException.IsFatal())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return
|
||||
ex is TypeInitializationException ||
|
||||
ex is AppDomainUnloadedException ||
|
||||
ex is ThreadInterruptedException ||
|
||||
ex is AccessViolationException ||
|
||||
ex is InvalidProgramException ||
|
||||
ex is BadImageFormatException ||
|
||||
ex is StackOverflowException ||
|
||||
ex is ThreadAbortException ||
|
||||
ex is OutOfMemoryException ||
|
||||
ex is SecurityException ||
|
||||
ex is SEHException;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// HTTP://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http.Headers;
|
||||
|
||||
/// <summary>
|
||||
/// Http headers extensions.
|
||||
/// </summary>
|
||||
public static class HttpHeadersExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the first HTTP header or default value.
|
||||
/// </summary>
|
||||
/// <typeparam name="TType">The type of the object housed in the header.</typeparam>
|
||||
/// <param name="headers">The HTTP headers.</param>
|
||||
/// <param name="name">The header name.</param>
|
||||
/// <param name="transform">A transformation function that converts strings to <typeparamref name="TType"/>.</param>
|
||||
/// <param name="defaultValue">The default value.</param>
|
||||
public static TType GetFirstOrDefault<TType>(this HttpHeaders headers, string name, Func<string, TType> transform, TType defaultValue = default(TType))
|
||||
{
|
||||
IEnumerable<string> values;
|
||||
if (headers.TryGetValues(name, out values) && values.Any())
|
||||
{
|
||||
return transform(values.First());
|
||||
}
|
||||
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the azure async operation percent complete header.
|
||||
/// </summary>
|
||||
/// <param name="headers">The HTTP response headers.</param>
|
||||
public static double? GetAzureAzyncOperationPercentComplete(this HttpResponseHeaders headers)
|
||||
{
|
||||
return headers.GetFirstOrDefault(
|
||||
"Azure-AsyncOperationPercentComplete",
|
||||
(value) =>
|
||||
{
|
||||
double percentComplete;
|
||||
if (double.TryParse(value, out percentComplete))
|
||||
{
|
||||
return (double?)percentComplete;
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the azure async operation header.
|
||||
/// </summary>
|
||||
/// <param name="headers">The HTTP response headers.</param>
|
||||
public static Uri GetAzureAsyncOperation(this HttpResponseHeaders headers)
|
||||
{
|
||||
return headers.GetFirstOrDefault("Azure-AsyncOperation", value =>
|
||||
{
|
||||
Uri uri;
|
||||
if (Uri.TryCreate(value, UriKind.Absolute, out uri))
|
||||
{
|
||||
return uri;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,84 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions
|
||||
{
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Class containing HTTP message extension methods.
|
||||
/// </summary>
|
||||
public static class HttpMessageExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads the JSON content from the http response message.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object contained in the JSON.</typeparam>
|
||||
/// <param name="message">The response message to be read.</param>
|
||||
/// <param name="rewindContentStream">Rewind content stream if set to true.</param>
|
||||
/// <returns>An object of type T instantiated from the response message's body.</returns>
|
||||
public static async Task<T> ReadContentAsJsonAsync<T>(this HttpResponseMessage message, bool rewindContentStream = false)
|
||||
{
|
||||
using (var stream = await message.Content
|
||||
.ReadAsStreamAsync()
|
||||
.ConfigureAwait(continueOnCapturedContext: false))
|
||||
{
|
||||
var streamPosition = stream.Position;
|
||||
try
|
||||
{
|
||||
return stream.FromJson<T>();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (stream.CanSeek && streamPosition != stream.Position && rewindContentStream)
|
||||
{
|
||||
stream.Seek(streamPosition, SeekOrigin.Begin);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the JSON content from the http response message.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object contained in the JSON.</typeparam>
|
||||
/// <param name="message">The response message to be read.</param>
|
||||
/// <param name="rewindContentStream">Rewind content stream if set to true.</param>
|
||||
/// <returns>An object of type T instantiated from the response message's body.</returns>
|
||||
public static async Task<string> ReadContentAsStringAsync(this HttpResponseMessage message, bool rewindContentStream = false)
|
||||
{
|
||||
using (var stream = await message.Content
|
||||
.ReadAsStreamAsync()
|
||||
.ConfigureAwait(continueOnCapturedContext: false))
|
||||
using (var streamReader = new StreamReader(stream))
|
||||
{
|
||||
var streamPosition = stream.Position;
|
||||
try
|
||||
{
|
||||
|
||||
return streamReader.ReadToEnd();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (stream.CanSeek && streamPosition != stream.Position && rewindContentStream)
|
||||
{
|
||||
stream.Seek(streamPosition, SeekOrigin.Begin);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,156 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Collections;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
/// <summary>
|
||||
/// IEnumerable extension methods
|
||||
/// </summary>
|
||||
public static class IEnumerableExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Coalesces the enumerable.
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource">The type of the source.</typeparam>
|
||||
/// <param name="source">The source.</param>
|
||||
public static IEnumerable<TSource> CoalesceEnumerable<TSource>(this IEnumerable<TSource> source)
|
||||
{
|
||||
return source ?? Enumerable.Empty<TSource>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Selects a collection and returns an array.
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource">The type of the source.</typeparam>
|
||||
/// <typeparam name="TResult">The result of the selector function.</typeparam>
|
||||
/// <param name="source">The source.</param>
|
||||
/// <param name="selector">The selector.</param>
|
||||
public static TResult[] SelectArray<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
|
||||
{
|
||||
return source.Select(selector).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Selects a collection and returns an array.
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource">The type of the source.</typeparam>
|
||||
/// <typeparam name="TResult">The result of the selector function.</typeparam>
|
||||
/// <param name="source">The source.</param>
|
||||
/// <param name="selector">The selector.</param>
|
||||
public static TResult[] SelectManyArray<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector)
|
||||
{
|
||||
return source.SelectMany(selector).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a distinct array.
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource">The type of the source.</typeparam>
|
||||
/// <param name="source">The source.</param>
|
||||
/// <param name="comparer">The comparer.</param>
|
||||
public static TSource[] DistinctArray<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer = null)
|
||||
{
|
||||
return source.Distinct(comparer ?? EqualityComparer<TSource>.Default).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an insensitive dictionary from an enumerable.
|
||||
/// </summary>
|
||||
/// <param name="source">The enumerable.</param>
|
||||
/// <param name="keySelector">The key selector.</param>
|
||||
public static InsensitiveDictionary<TValue> ToInsensitiveDictionary<TValue>(this IEnumerable<TValue> source, Func<TValue, string> keySelector)
|
||||
{
|
||||
var dictionary = new InsensitiveDictionary<TValue>();
|
||||
foreach (var value in source)
|
||||
{
|
||||
dictionary[keySelector(value)] = value;
|
||||
}
|
||||
|
||||
return dictionary;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an insensitive dictionary from an enumerable.
|
||||
/// </summary>
|
||||
/// <param name="source">The enumerable.</param>
|
||||
/// <param name="keySelector">The key selector.</param>
|
||||
/// <param name="valueSelector">The value selector.</param>
|
||||
public static InsensitiveDictionary<TValue> ToInsensitiveDictionary<TSource, TValue>(this IEnumerable<TSource> source, Func<TSource, string> keySelector, Func<TSource, TValue> valueSelector)
|
||||
{
|
||||
var dictionary = new InsensitiveDictionary<TValue>();
|
||||
foreach (var value in source)
|
||||
{
|
||||
dictionary[keySelector(value)] = valueSelector(value);
|
||||
}
|
||||
|
||||
return dictionary;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a distinct collection based on a key.
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource">The source type.</typeparam>
|
||||
/// <typeparam name="TKeyType">The key type.</typeparam>
|
||||
/// <param name="source">The source collection.</param>
|
||||
/// <param name="keySelector">The key selector.</param>
|
||||
/// <param name="comparer">The comparer.</param>
|
||||
public static IEnumerable<TSource> Distinct<TSource, TKeyType>(this IEnumerable<TSource> source, Func<TSource, TKeyType> keySelector, IEqualityComparer<TKeyType> comparer = null)
|
||||
{
|
||||
var set = new Dictionary<TKeyType, TSource>(comparer ?? EqualityComparer<TKeyType>.Default);
|
||||
foreach (TSource element in source)
|
||||
{
|
||||
TSource value;
|
||||
var key = keySelector(element);
|
||||
if (!set.TryGetValue(key, out value))
|
||||
{
|
||||
yield return element;
|
||||
}
|
||||
else
|
||||
{
|
||||
set[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Batches an enumerable into batches of the specified size.
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource">The source type/</typeparam>
|
||||
/// <param name="source">The enumerable to batch.</param>
|
||||
/// <param name="batchSize">The batch size.</param>
|
||||
public static IEnumerable<IEnumerable<TSource>> Batch<TSource>(this IEnumerable<TSource> source, int batchSize = 10)
|
||||
{
|
||||
var batch = new List<TSource>(batchSize);
|
||||
foreach (var item in source)
|
||||
{
|
||||
batch.Add(item);
|
||||
if (batch.Count >= batchSize)
|
||||
{
|
||||
yield return batch;
|
||||
batch = new List<TSource>(batchSize);
|
||||
}
|
||||
}
|
||||
|
||||
if (batch.Count > 0)
|
||||
{
|
||||
yield return batch;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,127 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions
|
||||
{
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Management.Automation;
|
||||
|
||||
/// <summary>
|
||||
/// A helper class for converting <see cref="JObject"/> and <see cref="JToken"/> objects to <see cref="PSObject"/> classes.
|
||||
/// </summary>
|
||||
internal static class JTokenExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// A lookup table that contains the native mappings which are supported.
|
||||
/// </summary>
|
||||
private static readonly Dictionary<JTokenType, Type> PrimitiveTypeMap = new Dictionary<JTokenType, Type>()
|
||||
{
|
||||
{ JTokenType.String, typeof(string) },
|
||||
{ JTokenType.Integer, typeof(long) },
|
||||
{ JTokenType.Float, typeof(double) },
|
||||
{ JTokenType.Boolean, typeof(bool) },
|
||||
{ JTokenType.Null, typeof(object) },
|
||||
{ JTokenType.Date, typeof(DateTime) },
|
||||
{ JTokenType.Bytes, typeof(byte[]) },
|
||||
{ JTokenType.Guid, typeof(Guid) },
|
||||
{ JTokenType.Uri, typeof(Uri) },
|
||||
{ JTokenType.TimeSpan, typeof(TimeSpan) },
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Converts a <see cref="JObject"/> to a <see cref="PSObject"/>
|
||||
/// </summary>
|
||||
/// <param name="jtoken">The <see cref="JObject"/></param>
|
||||
/// <param name="objectType">The type of the object.</param>
|
||||
internal static PSObject ToPsObject(this JToken jtoken, string objectType = null)
|
||||
{
|
||||
if (jtoken == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (jtoken.Type != JTokenType.Object)
|
||||
{
|
||||
return new PSObject(JTokenExtensions.ConvertPropertyValueForPsObject(propertyValue: jtoken));
|
||||
}
|
||||
|
||||
var jobject = (JObject)jtoken;
|
||||
var psObject = new PSObject();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(objectType))
|
||||
{
|
||||
psObject.TypeNames.Add(objectType);
|
||||
}
|
||||
|
||||
foreach (var property in jobject.Properties())
|
||||
{
|
||||
psObject.Properties.Add(new PSNoteProperty(
|
||||
name: property.Name,
|
||||
value: JTokenExtensions.ConvertPropertyValueForPsObject(propertyValue: property.Value)));
|
||||
}
|
||||
|
||||
return psObject;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a property value for a <see cref="JObject"/> into an <see cref="object"/> that can be
|
||||
/// used as the value of a <see cref="PSNoteProperty"/>.
|
||||
/// </summary>
|
||||
/// <param name="propertyValue">The <see cref="JToken"/> value.</param>
|
||||
internal static object ConvertPropertyValueForPsObject(JToken propertyValue)
|
||||
{
|
||||
if (propertyValue.Type == JTokenType.Object)
|
||||
{
|
||||
return propertyValue.ToPsObject();
|
||||
}
|
||||
|
||||
if (propertyValue.Type == JTokenType.Array)
|
||||
{
|
||||
var jArray = (JArray)propertyValue;
|
||||
|
||||
var array = new object[jArray.Count];
|
||||
|
||||
for (int i = 0; i < array.Length; ++i)
|
||||
{
|
||||
array[i] = JTokenExtensions.ConvertPropertyValueForPsObject(jArray[i]);
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
Type primitiveType;
|
||||
if (JTokenExtensions.PrimitiveTypeMap.TryGetValue(propertyValue.Type, out primitiveType))
|
||||
{
|
||||
try
|
||||
{
|
||||
return propertyValue.ToObject(primitiveType, JsonExtensions.JsonObjectTypeSerializer);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return propertyValue.ToString();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,243 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Json;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
|
||||
/// <summary>
|
||||
/// <c>JSON</c> extensions
|
||||
/// </summary>
|
||||
public static class JsonExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// The JSON content type for HTTP requests.
|
||||
/// </summary>
|
||||
public const string JsonContentType = "application/json";
|
||||
|
||||
/// <summary>
|
||||
/// The JSON object serialization settings.
|
||||
/// </summary>
|
||||
public static readonly JsonSerializerSettings ObjectSerializationSettings = new JsonSerializerSettings
|
||||
{
|
||||
TypeNameHandling = TypeNameHandling.None,
|
||||
DateParseHandling = DateParseHandling.None,
|
||||
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
MissingMemberHandling = MissingMemberHandling.Ignore,
|
||||
ContractResolver = new CamelCasePropertyNamesWithOverridesContractResolver(),
|
||||
Converters = new List<JsonConverter>
|
||||
{
|
||||
new TimeSpanConverter(),
|
||||
new StringEnumConverter { CamelCaseText = false },
|
||||
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AdjustToUniversal },
|
||||
},
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The JSON media serialization settings.
|
||||
/// </summary>
|
||||
public static readonly JsonSerializerSettings MediaSerializationSettings = new JsonSerializerSettings
|
||||
{
|
||||
TypeNameHandling = TypeNameHandling.None,
|
||||
DateParseHandling = DateParseHandling.None,
|
||||
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
ContractResolver = new CamelCasePropertyNamesWithOverridesContractResolver(),
|
||||
Converters = new List<JsonConverter>
|
||||
{
|
||||
new TimeSpanConverter(),
|
||||
new StringEnumConverter { CamelCaseText = false },
|
||||
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AdjustToUniversal },
|
||||
},
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The JSON media type serializer.
|
||||
/// </summary>
|
||||
public static readonly JsonSerializer JsonMediaTypeSerializer = JsonSerializer.Create(JsonExtensions.MediaSerializationSettings);
|
||||
|
||||
/// <summary>
|
||||
/// The JSON object type serializer.
|
||||
/// </summary>
|
||||
public static readonly JsonSerializer JsonObjectTypeSerializer = JsonSerializer.Create(JsonExtensions.ObjectSerializationSettings);
|
||||
|
||||
/// <summary>
|
||||
/// Serialize object to the JSON.
|
||||
/// </summary>
|
||||
/// <param name="obj">The object.</param>
|
||||
public static string ToJson(this object obj)
|
||||
{
|
||||
return JsonConvert.SerializeObject(obj, JsonExtensions.ObjectSerializationSettings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serialize object to formatted JSON.
|
||||
/// </summary>
|
||||
/// <param name="obj">The object.</param>
|
||||
public static string ToFormattedJson(this object obj)
|
||||
{
|
||||
return JsonConvert.SerializeObject(obj, Formatting.Indented);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserialize object from the JSON.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type of object</typeparam>
|
||||
/// <param name="json">JSON representation of object</param>
|
||||
public static T FromJson<T>(this string json)
|
||||
{
|
||||
return JsonConvert.DeserializeObject<T>(json, JsonExtensions.ObjectSerializationSettings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserialize object from a JSON stream.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type of object</typeparam>
|
||||
/// <param name="stream">A <see cref="Stream"/> that contains a JSON representation of object</param>
|
||||
public static T FromJson<T>(this Stream stream)
|
||||
{
|
||||
using (var streamReader = new StreamReader(stream))
|
||||
using (var jsonReader = new JsonTextReader(streamReader))
|
||||
{
|
||||
return JsonExtensions.JsonObjectTypeSerializer.Deserialize<T>(jsonReader);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serialize object to JToken.
|
||||
/// </summary>
|
||||
/// <param name="obj">The object.</param>
|
||||
public static JToken ToJToken(this object obj)
|
||||
{
|
||||
if (obj == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return JToken.FromObject(obj, JsonExtensions.JsonObjectTypeSerializer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a conversion from the supplied <see cref="JToken"/> to a <typeparamref name="TType"/> can be made.
|
||||
/// </summary>
|
||||
/// <typeparam name="TType">The type to convert to.</typeparam>
|
||||
/// <param name="jobject">The <see cref="JObject"/>.</param>
|
||||
public static bool CanConvertTo<TType>(this JToken jobject)
|
||||
{
|
||||
TType ignored;
|
||||
return jobject.TryConvertTo(out ignored);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a conversion from the supplied <see cref="JToken"/> to a <typeparamref name="TType"/> can be made.
|
||||
/// </summary>
|
||||
/// <typeparam name="TType">The type to convert to.</typeparam>
|
||||
/// <param name="str">The string.</param>
|
||||
/// <param name="result">The result.</param>
|
||||
public static bool TryConvertTo<TType>(this string str, out TType result)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(str))
|
||||
{
|
||||
result = default(TType);
|
||||
return true;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
result = str.FromJson<TType>();
|
||||
return !object.Equals(result, default(TType));
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
}
|
||||
|
||||
result = default(TType);
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a conversion from the supplied <see cref="JToken"/> to a <typeparamref name="TType"/> can be made.
|
||||
/// </summary>
|
||||
/// <typeparam name="TType">The type to convert to.</typeparam>
|
||||
/// <param name="jobject">The <see cref="JObject"/>.</param>
|
||||
/// <param name="result">The result.</param>
|
||||
public static bool TryConvertTo<TType>(this JToken jobject, out TType result)
|
||||
{
|
||||
if (jobject == null)
|
||||
{
|
||||
result = default(TType);
|
||||
return true;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
result = jobject.ToObject<TType>(JsonExtensions.JsonMediaTypeSerializer);
|
||||
return !object.Equals(result, default(TType));
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
}
|
||||
|
||||
result = default(TType);
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts an <see cref="IDictionary"/> object to <see cref="JObject"/> with an extra level labeled as "value".
|
||||
/// </summary>
|
||||
/// <param name="dict">The <see cref="IDictionary"/> object.</param>
|
||||
/// <param name="keys">The key set to extract from the <see cref="IDictionary"/> object. Default is all keys.</param>
|
||||
/// <returns>The conversion result.</returns>
|
||||
public static JObject ToJObjectWithValue(this IDictionary dict, IEnumerable keys = null)
|
||||
{
|
||||
if (dict == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (keys == null)
|
||||
{
|
||||
keys = dict.Keys;
|
||||
}
|
||||
var parameterObject = new JObject();
|
||||
foreach (string paramKey in keys)
|
||||
{
|
||||
var valueObject = new JObject();
|
||||
valueObject.Add("value", dict[paramKey].ToJToken());
|
||||
parameterObject.Add(paramKey, valueObject);
|
||||
}
|
||||
return parameterObject;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// The object extension methods.
|
||||
/// </summary>
|
||||
public static class ObjectExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Casts the specified object to type T.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type to cast to</typeparam>
|
||||
/// <param name="obj">The input object</param>
|
||||
public static T Cast<T>(this object obj)
|
||||
{
|
||||
return (T)obj;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wraps the object in an array of length 1.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type of object to wrap.</typeparam>
|
||||
/// <param name="obj">Object to wrap in array.</param>
|
||||
public static T[] AsArray<T>(this T obj)
|
||||
{
|
||||
return new T[] { obj };
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,165 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions
|
||||
{
|
||||
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Collections;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Management.Automation;
|
||||
|
||||
/// <summary>
|
||||
/// A helper class that handles common tasks that deal with the <see cref="ResourcePropertyObject"/> class.
|
||||
/// </summary>
|
||||
public static class PsObjectExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// The properties to remove.
|
||||
/// </summary>
|
||||
private static readonly InsensitiveDictionary<bool> PropertiesToRemove = new InsensitiveDictionary<bool>
|
||||
{
|
||||
{ "ResourceId", false },
|
||||
{ "ResourceName", false },
|
||||
{ "ResourceType", false},
|
||||
{ "ExtensionResourceName", false },
|
||||
{ "ExtensionResourceType", false },
|
||||
{ "ResourceGroupName", false },
|
||||
{ "SubscriptionId", false },
|
||||
{ "Tags", false },
|
||||
{ "PropertiesText", false },
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Converts a <see cref="ResourcePropertyObject"/> to <see cref="JToken"/>
|
||||
/// </summary>
|
||||
/// <param name="propertyObject">The <see cref="ResourcePropertyObject"/></param>
|
||||
internal static JToken ToResourcePropertiesBody(this PSObject propertyObject)
|
||||
{
|
||||
return PsObjectExtensions.ToJToken(propertyObject);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper method for converting <see cref="Object"/> to <see cref="JToken"/>
|
||||
/// </summary>
|
||||
/// <param name="value">The object.</param>
|
||||
private static JToken ToJToken(object value)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var valueAsPsObject = value as PSObject;
|
||||
if (valueAsPsObject != null)
|
||||
{
|
||||
JObject obj = new JObject();
|
||||
if (valueAsPsObject.BaseObject != null && valueAsPsObject.BaseObject is IDictionary)
|
||||
{
|
||||
var valueAsIDictionary = valueAsPsObject.BaseObject as IDictionary;
|
||||
var dictionaryEntries = valueAsIDictionary is IDictionary<string, object>
|
||||
? valueAsIDictionary.OfType<KeyValuePair<string, object>>().Select(kvp => Tuple.Create(kvp.Key, kvp.Value))
|
||||
: valueAsIDictionary.OfType<DictionaryEntry>().Select(dictionaryEntry => Tuple.Create(dictionaryEntry.Key.ToString(), dictionaryEntry.Value));
|
||||
|
||||
dictionaryEntries = dictionaryEntries.Any(dictionaryEntry => dictionaryEntry.Item1.EqualsInsensitively(Constants.MicrosoftAzureResource))
|
||||
? dictionaryEntries.Where(dictionaryEntry => !PsObjectExtensions.PropertiesToRemove.ContainsKey(dictionaryEntry.Item1))
|
||||
: dictionaryEntries;
|
||||
|
||||
foreach (var dictionaryEntry in dictionaryEntries)
|
||||
{
|
||||
obj.Add(dictionaryEntry.Item1, PsObjectExtensions.ToJToken(dictionaryEntry.Item2));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var properties = (valueAsPsObject.TypeNames.Any(typeName => typeName.EqualsInsensitively(Constants.MicrosoftAzureResource)))
|
||||
? valueAsPsObject.Properties.Where(property => !PsObjectExtensions.PropertiesToRemove.ContainsKey(property.Name))
|
||||
: valueAsPsObject.Properties.AsEnumerable();
|
||||
|
||||
foreach (var member in properties)
|
||||
{
|
||||
obj.Add(member.Name, PsObjectExtensions.ToJToken(member.Value));
|
||||
}
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
var valueAsDictionary = value as IDictionary;
|
||||
if (valueAsDictionary != null)
|
||||
{
|
||||
JObject obj = new JObject();
|
||||
var dictionaryEntries = valueAsDictionary is IDictionary<string, object>
|
||||
? valueAsDictionary.OfType<KeyValuePair<string, object>>().Select(kvp => Tuple.Create(kvp.Key, kvp.Value))
|
||||
: valueAsDictionary.OfType<DictionaryEntry>().Select(dictionaryEntry => Tuple.Create(dictionaryEntry.Key.ToString(), dictionaryEntry.Value));
|
||||
|
||||
dictionaryEntries = dictionaryEntries.Any(dictionaryEntry => dictionaryEntry.Item1.EqualsInsensitively(Constants.MicrosoftAzureResource))
|
||||
? dictionaryEntries.Where(dictionaryEntry => !PsObjectExtensions.PropertiesToRemove.ContainsKey(dictionaryEntry.Item1))
|
||||
: dictionaryEntries;
|
||||
|
||||
foreach (var dictionaryEntry in dictionaryEntries)
|
||||
{
|
||||
obj.Add(dictionaryEntry.Item1, PsObjectExtensions.ToJToken(dictionaryEntry.Item2));
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
var valueAsIList = value as IList;
|
||||
if (valueAsIList != null)
|
||||
{
|
||||
var tmpList = new List<JToken>();
|
||||
foreach (var v in valueAsIList)
|
||||
{
|
||||
tmpList.Add(PsObjectExtensions.ToJToken(v));
|
||||
}
|
||||
|
||||
return JArray.FromObject(tmpList.ToArray());
|
||||
}
|
||||
|
||||
return new JValue(value.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets nested property values from a <see cref="PSObject"/> easily using property path.
|
||||
/// </summary>
|
||||
/// <param name="propertyObject">The <see cref="PSObject"/> to get property value from.</param>
|
||||
/// <param name="propertyPath">The nested property path, e.g. "metadata.description".</param>
|
||||
/// <returns>The value of the specified property.</returns>
|
||||
internal static object GetPSObjectProperty(this PSObject propertyObject, string propertyPath)
|
||||
{
|
||||
var propertyNames = propertyPath.Split('.');
|
||||
var tmpObject = propertyObject;
|
||||
foreach (var propertyName in propertyNames)
|
||||
{
|
||||
var propertyInfo = tmpObject.Properties[propertyName];
|
||||
if (propertyInfo != null)
|
||||
{
|
||||
if (propertyInfo.Value is PSObject)
|
||||
{
|
||||
tmpObject = propertyInfo.Value as PSObject;
|
||||
continue;
|
||||
}
|
||||
return propertyInfo.Value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return tmpObject;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources;
|
||||
using Microsoft.WindowsAzure.Commands.Utilities.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Management.Automation;
|
||||
|
||||
/// <summary>
|
||||
/// A helper class that handles common tasks that deal with the <see cref="Resource{JToken}"/> class.
|
||||
/// </summary>
|
||||
internal static class ResourceExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts a <see cref="Resource{JToken}"/> object into a <see cref="PSObject"/> object.
|
||||
/// </summary>
|
||||
/// <param name="resource">The <see cref="Resource{JToken}"/> object.</param>
|
||||
internal static PSObject ToPsObject(this Resource<JToken> resource)
|
||||
{
|
||||
var resourceType = string.IsNullOrEmpty(resource.Id)
|
||||
? null
|
||||
: ResourceIdUtility.GetResourceType(resource.Id);
|
||||
|
||||
var extensionResourceType = string.IsNullOrEmpty(resource.Id)
|
||||
? null
|
||||
: ResourceIdUtility.GetExtensionResourceType(resource.Id);
|
||||
|
||||
var objectDefinition = new Dictionary<string, object>
|
||||
{
|
||||
{ "Name", resource.Name },
|
||||
{ "ResourceId", string.IsNullOrEmpty(resource.Id) ? null : resource.Id },
|
||||
{ "ResourceName", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceName(resource.Id) },
|
||||
{ "ResourceType", resourceType },
|
||||
{ "ExtensionResourceName", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetExtensionResourceName(resource.Id) },
|
||||
{ "ExtensionResourceType", extensionResourceType },
|
||||
{ "Kind", resource.Kind },
|
||||
{ "ResourceGroupName", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceGroupName(resource.Id) },
|
||||
{ "Location", resource.Location },
|
||||
{ "SubscriptionId", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetSubscriptionId(resource.Id) },
|
||||
{ "Tags", TagsHelper.GetTagsHashtable(resource.Tags) },
|
||||
{ "Plan", resource.Plan.ToJToken().ToPsObject() },
|
||||
{ "Properties", ResourceExtensions.GetProperties(resource) },
|
||||
{ "CreatedTime", resource.CreatedTime },
|
||||
{ "ChangedTime", resource.ChangedTime },
|
||||
{ "ETag", resource.ETag },
|
||||
{ "Sku", resource.Sku.ToJToken().ToPsObject() }
|
||||
};
|
||||
|
||||
var resourceTypeName = resourceType == null && extensionResourceType == null
|
||||
? null
|
||||
: (resourceType + extensionResourceType).Replace('/', '.');
|
||||
|
||||
var psObject =
|
||||
PowerShellUtilities.ConstructPSObject(
|
||||
resourceTypeName,
|
||||
objectDefinition.Where(kvp => kvp.Value != null).SelectManyArray(kvp => new[] { kvp.Key, kvp.Value }));
|
||||
|
||||
psObject.TypeNames.Add(Constants.MicrosoftAzureResource);
|
||||
return psObject;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the properties object
|
||||
/// </summary>
|
||||
/// <param name="resource">The <see cref="Resource{JToken}"/> object.</param>
|
||||
private static object GetProperties(Resource<JToken> resource)
|
||||
{
|
||||
if (resource.Properties == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return (object)resource.Properties.ToPsObject();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a <see cref="JToken"/> to a <see cref="Resource{JToken}"/>.
|
||||
/// </summary>
|
||||
/// <param name="jtoken">The <see cref="JToken"/>.</param>
|
||||
internal static Resource<JToken> ToResource(this JToken jtoken)
|
||||
{
|
||||
return jtoken.ToObject<Resource<JToken>>(JsonExtensions.JsonMediaTypeSerializer);
|
||||
}
|
||||
|
||||
/// <summary>00
|
||||
/// Converts a <see cref="JToken"/> to a <see cref="Resource{JToken}"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TType">The type of the properties.</typeparam>
|
||||
/// <param name="jtoken">The <see cref="JToken"/>.</param>
|
||||
internal static Resource<TType> ToResource<TType>(this JToken jtoken)
|
||||
{
|
||||
return jtoken.ToObject<Resource<TType>>(JsonExtensions.JsonMediaTypeSerializer);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Handlers
|
||||
{
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// The authentication handler.
|
||||
/// </summary>
|
||||
public class AuthenticationHandler : DelegatingHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// The subscription cloud credentials.
|
||||
/// </summary>
|
||||
private readonly SubscriptionCloudCredentials cloudCredentials;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AuthenticationHandler" /> class.
|
||||
/// </summary>
|
||||
/// <param name="cloudCredentials">The credentials.</param>
|
||||
public AuthenticationHandler(SubscriptionCloudCredentials cloudCredentials)
|
||||
{
|
||||
this.cloudCredentials = cloudCredentials;
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add the authentication token to the outgoing request.
|
||||
/// </summary>
|
||||
/// <param name="request">The HTTP request message.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
await this.cloudCredentials
|
||||
.ProcessHttpRequestAsync(request: request, cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
|
||||
return await base
|
||||
.SendAsync(request, cancellationToken)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Handlers
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// The cmdlet info handler.
|
||||
/// </summary>
|
||||
public class CmdletInfoHandler : DelegatingHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// The product info to add as headers.
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, string> cmdletHeaderValues;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CmdletInfoHandler" /> class.
|
||||
/// </summary>
|
||||
/// <param name="headerValues">The product info to add as headers.</param>
|
||||
public CmdletInfoHandler(Dictionary<string, string> cmdletHeaderValues)
|
||||
{
|
||||
this.cmdletHeaderValues = cmdletHeaderValues;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add the custom headers to the outgoing request.
|
||||
/// </summary>
|
||||
/// <param name="request">The HTTP request message.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (KeyValuePair<string, string> kvp in cmdletHeaderValues)
|
||||
{
|
||||
request.Headers.Add(kvp.Key, kvp.Value);
|
||||
}
|
||||
|
||||
return await base
|
||||
.SendAsync(request, cancellationToken)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,108 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Handlers
|
||||
{
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Utilities;
|
||||
|
||||
/// <summary>
|
||||
/// A basic retry handler.
|
||||
/// </summary>
|
||||
public class RetryHandler : DelegatingHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// The max number of attempts.
|
||||
/// </summary>
|
||||
private const int MaxAttempts = 3;
|
||||
|
||||
/// <summary>
|
||||
/// The delta back-off.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan DeltaBackoff = TimeSpan.FromSeconds(3);
|
||||
|
||||
/// <summary>
|
||||
/// The max back-off.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan MaxBackoff = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>
|
||||
/// The min back-off.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan MinBackoff = TimeSpan.FromSeconds(1);
|
||||
|
||||
/// <summary>
|
||||
/// Add the authentication token to the outgoing request.
|
||||
/// </summary>
|
||||
/// <param name="request">The HTTP request message.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
HttpResponseMessage response = null;
|
||||
|
||||
for (int attempt = 1; attempt <= RetryHandler.MaxAttempts; ++attempt)
|
||||
{
|
||||
try
|
||||
{
|
||||
response = await base
|
||||
.SendAsync(request: request, cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
|
||||
if (attempt == RetryHandler.MaxAttempts ||
|
||||
(!response.StatusCode.IsServerFailureRequest() &&
|
||||
response.StatusCode != HttpStatusCode.RequestTimeout &&
|
||||
response.StatusCode != HttpStatusCodeExt.TooManyRequests))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ex.IsFatal() || attempt == RetryHandler.MaxAttempts)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
if (response != null)
|
||||
{
|
||||
response.Dispose();
|
||||
}
|
||||
|
||||
await Task.Delay(delay: RetryHandler.GetDelay(attempt), cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the delay for the task following an exponential back-off strategy
|
||||
/// </summary>
|
||||
/// <param name="attempt">The current attempt.</param>
|
||||
private static TimeSpan GetDelay(int attempt)
|
||||
{
|
||||
var random = new Random((int)(DateTime.UtcNow.Ticks & 0xFFFF));
|
||||
int num = (int)((Math.Pow(2.0, attempt) - 1.0) * (double)random.Next((int)(RetryHandler.DeltaBackoff.TotalMilliseconds * 0.8), (int)(RetryHandler.DeltaBackoff.TotalMilliseconds * 1.2)));
|
||||
int num2 = (int)Math.Min(RetryHandler.MinBackoff.TotalMilliseconds + num, RetryHandler.MaxBackoff.TotalMilliseconds);
|
||||
return TimeSpan.FromMilliseconds(num2);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Handlers
|
||||
{
|
||||
using Hyak.Common;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Tracing handler.
|
||||
/// </summary>
|
||||
public class TracingHandler : DelegatingHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// Trace the outgoing request.
|
||||
/// </summary>
|
||||
/// <param name="request">The HTTP request message.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!TracingAdapter.IsEnabled)
|
||||
{
|
||||
return await base.SendAsync(request: request, cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
|
||||
var invocationId = TracingAdapter.NextInvocationId.ToString();
|
||||
try
|
||||
{
|
||||
TracingAdapter.SendRequest(invocationId: invocationId, request: request);
|
||||
var response = await base.SendAsync(request: request, cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
TracingAdapter.ReceiveResponse(invocationId: invocationId, response: response);
|
||||
return response;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ex.IsFatal())
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
TracingAdapter.Error(invocationId: invocationId, ex: ex);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Handlers
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// The user agent handler.
|
||||
/// </summary>
|
||||
public class UserAgentHandler : DelegatingHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// The product info to add as headers.
|
||||
/// </summary>
|
||||
private readonly IEnumerable<ProductInfoHeaderValue> headerValues;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserAgentHandler" /> class.
|
||||
/// </summary>
|
||||
/// <param name="headerValues">The product info to add as headers.</param>
|
||||
public UserAgentHandler(IEnumerable<ProductInfoHeaderValue> headerValues)
|
||||
{
|
||||
this.headerValues = headerValues;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add the user agent to the outgoing request.
|
||||
/// </summary>
|
||||
/// <param name="request">The HTTP request message.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var currentRequestHeaders = request.Headers.UserAgent
|
||||
.ToInsensitiveDictionary(header => header.Product.Name + header.Product.Version);
|
||||
|
||||
var infosToAdd = this.headerValues
|
||||
.Where(productInfo => !currentRequestHeaders.ContainsKey(productInfo.Product.Name + productInfo.Product.Version));
|
||||
|
||||
foreach (var infoToAdd in infosToAdd)
|
||||
{
|
||||
request.Headers.UserAgent.Add(infoToAdd);
|
||||
}
|
||||
|
||||
return await base
|
||||
.SendAsync(request, cancellationToken)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using ResourceManager.Common;
|
||||
using Microsoft.WindowsAzure.Commands.Utilities.Common;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkClient;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for all feature cmdlets
|
||||
/// </summary>
|
||||
public abstract class ProviderFeatureCmdletBase : AzureRMCmdlet
|
||||
{
|
||||
/// <summary>
|
||||
/// Cache for the feature client
|
||||
/// </summary>
|
||||
private ProviderFeatureClient providerFeatureClient;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the feature client
|
||||
/// </summary>
|
||||
public ProviderFeatureClient ProviderFeatureClient
|
||||
{
|
||||
get
|
||||
{
|
||||
if (this.providerFeatureClient == null)
|
||||
{
|
||||
this.providerFeatureClient = new ProviderFeatureClient(DefaultContext);
|
||||
}
|
||||
|
||||
return this.providerFeatureClient;
|
||||
}
|
||||
|
||||
set { this.providerFeatureClient = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines the parameter set name.
|
||||
/// </summary>
|
||||
public virtual string DetermineParameterSetName()
|
||||
{
|
||||
return this.ParameterSetName;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,465 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
using Microsoft.Azure.Commands.Common.Authentication;
|
||||
using Microsoft.Azure.Commands.Common.Authentication.Models;
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Commands.Common.Authentication.Abstractions;
|
||||
using Common;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.ErrorResponses;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.RestClients;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkClient;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Management.Automation;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// The base class for resource manager cmdlets.
|
||||
/// </summary>
|
||||
public abstract class ResourceManagerCmdletBase : AzureRMCmdlet
|
||||
{
|
||||
/// <summary>
|
||||
/// The cancellation source.
|
||||
/// </summary>
|
||||
private CancellationTokenSource cancellationSource;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the cancellation source.
|
||||
/// </summary>
|
||||
protected CancellationToken? CancellationToken
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.cancellationSource == null ? null : (CancellationToken?)this.cancellationSource.Token;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Field that holds the resource client instance
|
||||
/// </summary>
|
||||
private ResourceManagerSdkClient resourceManagerSdkClient;
|
||||
|
||||
/// <summary>
|
||||
/// Field that holds the subscripotions client instance
|
||||
/// </summary>
|
||||
private SubscriptionSdkClient subscriptionSdkClient;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the API version.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "When set, indicates the version of the resource provider API to use. If not specified, the API version is automatically determined as the latest available.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ApiVersion { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the switch that indicates if pre-release API version should be considered.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "When set, indicates that the cmdlet should use pre-release API versions when automatically determining which version to use.")]
|
||||
public SwitchParameter Pre { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The <c>BeginProcessing</c> method.
|
||||
/// </summary>
|
||||
protected override void BeginProcessing()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (this.cancellationSource == null)
|
||||
{
|
||||
this.cancellationSource = new CancellationTokenSource();
|
||||
}
|
||||
|
||||
base.BeginProcessing();
|
||||
this.OnBeginProcessing();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ex.IsFatal())
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
var capturedException = ExceptionDispatchInfo.Capture(ex);
|
||||
this.HandleException(capturedException: capturedException);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <c>StopProcessing</c> method.
|
||||
/// </summary>
|
||||
protected override void StopProcessing()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (this.cancellationSource != null && !this.cancellationSource.IsCancellationRequested)
|
||||
{
|
||||
this.cancellationSource.Cancel();
|
||||
}
|
||||
|
||||
this.OnStopProcessing();
|
||||
base.StopProcessing();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ex.IsFatal())
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
var capturedException = ExceptionDispatchInfo.Capture(ex);
|
||||
this.HandleException(capturedException: capturedException);
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.DisposeOfCancellationSource();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <c>EndProcessing</c> method.
|
||||
/// </summary>
|
||||
protected override void EndProcessing()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.OnEndProcessing();
|
||||
base.EndProcessing();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ex.IsFatal())
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
var capturedException = ExceptionDispatchInfo.Capture(ex);
|
||||
this.HandleException(capturedException: capturedException);
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.DisposeOfCancellationSource();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <c>ProcessRecord</c> method.
|
||||
/// </summary>
|
||||
public override void ExecuteCmdlet()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (this.cancellationSource == null)
|
||||
{
|
||||
this.cancellationSource = new CancellationTokenSource();
|
||||
}
|
||||
|
||||
base.ExecuteCmdlet();
|
||||
this.OnProcessRecord();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ex.IsFatal())
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
var capturedException = ExceptionDispatchInfo.Capture(ex);
|
||||
this.HandleException(capturedException: capturedException);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When overridden, allows child classes to be called when the <c>ProcessRecord</c> method is invoked.
|
||||
/// </summary>
|
||||
protected virtual void OnProcessRecord()
|
||||
{
|
||||
// no-op
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When overridden, allows child classes to be called when the <c>EndProcessing</c> method is invoked.
|
||||
/// </summary>
|
||||
protected virtual void OnEndProcessing()
|
||||
{
|
||||
// no-op
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When overridden, allows child classes to be called when the <c>BeginProcessing</c> method is invoked.
|
||||
/// </summary>
|
||||
protected virtual void OnBeginProcessing()
|
||||
{
|
||||
// no-op
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When overridden, allows child classes to be called when the <c>StopProcessing</c> method is invoked.
|
||||
/// </summary>
|
||||
protected virtual void OnStopProcessing()
|
||||
{
|
||||
// no-op
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines the API version.
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource Id.</param>
|
||||
/// <param name="pre">When specified, indicates if pre-release API versions should be considered.</param>
|
||||
protected Task<string> DetermineApiVersion(string resourceId, bool? pre = null)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(this.ApiVersion)
|
||||
? ApiVersionHelper.DetermineApiVersion(
|
||||
context: DefaultContext,
|
||||
resourceId: resourceId,
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
pre: pre ?? this.Pre,
|
||||
cmdletHeaderValues: this.GetCmdletHeaders())
|
||||
: Task.FromResult(this.ApiVersion);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines the API version.
|
||||
/// </summary>
|
||||
/// <param name="providerNamespace">The provider namespace.</param>
|
||||
/// <param name="resourceType">The resource type.</param>
|
||||
/// <param name="pre">When specified, indicates if pre-release API versions should be considered.</param>
|
||||
protected Task<string> DetermineApiVersion(string providerNamespace, string resourceType, bool? pre = null)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(this.ApiVersion)
|
||||
? ApiVersionHelper.DetermineApiVersion(
|
||||
DefaultContext,
|
||||
providerNamespace: providerNamespace,
|
||||
resourceType: resourceType,
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
pre: pre ?? this.Pre,
|
||||
cmdletHeaderValues: this.GetCmdletHeaders())
|
||||
: Task.FromResult(this.ApiVersion);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a new instance of the <see cref="ResourceManagerRestRestClient"/>.
|
||||
/// </summary>
|
||||
public ResourceManagerRestRestClient GetResourcesClient()
|
||||
{
|
||||
var endpoint = DefaultContext.Environment.GetEndpoint(AzureEnvironment.Endpoint.ResourceManager);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(endpoint))
|
||||
{
|
||||
throw new ApplicationException(
|
||||
"The endpoint for the Azure Resource Manager service is not set. Please report this issue via GitHub or contact Microsoft customer support.");
|
||||
}
|
||||
|
||||
var endpointUri = new Uri(endpoint, UriKind.Absolute);
|
||||
|
||||
return new ResourceManagerRestRestClient(
|
||||
endpointUri: endpointUri,
|
||||
httpClientHelper: HttpClientHelperFactory.Instance
|
||||
.CreateHttpClientHelper(
|
||||
credentials: AzureSession.Instance.AuthenticationFactory
|
||||
.GetSubscriptionCloudCredentials(
|
||||
DefaultContext,
|
||||
AzureEnvironment.Endpoint.ResourceManager),
|
||||
headerValues: AzureSession.Instance.ClientFactory.UserAgents,
|
||||
cmdletHeaderValues: this.GetCmdletHeaders()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the resource manager sdk client
|
||||
/// </summary>
|
||||
public ResourceManagerSdkClient ResourceManagerSdkClient
|
||||
{
|
||||
get
|
||||
{
|
||||
if (this.resourceManagerSdkClient == null)
|
||||
{
|
||||
this.resourceManagerSdkClient = new ResourceManagerSdkClient(DefaultContext);
|
||||
}
|
||||
|
||||
this.resourceManagerSdkClient.VerboseLogger = WriteVerboseWithTimestamp;
|
||||
this.resourceManagerSdkClient.ErrorLogger = WriteErrorWithTimestamp;
|
||||
this.resourceManagerSdkClient.WarningLogger = WriteWarningWithTimestamp;
|
||||
|
||||
return this.resourceManagerSdkClient;
|
||||
}
|
||||
|
||||
set { this.resourceManagerSdkClient = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the subscription sdk client
|
||||
/// </summary>
|
||||
public SubscriptionSdkClient SubscriptionSdkClient
|
||||
{
|
||||
get
|
||||
{
|
||||
if (this.subscriptionSdkClient == null)
|
||||
{
|
||||
this.subscriptionSdkClient = new SubscriptionSdkClient(DefaultContext)
|
||||
{
|
||||
VerboseLogger = WriteVerboseWithTimestamp,
|
||||
ErrorLogger = WriteErrorWithTimestamp,
|
||||
WarningLogger = WriteWarningWithTimestamp
|
||||
};
|
||||
}
|
||||
return this.subscriptionSdkClient;
|
||||
}
|
||||
|
||||
set { this.subscriptionSdkClient = value; }
|
||||
}
|
||||
|
||||
private Dictionary<string, string> GetCmdletHeaders()
|
||||
{
|
||||
return new Dictionary<string, string>
|
||||
{
|
||||
{"ParameterSetName", this.ParameterSetName },
|
||||
{"CommandName", this.CommandRuntime.ToString() }
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the object
|
||||
/// </summary>
|
||||
/// <param name="resultString">The result as a string</param>
|
||||
protected void TryConvertAndWriteObject(string resultString)
|
||||
{
|
||||
JToken resultJToken;
|
||||
if (resultString.TryConvertTo<JToken>(out resultJToken))
|
||||
{
|
||||
this.WriteObject(resultJToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.WriteObject(resultString);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the object
|
||||
/// </summary>
|
||||
/// <param name="resultString">The result as a string</param>
|
||||
protected void TryConvertToResourceAndWriteObject(string resultString)
|
||||
{
|
||||
Resource<JToken> resultResource;
|
||||
if (resultString.TryConvertTo<Resource<JToken>>(out resultResource))
|
||||
{
|
||||
this.WriteObject(resultResource.ToPsObject());
|
||||
}
|
||||
else
|
||||
{
|
||||
this.WriteObject(resultString);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a <see cref="JToken"/> object as a <see cref="PSObject"/>.
|
||||
/// </summary>
|
||||
/// <param name="result">The result of the action.</param>
|
||||
protected void WriteObject(JToken result)
|
||||
{
|
||||
this.WriteObject(sendToPipeline: result.ToPsObject(), enumerateCollection: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a new instance of the long running operation helper.
|
||||
/// </summary>
|
||||
/// <param name="activityName">The name of the action.</param>
|
||||
/// <param name="isResourceCreateOrUpdate">When set to true, indicates that the tracker will be used to track a resource creation request.</param>
|
||||
internal LongRunningOperationHelper GetLongRunningOperationTracker(string activityName, bool isResourceCreateOrUpdate)
|
||||
{
|
||||
return new LongRunningOperationHelper(
|
||||
activityName: activityName,
|
||||
resourcesClientFactory: () => this.GetResourcesClient(),
|
||||
writeProgressAction: progress => this.WriteProgress(progress),
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
isResourceCreateOrUpdate: isResourceCreateOrUpdate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes of the <see cref="CancellationTokenSource"/>.
|
||||
/// </summary>
|
||||
private void DisposeOfCancellationSource()
|
||||
{
|
||||
if (this.cancellationSource != null)
|
||||
{
|
||||
if (!this.cancellationSource.IsCancellationRequested)
|
||||
{
|
||||
this.cancellationSource.Cancel();
|
||||
}
|
||||
|
||||
this.cancellationSource.Dispose();
|
||||
this.cancellationSource = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provides specialized exception handling.
|
||||
/// </summary>
|
||||
/// <param name="capturedException">The captured exception</param>
|
||||
private void HandleException(ExceptionDispatchInfo capturedException)
|
||||
{
|
||||
try
|
||||
{
|
||||
var errorResponseException = capturedException.SourceException as ErrorResponseMessageException;
|
||||
if (errorResponseException != null)
|
||||
{
|
||||
this.ThrowTerminatingError(errorResponseException.ToErrorRecord());
|
||||
}
|
||||
|
||||
var aggregateException = capturedException.SourceException as AggregateException;
|
||||
if (aggregateException != null)
|
||||
{
|
||||
if (aggregateException.InnerExceptions.CoalesceEnumerable().Any() &&
|
||||
aggregateException.InnerExceptions.Count == 1)
|
||||
{
|
||||
errorResponseException = aggregateException.InnerExceptions.Single() as ErrorResponseMessageException;
|
||||
if (errorResponseException != null)
|
||||
{
|
||||
this.ThrowTerminatingError(errorResponseException.ToErrorRecord());
|
||||
}
|
||||
|
||||
this.ThrowTerminatingError(aggregateException.InnerExceptions.Single().ToErrorRecord());
|
||||
}
|
||||
else
|
||||
{
|
||||
this.ThrowTerminatingError(aggregateException.ToErrorRecord());
|
||||
}
|
||||
}
|
||||
|
||||
capturedException.Throw();
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.DisposeOfCancellationSource();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines the parameter set name.
|
||||
/// </summary>
|
||||
public virtual string DetermineParameterSetName()
|
||||
{
|
||||
return this.ParameterSetName;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,160 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Commands.Common.Authentication.Abstractions;
|
||||
using Common.ArgumentCompleters;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using System;
|
||||
using System.Management.Automation;
|
||||
|
||||
/// <summary>
|
||||
/// The base class for manipulating resources.
|
||||
/// </summary>
|
||||
public abstract class ResourceManipulationCmdletBase : ResourceManagerCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// The subscription level parameter set.
|
||||
/// </summary>
|
||||
internal const string SubscriptionLevelResoruceParameterSet = "BySubscriptionLevel";
|
||||
|
||||
/// <summary>
|
||||
/// The tenant level parameter set.
|
||||
/// </summary>
|
||||
internal const string TenantLevelResoruceParameterSet = "ByTenantLevel";
|
||||
|
||||
/// <summary>
|
||||
/// The tenant level parameter set.
|
||||
/// </summary>
|
||||
internal const string ResourceIdParameterSet = "ByResourceId";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the resource Id parameter.
|
||||
/// </summary>
|
||||
[Alias("Id")]
|
||||
[Parameter(ParameterSetName = ResourceManipulationCmdletBase.ResourceIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified resource Id, including the subscription. e.g. /subscriptions/{subscriptionId}/providers/Microsoft.Sql/servers/myServer/databases/myDatabase")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the extension resource name parameter.
|
||||
/// </summary>
|
||||
[Alias("Name")]
|
||||
[Parameter(ParameterSetName = ResourceManipulationCmdletBase.SubscriptionLevelResoruceParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name. e.g. to specify a database MyServer/MyDatabase.")]
|
||||
[Parameter(ParameterSetName = ResourceManipulationCmdletBase.TenantLevelResoruceParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name. e.g. to specify a database MyServer/MyDatabase.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the resource type parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = ResourceManipulationCmdletBase.SubscriptionLevelResoruceParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource type. e.g. Microsoft.Sql/Servers/Databases.")]
|
||||
[Parameter(ParameterSetName = ResourceManipulationCmdletBase.TenantLevelResoruceParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource type. e.g. Microsoft.Sql/Servers/Databases.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the extension resource name parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = ResourceManipulationCmdletBase.SubscriptionLevelResoruceParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The extension resource name. e.g. to specify a database MyServer/MyDatabase.")]
|
||||
[Parameter(ParameterSetName = ResourceManipulationCmdletBase.TenantLevelResoruceParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The extension resource name. e.g. to specify a database MyServer/MyDatabase.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ExtensionResourceName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the extension resource type parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = ResourceManipulationCmdletBase.SubscriptionLevelResoruceParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The extension resource type. e.g. Microsoft.Sql/Servers/Databases.")]
|
||||
[Parameter(ParameterSetName = ResourceManipulationCmdletBase.TenantLevelResoruceParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The extension resource type. e.g. Microsoft.Sql/Servers/Databases.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ExtensionResourceType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the OData query parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "An OData style filter which will be appended to the request in addition to any other filters.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ODataQuery { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the resource group name parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = ResourceManipulationCmdletBase.SubscriptionLevelResoruceParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")]
|
||||
[ResourceGroupCompleter]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceGroupName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tenant level parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = ResourceManipulationCmdletBase.TenantLevelResoruceParameterSet, Mandatory = true, HelpMessage = "Indicates that this is a tenant level operation.")]
|
||||
public SwitchParameter TenantLevel { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the force parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")]
|
||||
public SwitchParameter Force { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the subscription id.
|
||||
/// </summary>
|
||||
public Guid SubscriptionId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the default subscription id if needed.
|
||||
/// </summary>
|
||||
public ResourceManipulationCmdletBase()
|
||||
{
|
||||
if (string.IsNullOrEmpty(this.ResourceId))
|
||||
{
|
||||
this.SubscriptionId = DefaultContext.Subscription.GetId();
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id from the supplied PowerShell parameters.
|
||||
/// </summary>
|
||||
protected string GetResourceId()
|
||||
{
|
||||
#pragma warning disable 618
|
||||
|
||||
return !string.IsNullOrWhiteSpace(this.ResourceId)
|
||||
? this.ResourceId
|
||||
: this.GetResourceIdWithoutParentResource();
|
||||
|
||||
#pragma warning restore 618
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id from the supplied PowerShell parameters.
|
||||
/// </summary>
|
||||
private string GetResourceIdWithoutParentResource()
|
||||
{
|
||||
return ResourceIdUtility.GetResourceId(
|
||||
subscriptionId: this.SubscriptionId,
|
||||
resourceGroupName: this.ResourceGroupName,
|
||||
resourceType: this.ResourceType,
|
||||
resourceName: this.ResourceName,
|
||||
extensionResourceType: this.ExtensionResourceType,
|
||||
extensionResourceName: this.ExtensionResourceName);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,211 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
using Microsoft.Azure.Commands.Common.Authentication;
|
||||
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Utilities;
|
||||
using Microsoft.WindowsAzure.Commands.Common;
|
||||
using Microsoft.WindowsAzure.Commands.Utilities.Common;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Management.Automation;
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
public abstract class ResourceWithParameterCmdletBase : ResourceManagerCmdletBase
|
||||
{
|
||||
protected const string TemplateFileParameterObjectParameterSetName = "ByTemplateFileAndParameterObject";
|
||||
protected const string TemplateFileParameterFileParameterSetName = "ByTemplateFileAndParameterFile";
|
||||
protected const string TemplateFileParameterUriParameterSetName = "ByTemplateFileAndParameterUri";
|
||||
protected const string TemplateUriParameterObjectParameterSetName = "ByTemplateUriAndParameterObject";
|
||||
protected const string TemplateUriParameterFileParameterSetName = "ByTemplateUriAndParameterFile";
|
||||
protected const string TemplateUriParameterUriParameterSetName = "ByTemplateUriAndParameterUri";
|
||||
protected const string ParameterlessTemplateFileParameterSetName = "ByTemplateFileWithNoParameters";
|
||||
protected const string ParameterlessGalleryTemplateParameterSetName = "ByGalleryWithNoParameters";
|
||||
protected const string ParameterlessTemplateUriParameterSetName = "ByTemplateUriWithNoParameters";
|
||||
|
||||
protected RuntimeDefinedParameterDictionary dynamicParameters;
|
||||
|
||||
private string templateFile;
|
||||
|
||||
private string templateUri;
|
||||
|
||||
protected ResourceWithParameterCmdletBase()
|
||||
{
|
||||
dynamicParameters = new RuntimeDefinedParameterDictionary();
|
||||
}
|
||||
|
||||
[Parameter(ParameterSetName = TemplateFileParameterObjectParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents the parameters.")]
|
||||
[Parameter(ParameterSetName = TemplateUriParameterObjectParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents the parameters.")]
|
||||
public Hashtable TemplateParameterObject { get; set; }
|
||||
|
||||
[Parameter(ParameterSetName = TemplateFileParameterFileParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "A file that has the template parameters.")]
|
||||
[Parameter(ParameterSetName = TemplateUriParameterFileParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "A file that has the template parameters.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string TemplateParameterFile { get; set; }
|
||||
|
||||
[Parameter(ParameterSetName = TemplateFileParameterUriParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Uri to the template parameter file.")]
|
||||
[Parameter(ParameterSetName = TemplateUriParameterUriParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Uri to the template parameter file.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string TemplateParameterUri { get; set; }
|
||||
|
||||
[Parameter(ParameterSetName = TemplateFileParameterObjectParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Local path to the template file.")]
|
||||
[Parameter(ParameterSetName = TemplateFileParameterFileParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Local path to the template file.")]
|
||||
[Parameter(ParameterSetName = TemplateFileParameterUriParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Local path to the template file.")]
|
||||
[Parameter(ParameterSetName = ParameterlessTemplateFileParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Local path to the template file.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string TemplateFile { get; set; }
|
||||
|
||||
[Parameter(ParameterSetName = TemplateUriParameterObjectParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Uri to the template file.")]
|
||||
[Parameter(ParameterSetName = TemplateUriParameterFileParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Uri to the template file.")]
|
||||
[Parameter(ParameterSetName = TemplateUriParameterUriParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Uri to the template file.")]
|
||||
[Parameter(ParameterSetName = ParameterlessTemplateUriParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Uri to the template file.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string TemplateUri { get; set; }
|
||||
|
||||
public object GetDynamicParameters()
|
||||
{
|
||||
if (!string.IsNullOrEmpty(TemplateFile) &&
|
||||
!TemplateFile.Equals(templateFile, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
templateFile = TemplateFile;
|
||||
if (string.IsNullOrEmpty(TemplateParameterUri))
|
||||
{
|
||||
dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
|
||||
this.TryResolvePath(TemplateFile),
|
||||
TemplateParameterObject,
|
||||
this.TryResolvePath(TemplateParameterFile),
|
||||
MyInvocation.MyCommand.Parameters.Keys.ToArray());
|
||||
}
|
||||
else
|
||||
{
|
||||
dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
|
||||
this.TryResolvePath(TemplateFile),
|
||||
TemplateParameterObject,
|
||||
TemplateParameterUri,
|
||||
MyInvocation.MyCommand.Parameters.Keys.ToArray());
|
||||
}
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(TemplateUri) &&
|
||||
!TemplateUri.Equals(templateUri, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
templateUri = TemplateUri;
|
||||
if (string.IsNullOrEmpty(TemplateParameterUri))
|
||||
{
|
||||
dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
|
||||
TemplateUri,
|
||||
TemplateParameterObject,
|
||||
this.TryResolvePath(TemplateParameterFile),
|
||||
MyInvocation.MyCommand.Parameters.Keys.ToArray());
|
||||
}
|
||||
else
|
||||
{
|
||||
dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
|
||||
TemplateUri,
|
||||
TemplateParameterObject,
|
||||
TemplateParameterUri,
|
||||
MyInvocation.MyCommand.Parameters.Keys.ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
RegisterDynamicParameters(dynamicParameters);
|
||||
|
||||
return dynamicParameters;
|
||||
}
|
||||
|
||||
protected Hashtable GetTemplateParameterObject(Hashtable templateParameterObject)
|
||||
{
|
||||
// NOTE(jogao): create a new Hashtable so that user can re-use the templateParameterObject.
|
||||
var prameterObject = new Hashtable();
|
||||
if (templateParameterObject != null)
|
||||
{
|
||||
foreach (var parameterKey in templateParameterObject.Keys)
|
||||
{
|
||||
prameterObject[parameterKey] = new Hashtable { { "value", templateParameterObject[parameterKey] } };
|
||||
}
|
||||
}
|
||||
|
||||
// Load parameters from the file
|
||||
string templateParameterFilePath = this.TryResolvePath(TemplateParameterFile);
|
||||
if (templateParameterFilePath != null && FileUtilities.DataStore.FileExists(templateParameterFilePath))
|
||||
{
|
||||
var parametersFromFile = TemplateUtility.ParseTemplateParameterFileContents(templateParameterFilePath);
|
||||
parametersFromFile.ForEach(dp =>
|
||||
{
|
||||
var parameter = new Hashtable();
|
||||
if (dp.Value.Value != null)
|
||||
{
|
||||
parameter.Add("value", dp.Value.Value);
|
||||
}
|
||||
if (dp.Value.Reference != null)
|
||||
{
|
||||
parameter.Add("reference", dp.Value.Reference);
|
||||
}
|
||||
|
||||
prameterObject[dp.Key] = parameter;
|
||||
});
|
||||
}
|
||||
|
||||
// Load dynamic parameters
|
||||
IEnumerable<RuntimeDefinedParameter> parameters = PowerShellUtilities.GetUsedDynamicParameters(this.AsJobDynamicParameters, MyInvocation);
|
||||
if (parameters.Any())
|
||||
{
|
||||
parameters.ForEach(dp => prameterObject[((ParameterAttribute)dp.Attributes[0]).HelpMessage] = new Hashtable { { "value", dp.Value } });
|
||||
}
|
||||
|
||||
return prameterObject;
|
||||
}
|
||||
|
||||
protected string GetDeploymentDebugLogLevel(string deploymentDebugLogLevel)
|
||||
{
|
||||
string debugSetting = string.Empty;
|
||||
if (!string.IsNullOrEmpty(deploymentDebugLogLevel))
|
||||
{
|
||||
switch (deploymentDebugLogLevel.ToLower())
|
||||
{
|
||||
case "all":
|
||||
debugSetting = "RequestContent,ResponseContent";
|
||||
break;
|
||||
case "requestcontent":
|
||||
debugSetting = "RequestContent";
|
||||
break;
|
||||
case "responsecontent":
|
||||
debugSetting = "ResponseContent";
|
||||
break;
|
||||
case "none":
|
||||
debugSetting = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return debugSetting;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,79 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Management.Automation;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the preview features of a certain azure resource provider.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Get, "AzureRmProviderFeature", DefaultParameterSetName = GetAzureProviderFeatureCmdlet.ListAvailableParameterSet)]
|
||||
[OutputType(typeof(List<PSProviderFeature>))]
|
||||
public class GetAzureProviderFeatureCmdlet : ProviderFeatureCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// The filter unregistered parameter set
|
||||
/// </summary>
|
||||
public const string ListAvailableParameterSet = "ListAvailableParameterSet";
|
||||
|
||||
/// <summary>
|
||||
/// The get feature parameter set
|
||||
/// </summary>
|
||||
public const string GetFeatureParameterSet = "GetFeature";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the provider namespace
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource provider namespace.", ParameterSetName = GetAzureProviderFeatureCmdlet.GetFeatureParameterSet)]
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, HelpMessage = "The resource provider namespace.", ParameterSetName = GetAzureProviderFeatureCmdlet.ListAvailableParameterSet)]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ProviderNamespace { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the feature name
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, HelpMessage = "The feature name.", ParameterSetName = GetAzureProviderFeatureCmdlet.GetFeatureParameterSet)]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string FeatureName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a switch indicating whether to list all available features or just the ones registered with the current subscription
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, HelpMessage = "When set, lists all available features including those not registered with the current subscription.", ParameterSetName = GetAzureProviderFeatureCmdlet.ListAvailableParameterSet)]
|
||||
public SwitchParameter ListAvailable { get; set; }
|
||||
|
||||
public override void ExecuteCmdlet()
|
||||
{
|
||||
var parameterSetName = this.DetermineParameterSetName();
|
||||
|
||||
switch (parameterSetName)
|
||||
{
|
||||
case GetAzureProviderFeatureCmdlet.ListAvailableParameterSet:
|
||||
this.WriteObject(this.ProviderFeatureClient.ListPSProviderFeatures(this.ListAvailable, this.ProviderNamespace), enumerateCollection: true);
|
||||
break;
|
||||
|
||||
case GetAzureProviderFeatureCmdlet.GetFeatureParameterSet:
|
||||
this.WriteObject(this.ProviderFeatureClient.ListPSProviderFeatures(this.ProviderNamespace, this.FeatureName), enumerateCollection: true);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new ApplicationException(string.Format("Unknown parameter set encountered: '{0}'", this.ParameterSetName));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
using System.Management.Automation;
|
||||
using ProjectResources = Microsoft.Azure.Commands.ResourceManager.Cmdlets.Properties.Resources;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels;
|
||||
|
||||
/// <summary>
|
||||
/// Register the previewed features of a certain azure resource provider.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsLifecycle.Register, "AzureRmProviderFeature", SupportsShouldProcess = true), OutputType(typeof(List<PSProviderFeature>))]
|
||||
public class RegisterAzureProviderFeatureCmdlet : ProviderFeatureCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the provider name
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The feature name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string FeatureName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the provider name
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource provider namespace.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ProviderNamespace { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet
|
||||
/// </summary>
|
||||
public override void ExecuteCmdlet()
|
||||
{
|
||||
this.ConfirmAction(
|
||||
processMessage: ProjectResources.RegisterProviderFeatureMessage,
|
||||
target: this.ProviderNamespace,
|
||||
action: () => this.WriteObject(this.ProviderFeatureClient.RegisterProviderFeature(providerName: this.ProviderNamespace, featureName: this.FeatureName)));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,102 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels;
|
||||
using Microsoft.Azure.Management.ResourceManager.Models;
|
||||
using Microsoft.WindowsAzure.Commands.Utilities.Common;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Management.Automation;
|
||||
|
||||
/// <summary>
|
||||
/// Get all locations with the supported providers.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Get, "AzureRmLocation"), OutputType(typeof(List<PSResourceProviderLocation>))]
|
||||
public class GetAzureLocationCmdlet: ResourceManagerCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Executes the cmdlet
|
||||
/// </summary>
|
||||
public override void ExecuteCmdlet()
|
||||
{
|
||||
var allLocations = this.SubscriptionSdkClient.ListLocations(DefaultContext.Subscription.Id.ToString());
|
||||
var providers = this.ResourceManagerSdkClient.ListResourceProviders(providerName: null, listAvailable: true);
|
||||
var providerLocations = ConstructResourceProviderLocations(allLocations, providers);
|
||||
|
||||
this.WriteObject(providerLocations, enumerateCollection: true);
|
||||
}
|
||||
|
||||
private List<PSResourceProviderLocation> ConstructResourceProviderLocations(List<Internal.Subscriptions.Models.Location> locations, List<Provider> providers)
|
||||
{
|
||||
var locationProviderMap = GetLocationProviderMap(providers);
|
||||
|
||||
// Join locations and locationProviderMap on DisplayName
|
||||
// locations: list of [Name, DisplayName, Id, ...]
|
||||
// locationProviderMap: list of [Key: DisplayName, Value: Providers]
|
||||
var joinResult = locations.CoalesceEnumerable().Join(
|
||||
locationProviderMap.CoalesceEnumerable(),
|
||||
location => location.DisplayName,
|
||||
mapEntry => mapEntry.Key,
|
||||
(location, mapEntry) => new PSResourceProviderLocation
|
||||
{
|
||||
Location = location.Name,
|
||||
DisplayName = location.DisplayName,
|
||||
Providers = mapEntry.Value
|
||||
},
|
||||
StringComparer.InvariantCultureIgnoreCase);
|
||||
|
||||
return joinResult.ToList();
|
||||
}
|
||||
|
||||
private Dictionary<string, List<string>> GetLocationProviderMap(List<Provider> providers)
|
||||
{
|
||||
var locationMap = new Dictionary<string, List<string>>(StringComparer.InvariantCultureIgnoreCase);
|
||||
providers.CoalesceEnumerable()
|
||||
.ForEach(provider => AddResourceProvider(provider, locationMap));
|
||||
|
||||
return locationMap;
|
||||
}
|
||||
|
||||
private bool AddResourceProvider(Provider provider, Dictionary<string, List<string>> locationMap)
|
||||
{
|
||||
if (locationMap == null || provider == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var providersLocations = provider.ResourceTypes
|
||||
.CoalesceEnumerable()
|
||||
.SelectMany(type => type.Locations)
|
||||
.Distinct(StringComparer.InvariantCultureIgnoreCase);
|
||||
|
||||
providersLocations.ForEach(location =>
|
||||
{
|
||||
if (!locationMap.ContainsKey(location))
|
||||
{
|
||||
locationMap[location] = new List<string>();
|
||||
}
|
||||
if (!locationMap[location].Contains(provider.NamespaceProperty))
|
||||
{
|
||||
locationMap[location].Add(provider.NamespaceProperty);
|
||||
}
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,162 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Management.Automation;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource lock.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Get, "AzureRmResourceLock"), OutputType(typeof(PSObject))]
|
||||
public class GetAzureResourceLockCmdlet : ResourceLockManagementCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Contains the errors that encountered while satifying the request.
|
||||
/// </summary>
|
||||
private readonly ConcurrentBag<ErrorRecord> errors = new ConcurrentBag<ErrorRecord>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the extension resource name parameter.
|
||||
/// </summary>
|
||||
[Alias("ExtensionResourceName", "Name")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.ResourceGroupLevelLock, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.ResourceGroupResourceLevelLock, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.ScopeLevelLock, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.SubscriptionLevelLock, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.SubscriptionResourceLevelLock, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.TenantResourceLevelLock, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string LockName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the at-scope filter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "When specified returns all locks at or above the specified scope, otherwise returns all locks at, above or below the scope.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public SwitchParameter AtScope { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
PaginatedResponseHelper.ForEach(
|
||||
getFirstPage: () => this.GetResources(),
|
||||
getNextPage: nextLink => this.GetNextLink<JObject>(nextLink),
|
||||
cancellationToken: this.CancellationToken,
|
||||
action: resources => this.WriteObject(sendToPipeline: this.GetOutputObjects(resources), enumerateCollection: true));
|
||||
|
||||
if (this.errors.Count != 0)
|
||||
{
|
||||
foreach (var error in this.errors)
|
||||
{
|
||||
this.WriteError(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queries the ARM cache and returns the cached resource that match the query specified.
|
||||
/// </summary>
|
||||
private async Task<ResponseWithContinuation<JObject[]>> GetResources()
|
||||
{
|
||||
var response = new ResponseWithContinuation<JObject[]> { Value = new JObject[0] };
|
||||
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(this.LockName))
|
||||
{
|
||||
var resource = await this.GetResource().ConfigureAwait(continueOnCapturedContext: false);
|
||||
|
||||
response.Value = resource.AsArray();
|
||||
}
|
||||
else
|
||||
{
|
||||
response = await this.ListResourcesTypeCollection().ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ex.IsFatal())
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
ex = (ex is AggregateException)
|
||||
? (ex as AggregateException).Flatten()
|
||||
: ex;
|
||||
|
||||
this.errors.Add(new ErrorRecord(ex, "ErrorGettingResourceLock", ErrorCategory.CloseError, null));
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a resource.
|
||||
/// </summary>
|
||||
private async Task<JObject> GetResource()
|
||||
{
|
||||
var resourceId = this.GetResourceId(this.LockName);
|
||||
|
||||
return await this
|
||||
.GetResourcesClient()
|
||||
.GetResource<JObject>(
|
||||
resourceId: resourceId,
|
||||
apiVersion: this.LockApiVersion,
|
||||
cancellationToken: this.CancellationToken.Value)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lists resources in a type collection.
|
||||
/// </summary>
|
||||
private async Task<ResponseWithContinuation<JObject[]>> ListResourcesTypeCollection()
|
||||
{
|
||||
var resourceCollectionId = this.GetResourceId(this.LockName);
|
||||
|
||||
var filter = this.AtScope
|
||||
? "$filter=atScope()"
|
||||
: null;
|
||||
|
||||
return await this
|
||||
.GetResourcesClient()
|
||||
.ListObjectColleciton<JObject>(
|
||||
resourceCollectionId: resourceCollectionId,
|
||||
apiVersion: this.LockApiVersion,
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: filter)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the next set of resources using the <paramref name="nextLink"/>
|
||||
/// </summary>
|
||||
/// <param name="nextLink">The next link.</param>
|
||||
private Task<ResponseWithContinuation<TType[]>> GetNextLink<TType>(string nextLink)
|
||||
{
|
||||
return this
|
||||
.GetResourcesClient()
|
||||
.ListNextBatch<TType>(nextLink: nextLink, cancellationToken: this.CancellationToken.Value);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,134 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Locks;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Management.Automation;
|
||||
|
||||
/// <summary>
|
||||
/// The new azure resource lock cmdlet.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.New, "AzureRmResourceLock", SupportsShouldProcess = true, DefaultParameterSetName = ResourceLockManagementCmdletBase.ScopeLevelLock), OutputType(typeof(PSObject))]
|
||||
public class NewAzureResourceLockCmdlet : ResourceLockManagementCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the extension resource name parameter.
|
||||
/// </summary>
|
||||
[Alias("ExtensionResourceName", "Name")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.ResourceGroupLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.ResourceGroupResourceLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.ScopeLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.SubscriptionLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.SubscriptionResourceLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.TenantResourceLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string LockName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the extension resource name parameter.
|
||||
/// </summary>
|
||||
[Alias("Level")]
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The level of the lock.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public LockLevel LockLevel { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the extension resource name parameter.
|
||||
/// </summary>
|
||||
[Alias("Notes")]
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The notes of the lock.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string LockNotes { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the force parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")]
|
||||
public SwitchParameter Force { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
var resourceId = this.GetResourceId(this.LockName);
|
||||
this.ConfirmAction(
|
||||
this.Force,
|
||||
this.GetActionMessage(resourceId),
|
||||
this.GetProccessMessage(),
|
||||
resourceId,
|
||||
() =>
|
||||
{
|
||||
var resourceBody = this.GetResourceBody();
|
||||
|
||||
var operationResult = this.GetResourcesClient()
|
||||
.PutResource(
|
||||
resourceId: resourceId,
|
||||
apiVersion: this.LockApiVersion,
|
||||
resource: resourceBody,
|
||||
cancellationToken: this.CancellationToken.Value)
|
||||
.Result;
|
||||
|
||||
var managementUri = this.GetResourcesClient()
|
||||
.GetResourceManagementRequestUri(
|
||||
resourceId: resourceId,
|
||||
apiVersion: this.LockApiVersion);
|
||||
|
||||
var activity = string.Format("PUT {0}", managementUri.PathAndQuery);
|
||||
var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true)
|
||||
.WaitOnOperation(operationResult: operationResult);
|
||||
|
||||
this.WriteObject(this.GetOutputObjects(JObject.Parse(result)), enumerateCollection: true);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the action message.
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource Id.</param>
|
||||
protected virtual string GetActionMessage(string resourceId)
|
||||
{
|
||||
return "Are you sure you want to create the following lock: " + resourceId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the process message.
|
||||
/// </summary>
|
||||
protected virtual string GetProccessMessage()
|
||||
{
|
||||
return "Creating the lock.";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the lock.
|
||||
/// </summary>
|
||||
private JToken GetResourceBody()
|
||||
{
|
||||
var lockObject = new Lock
|
||||
{
|
||||
Properties = new LockProperties
|
||||
{
|
||||
Level = this.LockLevel,
|
||||
Notes = this.LockNotes,
|
||||
}
|
||||
};
|
||||
|
||||
return lockObject.ToJToken();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,84 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using System.Management.Automation;
|
||||
|
||||
/// <summary>
|
||||
/// The remove azure resource lock cmdlet.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Remove, "AzureRmResourceLock", SupportsShouldProcess = true, DefaultParameterSetName = ResourceLockManagementCmdletBase.LockIdParameterSet), OutputType(typeof(PSObject))]
|
||||
public class RemoveAzureResourceLockCmdlet : ResourceLockManagementCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the extension resource name parameter.
|
||||
/// </summary>
|
||||
[Alias("ExtensionResourceName", "Name")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.ResourceGroupLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.ResourceGroupResourceLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.ScopeLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.SubscriptionLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.SubscriptionResourceLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.TenantResourceLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the lock.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string LockName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the force parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")]
|
||||
public SwitchParameter Force { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
var resourceId = this.GetResourceId(this.LockName);
|
||||
this.ConfirmAction(
|
||||
this.Force,
|
||||
string.Format("Are you sure you want to delete the following lock: {0}", resourceId),
|
||||
"Deleting the lock...",
|
||||
resourceId,
|
||||
() =>
|
||||
{
|
||||
var operationResult = this.GetResourcesClient()
|
||||
.DeleteResource(
|
||||
resourceId: resourceId,
|
||||
apiVersion: this.LockApiVersion,
|
||||
cancellationToken: this.CancellationToken.Value)
|
||||
.Result;
|
||||
|
||||
if (operationResult.HttpStatusCode == System.Net.HttpStatusCode.NoContent)
|
||||
{
|
||||
throw new PSInvalidOperationException(string.Format("The resource lock '{0}' could not be found.", resourceId));
|
||||
}
|
||||
|
||||
var managementUri = this.GetResourcesClient()
|
||||
.GetResourceManagementRequestUri(
|
||||
resourceId: resourceId,
|
||||
apiVersion: this.LockApiVersion);
|
||||
|
||||
var activity = string.Format("DELETE {0}", managementUri.PathAndQuery);
|
||||
|
||||
var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false)
|
||||
.WaitOnOperation(operationResult: operationResult);
|
||||
|
||||
this.WriteObject(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,176 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Commands.Common.Authentication.Abstractions;
|
||||
using Common.ArgumentCompleters;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Management.Automation;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for resource lock management cmdlets.
|
||||
/// </summary>
|
||||
public abstract class ResourceLockManagementCmdletBase : ResourceManagerCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// The Id parameter set.
|
||||
/// </summary>
|
||||
internal const string LockIdParameterSet = "ByLockId";
|
||||
|
||||
/// <summary>
|
||||
/// The resource group level resource lock.
|
||||
/// </summary>
|
||||
internal const string ScopeLevelLock = "BySpecifiedScope";
|
||||
|
||||
/// <summary>
|
||||
/// The resource group level resource lock.
|
||||
/// </summary>
|
||||
internal const string ResourceGroupResourceLevelLock = "ByResourceGroupLevel";
|
||||
|
||||
/// <summary>
|
||||
/// The subscription level resource lock.
|
||||
/// </summary>
|
||||
internal const string SubscriptionResourceLevelLock = "BySubscriptionLevel";
|
||||
|
||||
/// <summary>
|
||||
/// The tenant level resource lock patameter set.
|
||||
/// </summary>
|
||||
internal const string TenantResourceLevelLock = "ByTenantLevel";
|
||||
|
||||
/// <summary>
|
||||
/// The resource group lock parametere set.
|
||||
/// </summary>
|
||||
internal const string ResourceGroupLevelLock = "ByResourceGroup";
|
||||
|
||||
/// <summary>
|
||||
/// The subscription lock parameter set.
|
||||
/// </summary>
|
||||
internal const string SubscriptionLevelLock = "BySubscription";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the scope.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.ScopeLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The scope. e.g. to specify a database '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaserName}', to specify a resoruce group: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}'")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Scope { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the resource name parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.ResourceGroupResourceLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name. e.g. to specify a database MyServer/MyDatabase.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.SubscriptionResourceLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name. e.g. to specify a database MyServer/MyDatabase.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.TenantResourceLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name. e.g. to specify a database MyServer/MyDatabase.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the resource type parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.ResourceGroupResourceLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource type. e.g. Microsoft.Sql/Servers/Databases.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.SubscriptionResourceLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource type. e.g. Microsoft.Sql/Servers/Databases.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.TenantResourceLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource type. e.g. Microsoft.Sql/Servers/Databases.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the resource group name parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.ResourceGroupResourceLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.ResourceGroupLevelLock, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")]
|
||||
[ResourceGroupCompleter]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceGroupName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tenant level parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.TenantResourceLevelLock, Mandatory = true, HelpMessage = "Indicates that this is a tenant level operation.")]
|
||||
public SwitchParameter TenantLevel { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The Id of the lock.
|
||||
/// </summary>
|
||||
[Alias("Id", "ResourceId")]
|
||||
[Parameter(ParameterSetName = ResourceLockManagementCmdletBase.LockIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The Id of the lock.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string LockId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Determines the api version to be used
|
||||
/// </summary>
|
||||
public string LockApiVersion { get; set; }
|
||||
|
||||
public ResourceLockManagementCmdletBase()
|
||||
{
|
||||
this.LockApiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.LockApiVersion : this.ApiVersion;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id from the supplied PowerShell parameters.
|
||||
/// </summary>
|
||||
/// <param name="lockName">The name of the lock.</param>
|
||||
protected string GetResourceId(string lockName)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(this.LockId))
|
||||
{
|
||||
var resourceType = ResourceIdUtility.GetResourceType(this.LockId);
|
||||
var extensionResourceType = ResourceIdUtility.GetExtensionResourceType(this.LockId);
|
||||
|
||||
if ((resourceType.EqualsInsensitively(Constants.MicrosoftAuthorizationLocksType) &&
|
||||
string.IsNullOrWhiteSpace(extensionResourceType)) ||
|
||||
extensionResourceType.EqualsInsensitively(Constants.MicrosoftAuthorizationLocksType))
|
||||
{
|
||||
return this.LockId;
|
||||
}
|
||||
|
||||
throw new InvalidOperationException(string.Format("The Id '{0}' does not belong to a lock.", this.LockId));
|
||||
}
|
||||
|
||||
return !string.IsNullOrWhiteSpace(this.Scope)
|
||||
? ResourceIdUtility.GetResourceId(
|
||||
resourceId: this.Scope,
|
||||
extensionResourceType: Constants.MicrosoftAuthorizationLocksType,
|
||||
extensionResourceName: lockName)
|
||||
: ResourceIdUtility.GetResourceId(
|
||||
subscriptionId: this.DefaultContext.Subscription.GetId(),
|
||||
resourceGroupName: this.ResourceGroupName,
|
||||
resourceType: this.ResourceType,
|
||||
resourceName: this.ResourceName,
|
||||
extensionResourceType: Constants.MicrosoftAuthorizationLocksType,
|
||||
extensionResourceName: lockName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts the resource object to output that can be piped to the lock cmdlets.
|
||||
/// </summary>
|
||||
/// <param name="resources">The lock resource object.</param>
|
||||
protected PSObject[] GetOutputObjects(params JToken[] resources)
|
||||
{
|
||||
return resources
|
||||
.CoalesceEnumerable()
|
||||
.Where(resource => resource != null)
|
||||
.SelectArray(resource =>
|
||||
{
|
||||
var psobject = resource.ToResource().ToPsObject();
|
||||
psobject.Properties.Add(new PSNoteProperty("LockId", psobject.Properties["ResourceId"].Value));
|
||||
return psobject;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using System.Management.Automation;
|
||||
|
||||
/// <summary>
|
||||
/// The set resource lock cmdlet.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Set, "AzureRmResourceLock", SupportsShouldProcess = true, DefaultParameterSetName = ResourceLockManagementCmdletBase.ScopeLevelLock), OutputType(typeof(PSObject))]
|
||||
public class SetAzureResourceLockCmdlet : NewAzureResourceLockCmdlet
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the action message.
|
||||
/// </summary>
|
||||
/// <param name="resourceId">The resource Id.</param>
|
||||
protected override string GetActionMessage(string resourceId)
|
||||
{
|
||||
return "Are you sure you want to update the following lock: " + resourceId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the process message.
|
||||
/// </summary>
|
||||
protected override string GetProccessMessage()
|
||||
{
|
||||
return "Updating the lock.";
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,156 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Common.ArgumentCompleters;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Management.Automation;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the managed application.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Get, "AzureRmManagedApplication", DefaultParameterSetName = GetAzureManagedApplicationCmdlet.ParameterlessSet), OutputType(typeof(PSObject))]
|
||||
public class GetAzureManagedApplicationCmdlet : ManagedApplicationCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// The managed application Id parameter set.
|
||||
/// </summary>
|
||||
internal const string ManagedApplicationIdParameterSet = "GetById";
|
||||
|
||||
/// <summary>
|
||||
/// The managed application name parameter set.
|
||||
/// </summary>
|
||||
internal const string ManagedApplicationNameParameterSet = "GetByNameAndResourceGroup";
|
||||
|
||||
/// <summary>
|
||||
/// The list all managed application parameter set.
|
||||
/// </summary>
|
||||
internal const string ParameterlessSet = "GetBySubscription";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application name parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = GetAzureManagedApplicationCmdlet.ManagedApplicationNameParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application resource group parameter
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = GetAzureManagedApplicationCmdlet.ManagedApplicationNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")]
|
||||
[ResourceGroupCompleter]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceGroupName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application id parameter
|
||||
/// </summary>
|
||||
[Alias("ResourceId", "ManagedApplicationId")]
|
||||
[Parameter(ParameterSetName = GetAzureManagedApplicationCmdlet.ManagedApplicationIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified managed application Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
|
||||
this.RunCmdlet();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Contains the cmdlet's execution logic.
|
||||
/// </summary>
|
||||
private void RunCmdlet()
|
||||
{
|
||||
PaginatedResponseHelper.ForEach(
|
||||
getFirstPage: () => this.GetResources(),
|
||||
getNextPage: nextLink => this.GetNextLink<JObject>(nextLink),
|
||||
cancellationToken: this.CancellationToken,
|
||||
action: resources => this.WriteObject(sendToPipeline: this.GetOutputObjects("ManagedApplicationId", resources), enumerateCollection: true));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queries the ARM cache and returns the cached resource that match the query specified.
|
||||
/// </summary>
|
||||
private async Task<ResponseWithContinuation<JObject[]>> GetResources()
|
||||
{
|
||||
string resourceId = this.Id ?? this.GetResourceId();
|
||||
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.ApplicationApiVersion : this.ApiVersion;
|
||||
|
||||
if (!string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId)))
|
||||
{
|
||||
var resource = await this
|
||||
.GetResourcesClient()
|
||||
.GetResource<JObject>(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
ResponseWithContinuation<JObject[]> retVal;
|
||||
return resource.TryConvertTo(out retVal) && retVal.Value != null
|
||||
? retVal
|
||||
: new ResponseWithContinuation<JObject[]> { Value = resource.AsArray() };
|
||||
}
|
||||
else
|
||||
{
|
||||
return await this
|
||||
.GetResourcesClient()
|
||||
.ListObjectColleciton<JObject>(
|
||||
resourceCollectionId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id
|
||||
/// </summary>
|
||||
private string GetResourceId()
|
||||
{
|
||||
var subscriptionId = DefaultContext.Subscription.Id;
|
||||
if (string.IsNullOrEmpty(this.Name) && string.IsNullOrEmpty(this.ResourceGroupName))
|
||||
{
|
||||
return string.Format("/subscriptions/{0}/providers/{1}",
|
||||
subscriptionId.ToString(),
|
||||
Constants.MicrosoftApplicationType);
|
||||
}
|
||||
else if (string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.ResourceGroupName))
|
||||
{
|
||||
return string.Format("/subscriptions/{0}/resourcegroups/{1}/providers/{2}",
|
||||
subscriptionId.ToString(),
|
||||
this.ResourceGroupName,
|
||||
Constants.MicrosoftApplicationType);
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.ResourceGroupName))
|
||||
{
|
||||
return string.Format("/subscriptions/{0}/resourcegroups/{1}/providers/{2}/{3}",
|
||||
subscriptionId.ToString(),
|
||||
this.ResourceGroupName,
|
||||
Constants.MicrosoftApplicationType,
|
||||
this.Name);
|
||||
}
|
||||
return this.Id;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,145 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Common.ArgumentCompleters;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Management.Automation;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the managed application definition.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Get, "AzureRmManagedApplicationDefinition", DefaultParameterSetName = GetAzureManagedApplicationDefinitionCmdlet.ManagedApplicationDefinitionNameParameterSet), OutputType(typeof(PSObject))]
|
||||
public class GetAzureManagedApplicationDefinitionCmdlet : ManagedApplicationCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// The managed application definition Id parameter set.
|
||||
/// </summary>
|
||||
internal const string ManagedApplicationDefinitionIdParameterSet = "GetById";
|
||||
|
||||
/// <summary>
|
||||
/// The managed application definition name parameter set.
|
||||
/// </summary>
|
||||
internal const string ManagedApplicationDefinitionNameParameterSet = "GetByNameAndResourceGroup";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition name parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = GetAzureManagedApplicationDefinitionCmdlet.ManagedApplicationDefinitionNameParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application definition name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition resource group parameter
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = GetAzureManagedApplicationDefinitionCmdlet.ManagedApplicationDefinitionNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")]
|
||||
[ResourceGroupCompleter]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceGroupName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition id parameter
|
||||
/// </summary>
|
||||
[Alias("ResourceId", "ManagedApplicationDefinitionId")]
|
||||
[Parameter(ParameterSetName = GetAzureManagedApplicationDefinitionCmdlet.ManagedApplicationDefinitionIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified managed application definition Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
|
||||
this.RunCmdlet();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Contains the cmdlet's execution logic.
|
||||
/// </summary>
|
||||
private void RunCmdlet()
|
||||
{
|
||||
PaginatedResponseHelper.ForEach(
|
||||
getFirstPage: () => this.GetResources(),
|
||||
getNextPage: nextLink => this.GetNextLink<JObject>(nextLink),
|
||||
cancellationToken: this.CancellationToken,
|
||||
action: resources => this.WriteObject(sendToPipeline: this.GetOutputObjects("ManagedApplicationDefinitionId", resources), enumerateCollection: true));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queries the ARM cache and returns the cached resource that match the query specified.
|
||||
/// </summary>
|
||||
private async Task<ResponseWithContinuation<JObject[]>> GetResources()
|
||||
{
|
||||
string resourceId = this.Id ?? this.GetResourceId();
|
||||
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.ApplicationApiVersion : this.ApiVersion;
|
||||
|
||||
if (!string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId)))
|
||||
{
|
||||
var resource = await this
|
||||
.GetResourcesClient()
|
||||
.GetResource<JObject>(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
ResponseWithContinuation<JObject[]> retVal;
|
||||
return resource.TryConvertTo(out retVal) && retVal.Value != null
|
||||
? retVal
|
||||
: new ResponseWithContinuation<JObject[]> { Value = resource.AsArray() };
|
||||
}
|
||||
else
|
||||
{
|
||||
return await this
|
||||
.GetResourcesClient()
|
||||
.ListObjectColleciton<JObject>(
|
||||
resourceCollectionId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id
|
||||
/// </summary>
|
||||
private string GetResourceId()
|
||||
{
|
||||
var subscriptionId = DefaultContext.Subscription.Id;
|
||||
if(string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.ResourceGroupName))
|
||||
{
|
||||
return string.Format("/subscriptions/{0}/resourcegroups/{1}/providers/{2}",
|
||||
subscriptionId.ToString(),
|
||||
this.ResourceGroupName,
|
||||
Constants.MicrosoftApplicationDefinitionType);
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.ResourceGroupName))
|
||||
{
|
||||
return string.Format("/subscriptions/{0}/resourcegroups/{1}/providers/{2}/{3}",
|
||||
subscriptionId.ToString(),
|
||||
this.ResourceGroupName,
|
||||
Constants.MicrosoftApplicationDefinitionType,
|
||||
this.Name);
|
||||
}
|
||||
return this.Id;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,150 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using ProjectResources = Microsoft.Azure.Commands.ResourceManager.Cmdlets.Properties.Resources;
|
||||
using System.Linq;
|
||||
using System.Management.Automation;
|
||||
using System.Threading.Tasks;
|
||||
using System;
|
||||
using Microsoft.WindowsAzure.Commands.Utilities.Common;
|
||||
using System.IO;
|
||||
using Microsoft.WindowsAzure.Commands.Common;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application;
|
||||
using Commands.Common.Authentication.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for policy assignment cmdlets.
|
||||
/// </summary>
|
||||
public abstract class ManagedApplicationCmdletBase : ResourceManagerCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the next set of resources using the <paramref name="nextLink"/>
|
||||
/// </summary>
|
||||
/// <param name="nextLink">The next link.</param>
|
||||
protected Task<ResponseWithContinuation<TType[]>> GetNextLink<TType>(string nextLink)
|
||||
{
|
||||
return this
|
||||
.GetResourcesClient()
|
||||
.ListNextBatch<TType>(nextLink: nextLink, cancellationToken: this.CancellationToken.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts the resource object to specified resource type object.
|
||||
/// </summary>
|
||||
/// <param name="resources">The policy definition resource object.</param>
|
||||
protected PSObject[] GetOutputObjects(string resourceType, params JToken[] resources)
|
||||
{
|
||||
return resources
|
||||
.CoalesceEnumerable()
|
||||
.Where(resource => resource != null)
|
||||
.SelectArray(resource =>
|
||||
{
|
||||
var psobject = resource.ToResource().ToPsObject();
|
||||
psobject.Properties.Add(new PSNoteProperty(resourceType, psobject.Properties["ResourceId"].Value));
|
||||
return psobject;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a resource.
|
||||
/// </summary>
|
||||
protected async Task<JObject> GetExistingResource(string resourceId, string apiVersion)
|
||||
{
|
||||
return await this
|
||||
.GetResourcesClient()
|
||||
.GetResource<JObject>(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the authorization object
|
||||
/// </summary>
|
||||
protected JToken GetAuthorizationObject(string[] authorizations)
|
||||
{
|
||||
List<ApplicationProviderAuthorization> lstAuth = new List<ApplicationProviderAuthorization>();
|
||||
if (authorizations != null)
|
||||
{
|
||||
foreach (string s in authorizations)
|
||||
{
|
||||
string[] auth = s.Split(':');
|
||||
if (auth != null)
|
||||
{
|
||||
lstAuth.Add(new ApplicationProviderAuthorization
|
||||
{
|
||||
PrincipalId = auth[0],
|
||||
RoleDefinitionId = auth[1]
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return lstAuth.ToJToken();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the JToken object from parameter
|
||||
/// </summary>
|
||||
protected JToken GetObjectFromParameter(string parameter)
|
||||
{
|
||||
Uri outUri = null;
|
||||
if (Uri.TryCreate(parameter, UriKind.Absolute, out outUri))
|
||||
{
|
||||
if (outUri.Scheme == Uri.UriSchemeFile)
|
||||
{
|
||||
string filePath = this.TryResolvePath(parameter);
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
return JToken.FromObject(FileUtilities.DataStore.ReadFileAsText(filePath));
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new PSInvalidOperationException(string.Format(ProjectResources.InvalidFilePath, parameter));
|
||||
}
|
||||
}
|
||||
else if (outUri.Scheme != Uri.UriSchemeHttp && outUri.Scheme != Uri.UriSchemeHttps)
|
||||
{
|
||||
throw new PSInvalidOperationException(ProjectResources.InvalidUriScheme);
|
||||
}
|
||||
else if (!Uri.IsWellFormedUriString(outUri.AbsoluteUri, UriKind.Absolute))
|
||||
{
|
||||
throw new PSInvalidOperationException(string.Format(ProjectResources.InvalidUriString, parameter));
|
||||
}
|
||||
else
|
||||
{
|
||||
string contents = GeneralUtilities.DownloadFile(outUri.AbsoluteUri);
|
||||
if (string.IsNullOrEmpty(contents))
|
||||
{
|
||||
throw new PSInvalidOperationException(string.Format(ProjectResources.InvalidUriContent, parameter));
|
||||
}
|
||||
return JToken.FromObject(contents);
|
||||
}
|
||||
}
|
||||
|
||||
//for non absolute file paths
|
||||
string path = this.TryResolvePath(parameter);
|
||||
|
||||
return File.Exists(path)
|
||||
? JToken.FromObject(FileUtilities.DataStore.ReadFileAsText(path))
|
||||
: JToken.FromObject(parameter);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,170 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Common.ArgumentCompleters;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.WindowsAzure.Commands.Utilities.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.IO;
|
||||
using System.Management.Automation;
|
||||
using WindowsAzure.Commands.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the managed application.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.New, "AzureRmManagedApplication", SupportsShouldProcess = true), OutputType(typeof(PSObject))]
|
||||
public class NewAzureManagedApplicationCmdlet : ManagedApplicationCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application name parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application resource group parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")]
|
||||
[ResourceGroupCompleter]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceGroupName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application managed resource group parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed resource group name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ManagedResourceGroupName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application managed application definition id parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed resource group name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ManagedApplicationDefinitionId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the location.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, HelpMessage = "The resource location.")]
|
||||
[LocationCompleter("Microsoft.Solutions/applications")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Location { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application parameters parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The JSON formatted string of parameters for managed application. This can either be a path to a file name or uri containing the parameters, or the parameters as string.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Parameter { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the kind.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, HelpMessage = "The managed application kind. One of marketplace or servicecatalog")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public ApplicationKind Kind { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the plan object.
|
||||
/// </summary>
|
||||
[Alias("PlanObject")]
|
||||
[Parameter(Mandatory = false, HelpMessage = "A hash table which represents managed application plan properties.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public Hashtable Plan { get; set; }
|
||||
|
||||
[Alias("Tags")]
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hashtable which represents resource tags.")]
|
||||
public Hashtable Tag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
if (this.ShouldProcess(this.Name, "Create Managed Application"))
|
||||
{
|
||||
string resourceId = GetResourceId();
|
||||
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.ApplicationApiVersion : this.ApiVersion;
|
||||
|
||||
var operationResult = this.GetResourcesClient()
|
||||
.PutResource(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
resource: this.GetResource(),
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: null)
|
||||
.Result;
|
||||
|
||||
var managementUri = this.GetResourcesClient()
|
||||
.GetResourceManagementRequestUri(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
odataQuery: null);
|
||||
|
||||
var activity = string.Format("PUT {0}", managementUri.PathAndQuery);
|
||||
var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true)
|
||||
.WaitOnOperation(operationResult: operationResult);
|
||||
this.WriteObject(this.GetOutputObjects("ManagedApplicationId", JObject.Parse(result)), enumerateCollection: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id
|
||||
/// </summary>
|
||||
private string GetResourceId()
|
||||
{
|
||||
var subscriptionId = DefaultContext.Subscription.Id;
|
||||
return string.Format("/subscriptions/{0}/resourcegroups/{1}/providers/{2}/{3}",
|
||||
subscriptionId.ToString(),
|
||||
this.ResourceGroupName,
|
||||
Constants.MicrosoftApplicationType,
|
||||
this.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs the resource
|
||||
/// </summary>
|
||||
private JToken GetResource()
|
||||
{
|
||||
var applicationObject = new Application
|
||||
{
|
||||
Name = this.Name,
|
||||
Location = this.Location,
|
||||
Plan = this.Plan.ToDictionary(addValueLayer: false).ToJson().FromJson<ResourcePlan>(),
|
||||
Kind = this.Kind,
|
||||
Properties = new ApplicationProperties
|
||||
{
|
||||
ManagedResourceGroupId = string.Format("/subscriptions/{0}/resourcegroups/{1}", Guid.Parse(DefaultContext.Subscription.Id), this.ManagedResourceGroupName),
|
||||
ApplicationDefinitionId =this.ManagedApplicationDefinitionId ?? null,
|
||||
Parameters = this.Parameter == null ? null : JObject.Parse(this.GetObjectFromParameter(this.Parameter).ToString())
|
||||
},
|
||||
Tags = TagsHelper.GetTagsDictionary(this.Tag)
|
||||
};
|
||||
|
||||
return applicationObject.ToJToken();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,199 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Common.ArgumentCompleters;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Collections;
|
||||
using System.Management.Automation;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the managed application definition.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.New, "AzureRmManagedApplicationDefinition", SupportsShouldProcess = true), OutputType(typeof(PSObject))]
|
||||
public class NewAzureManagedApplicationDefinitionCmdlet : ManagedApplicationCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition name parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application definition name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition resource group parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")]
|
||||
[ResourceGroupCompleter]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceGroupName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition display name parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application definition display name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string DisplayName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition description parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application definition description.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the location.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, HelpMessage = "The resource location.")]
|
||||
[LocationCompleter("Microsoft.Solutions/applicationDefinitions")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Location { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the lock level.
|
||||
/// </summary>
|
||||
[Alias("Level")]
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The level of the lock for managed application definition.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public ApplicationLockLevel LockLevel { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition package file uri.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application definition package file uri.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string PackageFileUri { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition create ui definition file path or create ui definition as string.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application definition create ui definition.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string CreateUiDefinition { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition main template file path or main template as string.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application definition main template.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string MainTemplate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition authorization.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application definition authorization. Comma separated authorization pairs in a format of <principalId>:<roleDefinitionId>")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string[] Authorization { get; set; }
|
||||
|
||||
[Alias("Tags")]
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hashtable which represents resource tags.")]
|
||||
public Hashtable Tag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
if (this.ShouldProcess(this.Name, "Create Managed Application Definition"))
|
||||
{
|
||||
if (!string.IsNullOrEmpty(this.PackageFileUri))
|
||||
{
|
||||
if (!string.IsNullOrEmpty(this.MainTemplate) || !string.IsNullOrEmpty(this.CreateUiDefinition))
|
||||
{
|
||||
throw new PSInvalidOperationException("If PackageFileUri is specified, MainTemplate and CreateUiDefinition cannot have a value.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (string.IsNullOrEmpty(this.MainTemplate) || string.IsNullOrEmpty(this.CreateUiDefinition))
|
||||
{
|
||||
throw new PSInvalidOperationException("If PackageFileUri is not specified, both MainTemplate and CreateUiDefinition should have a valid value.");
|
||||
}
|
||||
}
|
||||
string resourceId = GetResourceId();
|
||||
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.ApplicationApiVersion : this.ApiVersion;
|
||||
|
||||
var operationResult = this.GetResourcesClient()
|
||||
.PutResource(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
resource: this.GetResource(),
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: null)
|
||||
.Result;
|
||||
|
||||
var managementUri = this.GetResourcesClient()
|
||||
.GetResourceManagementRequestUri(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
odataQuery: null);
|
||||
|
||||
var activity = string.Format("PUT {0}", managementUri.PathAndQuery);
|
||||
var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true)
|
||||
.WaitOnOperation(operationResult: operationResult);
|
||||
this.WriteObject(this.GetOutputObjects("ManagedApplicationDefinitionId", JObject.Parse(result)), enumerateCollection: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id
|
||||
/// </summary>
|
||||
private string GetResourceId()
|
||||
{
|
||||
var subscriptionId = DefaultContext.Subscription.Id;
|
||||
return string.Format("/subscriptions/{0}/resourcegroups/{1}/providers/{2}/{3}",
|
||||
subscriptionId.ToString(),
|
||||
this.ResourceGroupName,
|
||||
Constants.MicrosoftApplicationDefinitionType,
|
||||
this.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs the resource
|
||||
/// </summary>
|
||||
private JToken GetResource()
|
||||
{
|
||||
var applicationDefinitionObject = new ApplicationDefinition
|
||||
{
|
||||
Name = this.Name,
|
||||
Location = this.Location,
|
||||
Properties = new ApplicationDefinitionProperties
|
||||
{
|
||||
LockLevel = this.LockLevel,
|
||||
Description = this.Description,
|
||||
DisplayName = this.DisplayName,
|
||||
PackageFileUri = this.PackageFileUri ?? null,
|
||||
Authorizations = JArray.Parse(this.GetAuthorizationObject(this.Authorization).ToString()).ToJson().FromJson<ApplicationProviderAuthorization[]>()
|
||||
},
|
||||
Tags = TagsHelper.GetTagsDictionary(this.Tag)
|
||||
};
|
||||
|
||||
if (!string.IsNullOrEmpty(this.MainTemplate) && !string.IsNullOrEmpty(this.CreateUiDefinition))
|
||||
{
|
||||
applicationDefinitionObject.Properties.MainTemplate = JObject.Parse(this.GetObjectFromParameter(this.MainTemplate).ToString());
|
||||
applicationDefinitionObject.Properties.CreateUiDefinition = JObject.Parse(this.GetObjectFromParameter(this.CreateUiDefinition).ToString());
|
||||
}
|
||||
|
||||
return applicationDefinitionObject.ToJToken();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,130 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Common.ArgumentCompleters;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using System.Management.Automation;
|
||||
|
||||
/// <summary>
|
||||
/// Removes the managed application.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Remove, "AzureRmManagedApplication", SupportsShouldProcess = true,
|
||||
DefaultParameterSetName = RemoveAzureManagedApplicationCmdlet.ManagedApplicationNameParameterSet),
|
||||
OutputType(typeof(bool))]
|
||||
public class RemoveAzureManagedApplicationCmdlet : ManagedApplicationCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// The policy Id parameter set.
|
||||
/// </summary>
|
||||
internal const string ManagedApplicationIdParameterSet = "RemoveById";
|
||||
|
||||
/// <summary>
|
||||
/// The policy name parameter set.
|
||||
/// </summary>
|
||||
internal const string ManagedApplicationNameParameterSet = "RemoveByNameAndResourceGroup";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application name parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = RemoveAzureManagedApplicationCmdlet.ManagedApplicationNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application resource group parameter
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = RemoveAzureManagedApplicationCmdlet.ManagedApplicationNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")]
|
||||
[ResourceGroupCompleter]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceGroupName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application id parameter
|
||||
/// </summary>
|
||||
[Alias("ResourceId")]
|
||||
[Parameter(ParameterSetName = RemoveAzureManagedApplicationCmdlet.ManagedApplicationIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified managed application Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the force parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")]
|
||||
public SwitchParameter Force { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
|
||||
this.RunCmdlet();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Contains the cmdlet's execution logic.
|
||||
/// </summary>
|
||||
private void RunCmdlet()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
string resourceId = this.Id ?? this.GetResourceId();
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.ApplicationApiVersion : this.ApiVersion;
|
||||
|
||||
this.ConfirmAction(
|
||||
this.Force,
|
||||
string.Format("Are you sure you want to delete the following managed application: {0}", resourceId),
|
||||
"Deleting the managed application...",
|
||||
resourceId,
|
||||
() =>
|
||||
{
|
||||
var operationResult = this.GetResourcesClient()
|
||||
.DeleteResource(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: null)
|
||||
.Result;
|
||||
|
||||
var managementUri = this.GetResourcesClient()
|
||||
.GetResourceManagementRequestUri(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
odataQuery: null);
|
||||
|
||||
var activity = string.Format("DELETE {0}", managementUri.PathAndQuery);
|
||||
|
||||
this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false)
|
||||
.WaitOnOperation(operationResult: operationResult);
|
||||
|
||||
this.WriteObject(true);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id from the supplied PowerShell parameters.
|
||||
/// </summary>
|
||||
protected string GetResourceId()
|
||||
{
|
||||
var subscriptionId = DefaultContext.Subscription.Id;
|
||||
return string.Format("/subscriptions/{0}/resourcegroups/{1}/providers/{2}/{3}",
|
||||
subscriptionId.ToString(),
|
||||
this.ResourceGroupName,
|
||||
Constants.MicrosoftApplicationType,
|
||||
this.Name);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,130 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Common.ArgumentCompleters;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using System.Management.Automation;
|
||||
|
||||
/// <summary>
|
||||
/// Removes the managed application definition.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Remove, "AzureRmManagedApplicationDefinition", SupportsShouldProcess = true,
|
||||
DefaultParameterSetName = RemoveAzureManagedApplicationDefinitionCmdlet.ManagedApplicationDefinitionNameParameterSet),
|
||||
OutputType(typeof(bool))]
|
||||
public class RemoveAzureManagedApplicationDefinitionCmdlet : ManagedApplicationCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// The policy Id parameter set.
|
||||
/// </summary>
|
||||
internal const string ManagedApplicationDefinitionIdParameterSet = "RemoveById";
|
||||
|
||||
/// <summary>
|
||||
/// The policy name parameter set.
|
||||
/// </summary>
|
||||
internal const string ManagedApplicationDefinitionNameParameterSet = "RemoveByNameAndResourceGroup";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition name parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = RemoveAzureManagedApplicationDefinitionCmdlet.ManagedApplicationDefinitionNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application definition name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition resource group parameter
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = RemoveAzureManagedApplicationDefinitionCmdlet.ManagedApplicationDefinitionNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")]
|
||||
[ResourceGroupCompleter]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceGroupName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition id parameter
|
||||
/// </summary>
|
||||
[Alias("ResourceId")]
|
||||
[Parameter(ParameterSetName = RemoveAzureManagedApplicationDefinitionCmdlet.ManagedApplicationDefinitionIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified managed application definition Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the force parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")]
|
||||
public SwitchParameter Force { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
|
||||
this.RunCmdlet();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Contains the cmdlet's execution logic.
|
||||
/// </summary>
|
||||
private void RunCmdlet()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
string resourceId = this.Id ?? this.GetResourceId();
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.ApplicationApiVersion : this.ApiVersion;
|
||||
|
||||
this.ConfirmAction(
|
||||
this.Force,
|
||||
string.Format("Are you sure you want to delete the following managed application definition: {0}", resourceId),
|
||||
"Deleting the managed application definition...",
|
||||
resourceId,
|
||||
() =>
|
||||
{
|
||||
var operationResult = this.GetResourcesClient()
|
||||
.DeleteResource(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: null)
|
||||
.Result;
|
||||
|
||||
var managementUri = this.GetResourcesClient()
|
||||
.GetResourceManagementRequestUri(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
odataQuery: null);
|
||||
|
||||
var activity = string.Format("DELETE {0}", managementUri.PathAndQuery);
|
||||
|
||||
this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false)
|
||||
.WaitOnOperation(operationResult: operationResult);
|
||||
|
||||
this.WriteObject(true);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id from the supplied PowerShell parameters.
|
||||
/// </summary>
|
||||
protected string GetResourceId()
|
||||
{
|
||||
var subscriptionId = DefaultContext.Subscription.Id;
|
||||
return string.Format("/subscriptions/{0}/resourcegroups/{1}/providers/{2}/{3}",
|
||||
subscriptionId.ToString(),
|
||||
this.ResourceGroupName,
|
||||
Constants.MicrosoftApplicationDefinitionType,
|
||||
this.Name);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,244 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Common.ArgumentCompleters;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.WindowsAzure.Commands.Utilities.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.IO;
|
||||
using System.Management.Automation;
|
||||
using WindowsAzure.Commands.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the managed application.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Set, "AzureRmManagedApplication", DefaultParameterSetName = SetAzureManagedApplicationCmdlet.ManagedApplicationNameParameterSet, SupportsShouldProcess = true), OutputType(typeof(PSObject))]
|
||||
public class SetAzureManagedApplicationCmdlet : ManagedApplicationCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// The managed application Id parameter set.
|
||||
/// </summary>
|
||||
internal const string ManagedApplicationIdParameterSet = "SetById";
|
||||
|
||||
/// <summary>
|
||||
/// The managed application name parameter set.
|
||||
/// </summary>
|
||||
internal const string ManagedApplicationNameParameterSet = "SetByNameAndResourceGroup";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application name parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = SetAzureManagedApplicationCmdlet.ManagedApplicationNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application resource group parameter
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = SetAzureManagedApplicationCmdlet.ManagedApplicationNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")]
|
||||
[ResourceGroupCompleter]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceGroupName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application id parameter
|
||||
/// </summary>
|
||||
[Alias("ResourceId")]
|
||||
[Parameter(ParameterSetName = SetAzureManagedApplicationCmdlet.ManagedApplicationIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified managed application Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application managed resource group parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed resource group name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ManagedResourceGroupName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application managed application definition id parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed resource group name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ManagedApplicationDefinitionId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application parameters parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The JSON formatted string of parameters for managed application. This can either be a path to a file name or uri containing the parameters, or the parameters as string.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Parameter { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the kind.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "The managed application kind. One of marketplace or servicecatalog")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Kind { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the plan object.
|
||||
/// </summary>
|
||||
[Alias("PlanObject")]
|
||||
[Parameter(Mandatory = false, HelpMessage = "A hash table which represents managed application plan properties.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public Hashtable Plan { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tags.
|
||||
/// </summary>
|
||||
[Alias("Tags")]
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents resource tags.")]
|
||||
public Hashtable Tag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
if (this.ShouldProcess(this.Name, "Update Managed Application"))
|
||||
{
|
||||
string resourceId = this.Id ?? GetResourceId();
|
||||
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.ApplicationApiVersion : this.ApiVersion;
|
||||
var resourceBody = this.GetResourceBody(resourceId, apiVersion);
|
||||
|
||||
var operationResult = this.ShouldUsePatchSemantics()
|
||||
? this.GetResourcesClient()
|
||||
.PatchResource(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
resource: resourceBody,
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: null)
|
||||
.Result
|
||||
: this.GetResourcesClient()
|
||||
.PutResource(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
resource: resourceBody,
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: null)
|
||||
.Result;
|
||||
|
||||
var managementUri = this.GetResourcesClient()
|
||||
.GetResourceManagementRequestUri(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
odataQuery: null);
|
||||
|
||||
var activity = string.Format("PUT {0}", managementUri.PathAndQuery);
|
||||
var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true)
|
||||
.WaitOnOperation(operationResult: operationResult);
|
||||
this.WriteObject(this.GetOutputObjects("ManagedApplicationId", JObject.Parse(result)), enumerateCollection: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id
|
||||
/// </summary>
|
||||
private string GetResourceId()
|
||||
{
|
||||
var subscriptionId = DefaultContext.Subscription.Id;
|
||||
return string.Format("/subscriptions/{0}/resourcegroups/{1}/providers/{2}/{3}",
|
||||
subscriptionId.ToString(),
|
||||
this.ResourceGroupName,
|
||||
Constants.MicrosoftApplicationType,
|
||||
this.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource body.
|
||||
/// </summary>
|
||||
private JToken GetResourceBody(string resourceId, string apiVersion)
|
||||
{
|
||||
if (this.ShouldUsePatchSemantics())
|
||||
{
|
||||
var resourceBody = this.GetPatchResourceBody();
|
||||
return resourceBody == null ? null : resourceBody.ToJToken();
|
||||
}
|
||||
else
|
||||
{
|
||||
return this.GetResource(resourceId, apiVersion);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource body for PATCH calls
|
||||
/// </summary>
|
||||
private Resource<JToken> GetPatchResourceBody()
|
||||
{
|
||||
if(this.Tag == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
else
|
||||
{
|
||||
Resource<JToken> resourceBody = new Resource<JToken>();
|
||||
resourceBody.Tags = TagsHelper.GetTagsDictionary(this.Tag);
|
||||
return resourceBody;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines if the cmdlet should use <c>PATCH</c> semantics.
|
||||
/// </summary>
|
||||
private bool ShouldUsePatchSemantics()
|
||||
{
|
||||
return ((this.Tag != null) && this.Plan == null && this.Kind == null
|
||||
&& this.ManagedApplicationDefinitionId == null && this.ManagedResourceGroupName ==null
|
||||
&& this.Parameter == null);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Constructs the resource
|
||||
/// </summary>
|
||||
private JToken GetResource(string resourceId, string apiVersion)
|
||||
{
|
||||
var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource();
|
||||
|
||||
var applicationObject = new Application
|
||||
{
|
||||
Name = this.Name,
|
||||
Location = resource.Location,
|
||||
Plan = this.Plan == null
|
||||
? resource.Plan
|
||||
: this.Plan.ToDictionary(addValueLayer: false).ToJson().FromJson<ResourcePlan>(),
|
||||
Properties = new ApplicationProperties
|
||||
{
|
||||
ManagedResourceGroupId = string.IsNullOrEmpty(this.ManagedResourceGroupName)
|
||||
? resource.Properties["managedResourceGroupId"].ToString()
|
||||
: string.Format("/subscriptions/{0}/resourcegroups/{1}", Guid.Parse(DefaultContext.Subscription.Id), this.ManagedResourceGroupName),
|
||||
ApplicationDefinitionId =this.ManagedApplicationDefinitionId ?? resource.Properties["applicationDefinitionId"].ToString(),
|
||||
Parameters = this.Parameter == null
|
||||
? (resource.Properties["parameters"] != null ? JObject.Parse(resource.Properties["parameters"].ToString()) : null)
|
||||
: JObject.Parse(this.GetObjectFromParameter(this.Parameter).ToString())
|
||||
},
|
||||
Tags = TagsHelper.GetTagsDictionary(this.Tag) ?? resource.Tags
|
||||
};
|
||||
|
||||
return applicationObject.ToJToken();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,183 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Common.ArgumentCompleters;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Application;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.WindowsAzure.Commands.Utilities.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Management.Automation;
|
||||
using WindowsAzure.Commands.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the managed application definition.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Set, "AzureRmManagedApplicationDefinition", DefaultParameterSetName = SetAzureManagedApplicationDefinitionCmdlet.ManagedApplicationDefinitionNameParameterSet, SupportsShouldProcess = true), OutputType(typeof(PSObject))]
|
||||
public class SetAzureManagedApplicationDefinitionCmdlet : ManagedApplicationCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// The managed application Id parameter set.
|
||||
/// </summary>
|
||||
internal const string ManagedApplicationDefinitionIdParameterSet = "SetById";
|
||||
|
||||
/// <summary>
|
||||
/// The managed application name parameter set.
|
||||
/// </summary>
|
||||
internal const string ManagedApplicationDefinitionNameParameterSet = "SetByNameAndResourceGroup";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition name parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = SetAzureManagedApplicationDefinitionCmdlet.ManagedApplicationDefinitionNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application definition name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition resource group parameter
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = SetAzureManagedApplicationDefinitionCmdlet.ManagedApplicationDefinitionNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")]
|
||||
[ResourceGroupCompleter]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string ResourceGroupName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition id parameter
|
||||
/// </summary>
|
||||
[Alias("ResourceId")]
|
||||
[Parameter(ParameterSetName = SetAzureManagedApplicationDefinitionCmdlet.ManagedApplicationDefinitionIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified managed application definition Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition display name parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application definition display name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string DisplayName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition description parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application definition description.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition package file uri.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application definition package file uri.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string PackageFileUri { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the managed application definition authorization.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The managed application definition authorization. Comma separated authorization pairs in a format of <principalId>:<roleDefinitionId>")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string[] Authorization { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tags.
|
||||
/// </summary>
|
||||
[Alias("Tags")]
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents resource tags.")]
|
||||
public Hashtable Tag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
if (this.ShouldProcess(this.Name, "Update Managed Application Definition"))
|
||||
{
|
||||
string resourceId = this.Id ?? GetResourceId();
|
||||
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.ApplicationApiVersion : this.ApiVersion;
|
||||
|
||||
var operationResult = this.GetResourcesClient()
|
||||
.PutResource(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
resource: this.GetResource(resourceId, apiVersion),
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: null)
|
||||
.Result;
|
||||
|
||||
var managementUri = this.GetResourcesClient()
|
||||
.GetResourceManagementRequestUri(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
odataQuery: null);
|
||||
|
||||
var activity = string.Format("PUT {0}", managementUri.PathAndQuery);
|
||||
var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true)
|
||||
.WaitOnOperation(operationResult: operationResult);
|
||||
this.WriteObject(this.GetOutputObjects("ManagedApplicationDefinitionId", JObject.Parse(result)), enumerateCollection: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id
|
||||
/// </summary>
|
||||
private string GetResourceId()
|
||||
{
|
||||
var subscriptionId = DefaultContext.Subscription.Id;
|
||||
return string.Format("/subscriptions/{0}/providers/{1}/{2}",
|
||||
subscriptionId.ToString(),
|
||||
Constants.MicrosoftApplicationDefinitionType,
|
||||
this.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs the resource
|
||||
/// </summary>
|
||||
private JToken GetResource(string resourceId, string apiVersion)
|
||||
{
|
||||
var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource();
|
||||
|
||||
var applicationDefinitionObject = new ApplicationDefinition
|
||||
{
|
||||
Name = this.Name,
|
||||
Location = resource.Location,
|
||||
Properties = new ApplicationDefinitionProperties
|
||||
{
|
||||
LockLevel = (ApplicationLockLevel) Enum.Parse(typeof(ApplicationLockLevel), resource.Properties["lockLevel"].ToString(), true),
|
||||
Description = this.Description ?? (resource.Properties["description"] != null
|
||||
? resource.Properties["description"].ToString()
|
||||
: null),
|
||||
DisplayName = this.DisplayName ?? (resource.Properties["displayName"] != null
|
||||
? resource.Properties["displayName"].ToString()
|
||||
: null),
|
||||
PackageFileUri = this.PackageFileUri ?? null,
|
||||
Authorizations = this.Authorization != null
|
||||
? JArray.Parse(this.GetAuthorizationObject(this.Authorization).ToString()).ToJson().FromJson<ApplicationProviderAuthorization[]>()
|
||||
: JArray.Parse(resource.Properties["authorizations"].ToString()).ToJson().FromJson<ApplicationProviderAuthorization[]>()
|
||||
},
|
||||
Tags = TagsHelper.GetTagsDictionary(this.Tag) ?? resource.Tags
|
||||
};
|
||||
|
||||
return applicationDefinitionObject.ToJToken();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,194 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Management.Automation;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the policy assignment.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Get, "AzureRmPolicyAssignment", DefaultParameterSetName = GetAzurePolicyAssignmentCmdlet.ParameterlessSet), OutputType(typeof(PSObject))]
|
||||
public class GetAzurePolicyAssignmentCmdlet : PolicyCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// The policy Id parameter set.
|
||||
/// </summary>
|
||||
internal const string PolicyAssignmentIdParameterSet = "GetPolicyAssignmentId";
|
||||
|
||||
/// <summary>
|
||||
/// The policy name parameter set.
|
||||
/// </summary>
|
||||
internal const string PolicyAssignmentNameParameterSet = "GetPolicyAssignmentName";
|
||||
|
||||
/// <summary>
|
||||
/// The list all policy parameter set.
|
||||
/// </summary>
|
||||
internal const string ParameterlessSet = "GetAllPolicyAssignments";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment name parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment scope parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Scope { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment id parameter
|
||||
/// </summary>
|
||||
[Alias("ResourceId")]
|
||||
[Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy assignment Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment policy definition id parameter
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentIdParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy assignment Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")]
|
||||
[Parameter(ParameterSetName = GetAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy assignment Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string PolicyDefinitionId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
|
||||
this.RunCmdlet();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Contains the cmdlet's execution logic.
|
||||
/// </summary>
|
||||
private void RunCmdlet()
|
||||
{
|
||||
PaginatedResponseHelper.ForEach(
|
||||
getFirstPage: () => this.GetResources(),
|
||||
getNextPage: nextLink => this.GetNextLink<JObject>(nextLink),
|
||||
cancellationToken: this.CancellationToken,
|
||||
action: resources => this.WriteObject(sendToPipeline: this.GetOutputObjects("PolicyAssignmentId", resources), enumerateCollection: true));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queries the ARM cache and returns the cached resource that match the query specified.
|
||||
/// </summary>
|
||||
private async Task<ResponseWithContinuation<JObject[]>> GetResources()
|
||||
{
|
||||
string resourceId = this.Id ?? this.GetResourceId();
|
||||
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.PolicyAssignmentApiVersion : this.ApiVersion;
|
||||
|
||||
if (IsResourceGet(resourceId))
|
||||
{
|
||||
var resource = await this
|
||||
.GetResourcesClient()
|
||||
.GetResource<JObject>(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: null)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
ResponseWithContinuation<JObject[]> retVal;
|
||||
return resource.TryConvertTo(out retVal) && retVal.Value != null
|
||||
? retVal
|
||||
: new ResponseWithContinuation<JObject[]> { Value = resource.AsArray() };
|
||||
}
|
||||
else if (IsScopeLevelList(resourceId))//If only scope is given, list assignments call
|
||||
{
|
||||
string filter = "$filter=atScope()";
|
||||
return await this
|
||||
.GetResourcesClient()
|
||||
.ListObjectColleciton<JObject>(
|
||||
resourceCollectionId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: filter)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
else
|
||||
{
|
||||
string filter = string.IsNullOrEmpty(this.PolicyDefinitionId)
|
||||
? null
|
||||
: string.Format("$filter=policydefinitionid eq '{0}'", this.PolicyDefinitionId);
|
||||
|
||||
return await this
|
||||
.GetResourcesClient()
|
||||
.ListObjectColleciton<JObject>(
|
||||
resourceCollectionId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: filter)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if it is scope level policy assignment list call
|
||||
/// </summary>
|
||||
private bool IsScopeLevelList(string resourceId)
|
||||
{
|
||||
return (!string.IsNullOrEmpty(this.Scope) && string.IsNullOrEmpty(this.Name))
|
||||
|| (!string.IsNullOrEmpty(this.Scope) && string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if it is a single policy assignment get
|
||||
/// </summary>
|
||||
/// <param name="resourceId"></param>
|
||||
private bool IsResourceGet(string resourceId)
|
||||
{
|
||||
return (!string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.Scope))
|
||||
|| !string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id
|
||||
/// </summary>
|
||||
private string GetResourceId()
|
||||
{
|
||||
var subscriptionId = DefaultContext.Subscription.Id;
|
||||
if (string.IsNullOrEmpty(this.Name) && string.IsNullOrEmpty(this.Scope))
|
||||
{
|
||||
return string.Format("/subscriptions/{0}/providers/{1}",
|
||||
subscriptionId.ToString(),
|
||||
Constants.MicrosoftAuthorizationPolicyAssignmentType);
|
||||
}
|
||||
else if (string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.Scope))
|
||||
{
|
||||
return ResourceIdUtility.GetResourceId(
|
||||
resourceId: this.Scope,
|
||||
extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType,
|
||||
extensionResourceName: null);
|
||||
}
|
||||
return ResourceIdUtility.GetResourceId(
|
||||
resourceId: this.Scope,
|
||||
extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType,
|
||||
extensionResourceName: this.Name);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,138 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Management.Automation;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the policy definition.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Get, "AzureRmPolicyDefinition", DefaultParameterSetName = GetAzurePolicyDefinitionCmdlet.ParameterlessSet), OutputType(typeof(PSObject))]
|
||||
public class GetAzurePolicyDefinitionCmdlet : PolicyCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// The policy Id parameter set.
|
||||
/// </summary>
|
||||
internal const string PolicyDefinitionIdParameterSet = "GetByPolicyDefinitionId";
|
||||
|
||||
/// <summary>
|
||||
/// The policy name parameter set.
|
||||
/// </summary>
|
||||
internal const string PolicyDefinitionNameParameterSet = "GetByPolicyDefintionName";
|
||||
|
||||
/// <summary>
|
||||
/// The list all policy parameter set.
|
||||
/// </summary>
|
||||
internal const string ParameterlessSet = "GetAllPolicyDefinitions";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy definition name parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = GetAzurePolicyDefinitionCmdlet.PolicyDefinitionNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy definition name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy definition id parameter
|
||||
/// </summary>
|
||||
[Alias("ResourceId")]
|
||||
[Parameter(ParameterSetName = GetAzurePolicyDefinitionCmdlet.PolicyDefinitionIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy definition Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
|
||||
this.RunCmdlet();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Contains the cmdlet's execution logic.
|
||||
/// </summary>
|
||||
private void RunCmdlet()
|
||||
{
|
||||
PaginatedResponseHelper.ForEach(
|
||||
getFirstPage: () => this.GetResources(),
|
||||
getNextPage: nextLink => this.GetNextLink<JObject>(nextLink),
|
||||
cancellationToken: this.CancellationToken,
|
||||
action: resources => this.WriteObject(sendToPipeline: this.GetOutputObjects("PolicyDefinitionId", resources), enumerateCollection: true));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queries the ARM cache and returns the cached resource that match the query specified.
|
||||
/// </summary>
|
||||
private async Task<ResponseWithContinuation<JObject[]>> GetResources()
|
||||
{
|
||||
string resourceId = this.Id ?? this.GetResourceId();
|
||||
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.PolicyDefinitionApiVersion : this.ApiVersion;
|
||||
|
||||
if (!string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId)))
|
||||
{
|
||||
var resource = await this
|
||||
.GetResourcesClient()
|
||||
.GetResource<JObject>(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
ResponseWithContinuation<JObject[]> retVal;
|
||||
return resource.TryConvertTo(out retVal) && retVal.Value != null
|
||||
? retVal
|
||||
: new ResponseWithContinuation<JObject[]> { Value = resource.AsArray() };
|
||||
}
|
||||
else
|
||||
{
|
||||
return await this
|
||||
.GetResourcesClient()
|
||||
.ListObjectColleciton<JObject>(
|
||||
resourceCollectionId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id
|
||||
/// </summary>
|
||||
private string GetResourceId()
|
||||
{
|
||||
var subscriptionId = DefaultContext.Subscription.Id;
|
||||
if (string.IsNullOrEmpty(this.Name))
|
||||
{
|
||||
return string.Format("/subscriptions/{0}/providers/{1}",
|
||||
subscriptionId.ToString(),
|
||||
Constants.MicrosoftAuthorizationPolicyDefinitionType);
|
||||
}
|
||||
else
|
||||
{
|
||||
return string.Format("/subscriptions/{0}/providers/{1}/{2}",
|
||||
subscriptionId.ToString(),
|
||||
Constants.MicrosoftAuthorizationPolicyDefinitionType,
|
||||
this.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,138 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Management.Automation;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the policy set definition.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Get, "AzureRmPolicySetDefinition", DefaultParameterSetName = GetAzurePolicySetDefinitionCmdlet.ParameterlessSet), OutputType(typeof(PSObject))]
|
||||
public class GetAzurePolicySetDefinitionCmdlet : PolicyCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// The policy Id parameter set.
|
||||
/// </summary>
|
||||
internal const string PolicySetDefinitionIdParameterSet = "GetById";
|
||||
|
||||
/// <summary>
|
||||
/// The policy name parameter set.
|
||||
/// </summary>
|
||||
internal const string PolicySetDefinitionNameParameterSet = "GetByNameAndResourceGroup";
|
||||
|
||||
/// <summary>
|
||||
/// The list all policy parameter set.
|
||||
/// </summary>
|
||||
internal const string ParameterlessSet = "GetBySubscription";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy set definition name parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = GetAzurePolicySetDefinitionCmdlet.PolicySetDefinitionNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy set definition name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy set definition id parameter
|
||||
/// </summary>
|
||||
[Alias("ResourceId")]
|
||||
[Parameter(ParameterSetName = GetAzurePolicySetDefinitionCmdlet.PolicySetDefinitionIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy set definition Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
|
||||
this.RunCmdlet();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Contains the cmdlet's execution logic.
|
||||
/// </summary>
|
||||
private void RunCmdlet()
|
||||
{
|
||||
PaginatedResponseHelper.ForEach(
|
||||
getFirstPage: () => this.GetResources(),
|
||||
getNextPage: nextLink => this.GetNextLink<JObject>(nextLink),
|
||||
cancellationToken: this.CancellationToken,
|
||||
action: resources => this.WriteObject(sendToPipeline: this.GetOutputObjects("PolicySetDefinitionId", resources), enumerateCollection: true));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queries the ARM cache and returns the cached resource that match the query specified.
|
||||
/// </summary>
|
||||
private async Task<ResponseWithContinuation<JObject[]>> GetResources()
|
||||
{
|
||||
string resourceId = this.Id ?? this.GetResourceId();
|
||||
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.PolicySetDefintionApiVersion : this.ApiVersion;
|
||||
|
||||
if (!string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId)))
|
||||
{
|
||||
var resource = await this
|
||||
.GetResourcesClient()
|
||||
.GetResource<JObject>(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
ResponseWithContinuation<JObject[]> retVal;
|
||||
return resource.TryConvertTo(out retVal) && retVal.Value != null
|
||||
? retVal
|
||||
: new ResponseWithContinuation<JObject[]> { Value = resource.AsArray() };
|
||||
}
|
||||
else
|
||||
{
|
||||
return await this
|
||||
.GetResourcesClient()
|
||||
.ListObjectColleciton<JObject>(
|
||||
resourceCollectionId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value)
|
||||
.ConfigureAwait(continueOnCapturedContext: false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id
|
||||
/// </summary>
|
||||
private string GetResourceId()
|
||||
{
|
||||
var subscriptionId = DefaultContext.Subscription.Id;
|
||||
if (string.IsNullOrEmpty(this.Name))
|
||||
{
|
||||
return string.Format("/subscriptions/{0}/providers/{1}",
|
||||
subscriptionId.ToString(),
|
||||
Constants.MicrosoftAuthorizationPolicySetDefinitionType);
|
||||
}
|
||||
else
|
||||
{
|
||||
return string.Format("/subscriptions/{0}/providers/{1}/{2}",
|
||||
subscriptionId.ToString(),
|
||||
Constants.MicrosoftAuthorizationPolicySetDefinitionType,
|
||||
this.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,283 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.Azure.Commands.Common.Authentication;
|
||||
using Microsoft.WindowsAzure.Commands.Utilities.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Management.Automation;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Collections;
|
||||
using WindowsAzure.Commands.Common;
|
||||
using Commands.Common.Authentication.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a policy assignment.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.New, "AzureRmPolicyAssignment", DefaultParameterSetName = ParameterlessPolicyParameterSetName), OutputType(typeof(PSObject))]
|
||||
public class NewAzurePolicyAssignmentCmdlet : PolicyCmdletBase, IDynamicParameters
|
||||
{
|
||||
protected RuntimeDefinedParameterDictionary dynamicParameters = new RuntimeDefinedParameterDictionary();
|
||||
|
||||
protected const string PolicyParameterObjectParameterSetName = "CreateWithPolicyParameterObject";
|
||||
protected const string PolicyParameterStringParameterSetName = "CreateWithPolicyParameterString";
|
||||
protected const string PolicySetParameterObjectParameterSetName = "CreateWithPolicySetParameterObject";
|
||||
protected const string PolicySetParameterStringParameterSetName = "CreateWithPolicySetParameterString";
|
||||
protected const string ParameterlessPolicyParameterSetName = "CreateWithoutParameters";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment name parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment scope parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The scope for policy assignment.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Scope { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment not scopes parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The not scopes for policy assignment.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string[] NotScope { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment display name parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The display name for policy assignment.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string DisplayName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment description parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The description for policy assignment.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment policy definition parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy definition object.")]
|
||||
[Parameter(ParameterSetName = ParameterlessPolicyParameterSetName,
|
||||
Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy definition object.")]
|
||||
[Parameter(ParameterSetName = PolicyParameterObjectParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy definition object.")]
|
||||
[Parameter(ParameterSetName = PolicyParameterStringParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy definition object.")]
|
||||
public PSObject PolicyDefinition { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment policy set definition parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy set definition object.")]
|
||||
[Parameter(ParameterSetName = ParameterlessPolicyParameterSetName,
|
||||
Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy set definition object.")]
|
||||
[Parameter(ParameterSetName = PolicySetParameterObjectParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy set definition object.")]
|
||||
[Parameter(ParameterSetName = PolicySetParameterStringParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy set definition object.")]
|
||||
public PSObject PolicySetDefinition { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment policy parameter object.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = PolicyParameterObjectParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = false, HelpMessage = "The policy parameter object.")]
|
||||
[Parameter(ParameterSetName = PolicySetParameterObjectParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = false, HelpMessage = "The policy parameter object.")]
|
||||
public Hashtable PolicyParameterObject { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment policy parameter file path or policy parameter string.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = PolicyParameterStringParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy parameter file path or policy parameter string.")]
|
||||
[Parameter(ParameterSetName = PolicySetParameterStringParameterSetName,
|
||||
Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy parameter file path or policy parameter string.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string PolicyParameter { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy sku object.
|
||||
/// </summary>
|
||||
[Alias("SkuObject")]
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents sku properties. Defaults to Free Sku: Name = A0, Tier = Free")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public Hashtable Sku { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
if(this.PolicyDefinition !=null && this.PolicySetDefinition !=null)
|
||||
{
|
||||
throw new PSInvalidOperationException("Only one of PolicyDefinition or PolicySetDefinition can be specified, not both.");
|
||||
}
|
||||
if (this.PolicyDefinition !=null && this.PolicyDefinition.Properties["policyDefinitionId"] == null)
|
||||
{
|
||||
throw new PSInvalidOperationException("The supplied PolicyDefinition object is invalid.");
|
||||
}
|
||||
if (this.PolicySetDefinition != null && this.PolicySetDefinition.Properties["policySetDefinitionId"] == null)
|
||||
{
|
||||
throw new PSInvalidOperationException("The supplied PolicySetDefinition object is invalid.");
|
||||
}
|
||||
string resourceId = GetResourceId();
|
||||
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.PolicyAssignmentApiVersion : this.ApiVersion;
|
||||
|
||||
var operationResult = this.GetResourcesClient()
|
||||
.PutResource(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
resource: this.GetResource(),
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: null)
|
||||
.Result;
|
||||
|
||||
var managementUri = this.GetResourcesClient()
|
||||
.GetResourceManagementRequestUri(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
odataQuery: null);
|
||||
|
||||
var activity = string.Format("PUT {0}", managementUri.PathAndQuery);
|
||||
var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true)
|
||||
.WaitOnOperation(operationResult: operationResult);
|
||||
|
||||
this.WriteObject(this.GetOutputObjects("PolicyAssignmentId", JObject.Parse(result)), enumerateCollection: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id
|
||||
/// </summary>
|
||||
private string GetResourceId()
|
||||
{
|
||||
return ResourceIdUtility.GetResourceId(
|
||||
resourceId: this.Scope,
|
||||
extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType,
|
||||
extensionResourceName: this.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs the resource
|
||||
/// </summary>
|
||||
private JToken GetResource()
|
||||
{
|
||||
var policyassignmentObject = new PolicyAssignment
|
||||
{
|
||||
Name = this.Name,
|
||||
Sku = this.Sku == null? new PolicySku { Name = "A0", Tier = "Free" } : this.Sku.ToDictionary(addValueLayer: false).ToJson().FromJson<PolicySku>(),
|
||||
Properties = new PolicyAssignmentProperties
|
||||
{
|
||||
DisplayName = this.DisplayName ?? null,
|
||||
Description = this.Description ?? null,
|
||||
Scope = this.Scope,
|
||||
NotScopes = this.NotScope ?? null,
|
||||
Parameters = this.GetParameters()
|
||||
}
|
||||
};
|
||||
|
||||
if(this.PolicyDefinition != null)
|
||||
{
|
||||
policyassignmentObject.Properties.PolicyDefinitionId = this.PolicyDefinition.Properties["policyDefinitionId"].Value.ToString();
|
||||
}
|
||||
else if(this.PolicySetDefinition != null)
|
||||
{
|
||||
policyassignmentObject.Properties.PolicyDefinitionId = this.PolicySetDefinition.Properties["policySetDefinitionId"].Value.ToString();
|
||||
}
|
||||
|
||||
return policyassignmentObject.ToJToken();
|
||||
}
|
||||
|
||||
object IDynamicParameters.GetDynamicParameters()
|
||||
{
|
||||
PSObject parameters = null;
|
||||
if (this.PolicyDefinition != null)
|
||||
{
|
||||
parameters = this.PolicyDefinition.GetPSObjectProperty("Properties.parameters") as PSObject;
|
||||
}
|
||||
else if(this.PolicySetDefinition != null)
|
||||
{
|
||||
parameters = this.PolicySetDefinition.GetPSObjectProperty("Properties.parameters") as PSObject;
|
||||
}
|
||||
if (parameters != null)
|
||||
{
|
||||
foreach (var param in parameters.Properties)
|
||||
{
|
||||
var type = (param.Value as PSObject).Properties["type"];
|
||||
var typeString = type != null ? type.Value.ToString() : string.Empty;
|
||||
var description = (param.Value as PSObject).GetPSObjectProperty("metadata.description");
|
||||
var helpString = description != null ? description.ToString() : string.Format("The {0} policy parameter.", param.Name);
|
||||
var dp = new RuntimeDefinedParameter
|
||||
{
|
||||
Name = param.Name,
|
||||
ParameterType = typeString.Equals("array", StringComparison.OrdinalIgnoreCase) ? typeof(string[]) : typeof(string)
|
||||
};
|
||||
dp.Attributes.Add(new ParameterAttribute
|
||||
{
|
||||
ParameterSetName = ParameterlessPolicyParameterSetName,
|
||||
Mandatory = true,
|
||||
ValueFromPipelineByPropertyName = false,
|
||||
HelpMessage = helpString
|
||||
});
|
||||
this.dynamicParameters.Add(param.Name, dp);
|
||||
}
|
||||
}
|
||||
|
||||
RegisterDynamicParameters(dynamicParameters);
|
||||
|
||||
return this.dynamicParameters;
|
||||
}
|
||||
|
||||
private JObject GetParameters()
|
||||
{
|
||||
// Load parameters from local file or literal
|
||||
if (this.PolicyParameter != null)
|
||||
{
|
||||
string policyParameterFilePath = this.TryResolvePath(this.PolicyParameter);
|
||||
return FileUtilities.DataStore.FileExists(policyParameterFilePath)
|
||||
? JObject.Parse(FileUtilities.DataStore.ReadFileAsText(policyParameterFilePath))
|
||||
: JObject.Parse(this.PolicyParameter);
|
||||
}
|
||||
|
||||
// Load from PS object
|
||||
if (this.PolicyParameterObject != null)
|
||||
{
|
||||
return this.PolicyParameterObject.ToJObjectWithValue();
|
||||
}
|
||||
|
||||
// Load dynamic parameters
|
||||
var parameters = PowerShellUtilities.GetUsedDynamicParameters(AsJobDynamicParameters, MyInvocation);
|
||||
if (parameters.Count() > 0)
|
||||
{
|
||||
return MyInvocation.BoundParameters.ToJObjectWithValue(parameters.Select(p => p.Name));
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,149 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
using Microsoft.Azure.Commands.Common.Authentication;
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Commands.Common.Authentication.Abstractions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.WindowsAzure.Commands.Utilities.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.IO;
|
||||
using System.Management.Automation;
|
||||
using WindowsAzure.Commands.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the policy definition.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.New, "AzureRmPolicyDefinition"), OutputType(typeof(PSObject))]
|
||||
public class NewAzurePolicyDefinitionCmdlet : PolicyCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the policy definition name parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy definition name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy definition display name parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The display name for policy definition.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string DisplayName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy definition description parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The description for policy definition.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy definition policy rule parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The rule for policy definition. This can either be a path to a file name or uri containing the rule, or the rule as string.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Policy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy definition metadata parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The metadata for policy definition. This can either be a path to a file name containing the metadata, or the metadata as string.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Metadata { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy definition parameters parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The parameters declaration for policy definition. This can either be a path to a file name or uri containing the parameters declaration, or the parameters declaration as string.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Parameter { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy definition mode parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The mode of the policy definition.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public PolicyDefinitionMode? Mode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
string resourceId = GetResourceId();
|
||||
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.PolicyDefinitionApiVersion : this.ApiVersion;
|
||||
|
||||
var operationResult = this.GetResourcesClient()
|
||||
.PutResource(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
resource: this.GetResource(),
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: null)
|
||||
.Result;
|
||||
|
||||
var managementUri = this.GetResourcesClient()
|
||||
.GetResourceManagementRequestUri(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
odataQuery: null);
|
||||
|
||||
var activity = string.Format("PUT {0}", managementUri.PathAndQuery);
|
||||
var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true)
|
||||
.WaitOnOperation(operationResult: operationResult);
|
||||
this.WriteObject(this.GetOutputObjects("PolicyDefinitionId", JObject.Parse(result)), enumerateCollection: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id
|
||||
/// </summary>
|
||||
private string GetResourceId()
|
||||
{
|
||||
var subscriptionId = DefaultContext.Subscription.Id;
|
||||
return string.Format("/subscriptions/{0}/providers/{1}/{2}",
|
||||
subscriptionId.ToString(),
|
||||
Constants.MicrosoftAuthorizationPolicyDefinitionType,
|
||||
this.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs the resource
|
||||
/// </summary>
|
||||
private JToken GetResource()
|
||||
{
|
||||
var policyDefinitionObject = new PolicyDefinition
|
||||
{
|
||||
Name = this.Name,
|
||||
Properties = new PolicyDefinitionProperties
|
||||
{
|
||||
Description = this.Description ?? null,
|
||||
DisplayName = this.DisplayName ?? null,
|
||||
PolicyRule = JObject.Parse(this.GetObjectFromParameter(this.Policy).ToString()),
|
||||
Metadata = this.Metadata == null ? null : JObject.Parse(this.GetObjectFromParameter(this.Metadata).ToString()),
|
||||
Parameters = this.Parameter == null ? null : JObject.Parse(this.GetObjectFromParameter(this.Parameter).ToString()),
|
||||
Mode = this.Mode.HasValue ? this.Mode : PolicyDefinitionMode.All
|
||||
}
|
||||
};
|
||||
|
||||
return policyDefinitionObject.ToJToken();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,142 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.WindowsAzure.Commands.Utilities.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.IO;
|
||||
using System.Management.Automation;
|
||||
using WindowsAzure.Commands.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the policy definition.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.New, "AzureRmPolicySetDefinition", SupportsShouldProcess = true), OutputType(typeof(PSObject))]
|
||||
public class NewAzurePolicySetDefinitionCmdlet : PolicyCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the policy set definition name parameter.
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy set definition name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy definition display name parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The display name for policy set definition.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string DisplayName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy definition description parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The description for policy set definition.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy set definition metadata parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The metadata for policy set definition. This can either be a path to a file name containing the metadata, or the metadata as string.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Metadata { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy definition parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy definition. This can either be a path to a file name containing the policy definitions, or the policy set definition as string.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string PolicyDefinition { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy definition parameters parameter
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The parameters declaration for policy set definition. This can either be a path to a file name containing the parameters declaration, or the parameters declaration as string.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Parameter { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
|
||||
if(this.ShouldProcess(this.Name, "Create Policy Set Definition"))
|
||||
{
|
||||
string resourceId = GetResourceId();
|
||||
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.PolicySetDefintionApiVersion : this.ApiVersion;
|
||||
|
||||
var operationResult = this.GetResourcesClient()
|
||||
.PutResource(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
resource: this.GetResource(),
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: null)
|
||||
.Result;
|
||||
|
||||
var managementUri = this.GetResourcesClient()
|
||||
.GetResourceManagementRequestUri(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
odataQuery: null);
|
||||
|
||||
var activity = string.Format("PUT {0}", managementUri.PathAndQuery);
|
||||
var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true)
|
||||
.WaitOnOperation(operationResult: operationResult);
|
||||
this.WriteObject(this.GetOutputObjects("PolicySetDefinitionId", JObject.Parse(result)), enumerateCollection: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id
|
||||
/// </summary>
|
||||
private string GetResourceId()
|
||||
{
|
||||
var subscriptionId = DefaultContext.Subscription.Id;
|
||||
return string.Format("/subscriptions/{0}/providers/{1}/{2}",
|
||||
subscriptionId.ToString(),
|
||||
Constants.MicrosoftAuthorizationPolicySetDefinitionType,
|
||||
this.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs the resource
|
||||
/// </summary>
|
||||
private JToken GetResource()
|
||||
{
|
||||
var policySetDefinitionObject = new PolicySetDefinition
|
||||
{
|
||||
Name = this.Name,
|
||||
Properties = new PolicySetDefinitionProperties
|
||||
{
|
||||
Description = this.Description ?? null,
|
||||
DisplayName = this.DisplayName ?? null,
|
||||
PolicyDefinitions = JArray.Parse(this.GetObjectFromParameter(this.PolicyDefinition).ToString()),
|
||||
Metadata = this.Metadata == null ? null : JObject.Parse(this.GetObjectFromParameter(this.Metadata).ToString()),
|
||||
Parameters = this.Parameter == null ? null : JObject.Parse(this.GetObjectFromParameter(this.Parameter).ToString())
|
||||
}
|
||||
};
|
||||
|
||||
return policySetDefinitionObject.ToJToken();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,110 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
|
||||
using Microsoft.Azure.Commands.ResourceManager.Common;
|
||||
using Microsoft.WindowsAzure.Commands.Common;
|
||||
using Microsoft.WindowsAzure.Commands.Utilities.Common;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using ProjectResources = Microsoft.Azure.Commands.ResourceManager.Cmdlets.Properties.Resources;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Management.Automation;
|
||||
using System.Threading.Tasks;
|
||||
using Commands.Common.Authentication.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for policy cmdlets.
|
||||
/// </summary>
|
||||
public abstract class PolicyCmdletBase : ResourceManagerCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts the resource object to specified resource type object.
|
||||
/// </summary>
|
||||
/// <param name="resources">The policy definition resource object.</param>
|
||||
protected PSObject[] GetOutputObjects(string resourceType, params JToken[] resources)
|
||||
{
|
||||
return resources
|
||||
.CoalesceEnumerable()
|
||||
.Where(resource => resource != null)
|
||||
.SelectArray(resource =>
|
||||
{
|
||||
var psobject = resource.ToResource().ToPsObject();
|
||||
psobject.Properties.Add(new PSNoteProperty(resourceType, psobject.Properties["ResourceId"].Value));
|
||||
return psobject;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the next set of resources using the <paramref name="nextLink"/>
|
||||
/// </summary>
|
||||
/// <param name="nextLink">The next link.</param>
|
||||
protected Task<ResponseWithContinuation<TType[]>> GetNextLink<TType>(string nextLink)
|
||||
{
|
||||
return this
|
||||
.GetResourcesClient()
|
||||
.ListNextBatch<TType>(nextLink: nextLink, cancellationToken: this.CancellationToken.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the JToken object from parameter
|
||||
/// </summary>
|
||||
protected JToken GetObjectFromParameter(string parameter)
|
||||
{
|
||||
Uri outUri = null;
|
||||
if (Uri.TryCreate(parameter, UriKind.Absolute, out outUri))
|
||||
{
|
||||
if(outUri.Scheme == Uri.UriSchemeFile)
|
||||
{
|
||||
string filePath = this.TryResolvePath(parameter);
|
||||
if(File.Exists(filePath))
|
||||
{
|
||||
return JToken.FromObject(FileUtilities.DataStore.ReadFileAsText(filePath));
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new PSInvalidOperationException(string.Format(ProjectResources.InvalidFilePath, parameter));
|
||||
}
|
||||
}
|
||||
else if (outUri.Scheme != Uri.UriSchemeHttp && outUri.Scheme != Uri.UriSchemeHttps)
|
||||
{
|
||||
throw new PSInvalidOperationException(ProjectResources.InvalidUriScheme);
|
||||
}
|
||||
else if (!Uri.IsWellFormedUriString(outUri.AbsoluteUri, UriKind.Absolute))
|
||||
{
|
||||
throw new PSInvalidOperationException(string.Format(ProjectResources.InvalidUriString, parameter));
|
||||
}
|
||||
else
|
||||
{
|
||||
string contents = GeneralUtilities.DownloadFile(outUri.AbsoluteUri);
|
||||
if(string.IsNullOrEmpty(contents))
|
||||
{
|
||||
throw new PSInvalidOperationException(string.Format(ProjectResources.InvalidUriContent, parameter));
|
||||
}
|
||||
return JToken.FromObject(contents);
|
||||
}
|
||||
}
|
||||
|
||||
//for non absolute file paths
|
||||
string path = this.TryResolvePath(parameter);
|
||||
|
||||
return File.Exists(path)
|
||||
? JToken.FromObject(FileUtilities.DataStore.ReadFileAsText(path))
|
||||
: JToken.FromObject(parameter);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,120 @@
|
|||
// ----------------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright Microsoft Corporation
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ----------------------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
|
||||
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
|
||||
{
|
||||
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
|
||||
using System.Management.Automation;
|
||||
|
||||
/// <summary>
|
||||
/// Removes the policy assignment.
|
||||
/// </summary>
|
||||
[Cmdlet(VerbsCommon.Remove, "AzureRmPolicyAssignment", SupportsShouldProcess = true,
|
||||
DefaultParameterSetName = RemoveAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet),
|
||||
OutputType(typeof(bool))]
|
||||
public class RemoveAzurePolicyAssignmentCmdlet : PolicyCmdletBase
|
||||
{
|
||||
/// <summary>
|
||||
/// The policy assignment Id parameter set.
|
||||
/// </summary>
|
||||
internal const string PolicyAssignmentIdParameterSet = "RemoveByPolicyAssignmentId";
|
||||
|
||||
/// <summary>
|
||||
/// The policy assignment name parameter set.
|
||||
/// </summary>
|
||||
internal const string PolicyAssignmentNameParameterSet = "RemoveByPolicyAssignmentName";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment name parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = RemoveAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment scope parameter.
|
||||
/// </summary>
|
||||
[Parameter(ParameterSetName = RemoveAzurePolicyAssignmentCmdlet.PolicyAssignmentNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The policy assignment name.")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Scope { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the policy assignment id parameter
|
||||
/// </summary>
|
||||
[Alias("ResourceId")]
|
||||
[Parameter(ParameterSetName = RemoveAzurePolicyAssignmentCmdlet.PolicyAssignmentIdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The fully qualified policy assignment Id, including the subscription. e.g. /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}")]
|
||||
[ValidateNotNullOrEmpty]
|
||||
public string Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the cmdlet.
|
||||
/// </summary>
|
||||
protected override void OnProcessRecord()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
|
||||
this.RunCmdlet();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Contains the cmdlet's execution logic.
|
||||
/// </summary>
|
||||
private void RunCmdlet()
|
||||
{
|
||||
base.OnProcessRecord();
|
||||
string resourceId = this.Id ?? this.GetResourceId();
|
||||
var apiVersion = string.IsNullOrWhiteSpace(this.ApiVersion) ? Constants.PolicyAssignmentApiVersion : this.ApiVersion;
|
||||
|
||||
this.ConfirmAction(
|
||||
"Deleting the policy assignment...",
|
||||
resourceId,
|
||||
() =>
|
||||
{
|
||||
var operationResult = this.GetResourcesClient()
|
||||
.DeleteResource(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
cancellationToken: this.CancellationToken.Value,
|
||||
odataQuery: null)
|
||||
.Result;
|
||||
|
||||
var managementUri = this.GetResourcesClient()
|
||||
.GetResourceManagementRequestUri(
|
||||
resourceId: resourceId,
|
||||
apiVersion: apiVersion,
|
||||
odataQuery: null);
|
||||
|
||||
var activity = string.Format("DELETE {0}", managementUri.PathAndQuery);
|
||||
|
||||
this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false)
|
||||
.WaitOnOperation(operationResult: operationResult);
|
||||
|
||||
this.WriteObject(true);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource Id from the supplied PowerShell parameters.
|
||||
/// </summary>
|
||||
protected string GetResourceId()
|
||||
{
|
||||
return ResourceIdUtility.GetResourceId(
|
||||
resourceId: this.Scope,
|
||||
extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType,
|
||||
extensionResourceName: this.Name);
|
||||
}
|
||||
}
|
||||
}
|
Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше
Загрузка…
Ссылка в новой задаче